http://stackoverflow.com/comment/92248704
has text: Yes, integers have to be in that specific order.
comment on: http://stackoverflow.com/q/52656381
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92395081
score: 0
type: AnswerComment
has text: I've updated my answer with how to do it alphabetically.
type: Comment
comment on: http://stackoverflow.com/a/52734081

http://stackoverflow.com/a/52711999
downvote count: 0
has body: First off, to make things clear, the longest common subsequence problem is not the same as the longest common substring problem. What you're trying to solve is the latter; better not to confuse the two. Secondly, your else branches are not aligned under the appropriate if conditions. Whenever the strings match X[i] == Y[j], we set the matrix element to 1 if the index i or j is 0 since i-1 or j-1 at 0 gives -1 (unfortunately, this is also the index for last item in Python) which is not what we want, otherwise we increment for higher indices i, j > 1. Thirdly, your looping should start at 0 not 1 since we start from the first characters in the strings which are at indices 0: def compute_lcs(X, Y): m = len(X) n = len(Y) # An (m) times (n) matrix matrix = [[0] * n for _ in range(m)] for i in range(0, m): for j in range(0, n): if X[i] == Y[j]: if i == 0 or j == 0: matrix[i][j] = 1 else: matrix[i][j] = matrix[i-1][j-1]+1 else: matrix[i][j] = 0 return matrix To get the exact matrix shown in the expected output, you should swap the order of the arguments or transpose the matrix before printing. Note however that these are not necessary (swapping or transposing) and only serve for formatting purposes: b = compute_lcs('TACGCTGGA', 'AACTGGCAG') for y in b: print (y) [0, 0, 0, 1, 0, 0, 0, 0, 0] [1, 1, 0, 0, 0, 0, 0, 1, 0] [0, 0, 2, 0, 0, 0, 1, 0, 0] [0, 0, 0, 0, 1, 1, 0, 0, 1] [0, 0, 1, 0, 0, 0, 2, 0, 0] [0, 0, 0, 2, 0, 0, 0, 0, 0] [0, 0, 0, 0, 3, 1, 0, 0, 1] [0, 0, 0, 0, 1, 4, 0, 0, 1] [1, 1, 0, 0, 0, 0, 0, 1, 0]
upvote count: 3
has comment: http://stackoverflow.com/comment/92350034
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52711864
answers question: http://stackoverflow.com/q/52711864
type: Answer
score: 3

http://stackoverflow.com/a/52594079
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52593926
has body: use csv dictreader and then filter out specific rows and columns import csv data = [] with open('names.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: data.append(row) colnames = ['col1', 'col2'] for i in range(1000): print(data[i][colnames[0]], data[i][colnames[1]])

http://stackoverflow.com/comment/93254795
type: QuestionComment
type: Comment
score: 0
has text: The problem is fairly simple. It's correct to give one two-pound coin back, but you're not done when you have done that. You should then check what the next coin is to give back. (Which may be another two-pound coin)
comment on: http://stackoverflow.com/q/52706139

http://stackoverflow.com/a/52653641
has body: I would parse the yaml file into a dictionary, and the edit the field and write the dictionary back out to yaml. See this question for discussion on parsing yaml in python How can I parse a YAML file in Python but I think you would end up with something like this. from ruamel.yaml import YAML from io import StringIO yaml=YAML(typ='safe') yaml.default_flow_style = False #Parse from string myConfig = yaml.load(doc) #Example replacement code for task in myConfig["tasks"]: if myConfig["tasks"][task]["details"]["args"]["template"]["name"] == "&amp;startup": myConfig["tasks"][task]["details"]["args"]["template"]["name"] = "new value" #Convert back to string buf = StringIO() yaml.dump(myConfig, buf) updatedYml = buf.getvalue()
has comment: http://stackoverflow.com/comment/92239028
answers question: http://stackoverflow.com/q/52653523
upvote count: 2
has comment: http://stackoverflow.com/comment/92239462
score: 2
has comment: http://stackoverflow.com/comment/92239752
has comment: http://stackoverflow.com/comment/92239174
downvote count: 0
has comment: http://stackoverflow.com/comment/92259864
type: Answer
has comment: http://stackoverflow.com/comment/92238883

http://stackoverflow.com/comment/92135094
has text: @Jodast: No, it doesn't give ten digits. "The first line contains an integer, , the number of test cases. Subsequent lines each contain an integer, denoting the number of cycles for that test case. 1 <= t <=10; 0 <= n <= 60"
comment on: http://stackoverflow.com/q/52600181
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92417890
has text: Or add your complete error stacktrace, so that we can figure out which line of code raises the error.
comment on: http://stackoverflow.com/q/52745994
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52605869
has answer: http://stackoverflow.com/a/52605991
accepted answer: http://stackoverflow.com/a/52605947
type: Question
answer count: 2
downvote count: 0
has title: Pagination does not work after changing queryset in get_context_data
has answer: http://stackoverflow.com/a/52605947
tagged with: python
favorite count: 0
upvote count: 2
has body: Pagination works ok until I add reverse arg to QS for ordering queryset in reverse mode. After it pagination is broke. I can use get() function and paginate it there, but I think that for this issue should be better solution. Thanks model.py: class Log(models.Model): user = models.ForeignKey('auth.User') comment = models.CharField() date_add = models.DateTimeField() class Meta: ordering = ['-date_add'] view.py: class LogView(ListView): model = UserLog template_name = 'log.html' context_object_name = 'log_list' paginate_by = 13 def get_queryset(self): return Log.objects.filter(user=self.request.user).all() def get_context_data(self, *, object_list=None, **kwargs): context = super(LogView, self).get_context_data(**kwargs) if 'reverse' in self.request.GET: context['log_list'] = Log.objects.filter(user=self.request.user).all().order_by('date_add') return context
tagged with: django
possible better answer: http://stackoverflow.com/a/52605991
has comment: http://stackoverflow.com/comment/92145838
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92145856
score: 2

http://stackoverflow.com/q/52634009
has answer: http://stackoverflow.com/a/52655013
accepted answer: http://stackoverflow.com/a/52655013
has comment: http://stackoverflow.com/comment/92201578
favorite count: 0
has title: OpenCV Python Scripts Mac "aborts"
upvote count: 5
has answer: http://stackoverflow.com/a/61661601
has answer: http://stackoverflow.com/a/54544653
tagged with: python
answer count: 4
tagged with: opencv
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/92203085
has comment: http://stackoverflow.com/comment/92204314
has comment: http://stackoverflow.com/comment/92205238
type: Question
score: 5
has comment: http://stackoverflow.com/comment/92206822
has body: So I'm just trying to run the basic OpenCV program import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) # Display the resulting frame cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() But for some reason when I try to run it (with python 2 or 3) I get this weird abort statement [1] 74309 abort python3 index.py (I'm guessing the 5 digit number is the PID) However, it does work if I pass in a path to an already existing video in the VideoCapture function. I am a beginner in all of this so I'm not really sure what the problem is Thanks :)
tagged with: macos-mojave
possible better answer: http://stackoverflow.com/a/54544653
has answer: http://stackoverflow.com/a/60855528

http://stackoverflow.com/q/52713859
has comment: http://stackoverflow.com/comment/92353727
answer count: 2
has comment: http://stackoverflow.com/comment/92353363
tagged with: python
has answer: http://stackoverflow.com/a/52714045
tagged with: list
has answer: http://stackoverflow.com/a/52713975
score: 0
has title: Converting sqlite3 records to list
type: UnansweredQuestion
tagged with: tuples
has body: I trying to convert sqlite3 records to list with the code below but the result is output this way [[1000], [1199], [1400], [1213], [1500], [1800], [1308]] with the code below but i want the result to display as: [1000, 1199, 1400, 1213, 1500, 1800, 1308] with the list removed from the numbers in the list conn = sqlite3.connect("TEST1.db") cur = conn.cursor() cur.execute("SELECT POINT FROM loyalty") rows = cur.fetchall() result = [list(i) for i in rows] print(result) I tried to iterate over the result this way for row in rows: print(list(row)) and it outputs this way [1000] [1199] [1400] [1213] [1500] [1800] [1308]
type: Question
tagged with: sqlite
has comment: http://stackoverflow.com/comment/92353269

http://stackoverflow.com/comment/92348945
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52711419
has text: Just put this text in the docstring: _"If user_names is passed, it overrides the the user names from the user_holdings"_. And yes, I would make the data in `user_names` _stronger_, because it is more explicitly setting the names. I would also replace `**kwargs` with `user_names=None`.

http://stackoverflow.com/q/52600654
has comment: http://stackoverflow.com/comment/92136661
has title: Why isn't selenium clicking a button in python?
type: Question
has comment: http://stackoverflow.com/comment/92135920
has answer: http://stackoverflow.com/a/52609946
accepted answer: http://stackoverflow.com/a/52609946
answer count: 1
score: 0
has body: I am using the xpath selector for the button itself and selenium gives me an error selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ember1355"]/button"} when I try to click. What I am trying to do is use selenium to connect with people in linkedin. When I search for a specific term, then I want to pull out all the profiles that say "Connect" and click on the each button. The html is Connect and my code is: if each.find('div', class_='search-result__actions').find('div').text.strip() == "Connect": id = each.find('div', class_='search-result__actions').find('div')['id'] id = '//*[@id="'+id+'"]' print(id) #this is where the code isn't working driver.find_element_by_xpath('//*[@id="ember1355"]/button').click()
tagged with: python
tagged with: selenium
type: AnsweredQuestion

python-3.x
tags question: http://stackoverflow.com/q/52639892
tags question: http://stackoverflow.com/q/52721158
tags question: http://stackoverflow.com/q/52725539
tags question: http://stackoverflow.com/q/52665955
tags question: http://stackoverflow.com/q/52621207
tags question: http://stackoverflow.com/q/52617401
tags question: http://stackoverflow.com/q/52640287
tags question: http://stackoverflow.com/q/52651519
tags question: http://stackoverflow.com/q/52742217
tags question: http://stackoverflow.com/q/52686600
tags question: http://stackoverflow.com/q/52619153
tags question: http://stackoverflow.com/q/52731437
tags question: http://stackoverflow.com/q/52733653
tags question: http://stackoverflow.com/q/52730982
tags question: http://stackoverflow.com/q/52744622
tags question: http://stackoverflow.com/q/52694057
tags question: http://stackoverflow.com/q/52732162
tags question: http://stackoverflow.com/q/52743399
tags question: http://stackoverflow.com/q/52684944
tags question: http://stackoverflow.com/q/52603890
tags question: http://stackoverflow.com/q/52672847
tags question: http://stackoverflow.com/q/52597760
tags question: http://stackoverflow.com/q/52613494
tags question: http://stackoverflow.com/q/52655656
tags question: http://stackoverflow.com/q/52621583
tags question: http://stackoverflow.com/q/52591542
tags question: http://stackoverflow.com/q/52718723
tags question: http://stackoverflow.com/q/52645253
tags question: http://stackoverflow.com/q/52631029
tags question: http://stackoverflow.com/q/52600888
tags question: http://stackoverflow.com/q/52620378
tags question: http://stackoverflow.com/q/52731884
tags question: http://stackoverflow.com/q/52744692
tags question: http://stackoverflow.com/q/52695114
tags question: http://stackoverflow.com/q/52715049
tags question: http://stackoverflow.com/q/52671451
tags question: http://stackoverflow.com/q/52673975
tags question: http://stackoverflow.com/q/52697446
tags question: http://stackoverflow.com/q/52658375
tags question: http://stackoverflow.com/q/52679038
tags question: http://stackoverflow.com/q/52692700
tags question: http://stackoverflow.com/q/52683744
tags question: http://stackoverflow.com/q/52637362
tags question: http://stackoverflow.com/q/52730430
tags question: http://stackoverflow.com/q/52709800
tags question: http://stackoverflow.com/q/52629661
tags question: http://stackoverflow.com/q/52681765
tags question: http://stackoverflow.com/q/52688278
tags question: http://stackoverflow.com/q/52590752
tags question: http://stackoverflow.com/q/52654043
tags question: http://stackoverflow.com/q/52661275
tags question: http://stackoverflow.com/q/52689200
tags question: http://stackoverflow.com/q/52592037
tags question: http://stackoverflow.com/q/52734346
tags question: http://stackoverflow.com/q/52620805
tags question: http://stackoverflow.com/q/52630920
tags question: http://stackoverflow.com/q/52594382
tags question: http://stackoverflow.com/q/52618146
tags question: http://stackoverflow.com/q/52616685
tags question: http://stackoverflow.com/q/52637488
tags question: http://stackoverflow.com/q/52727207
tags question: http://stackoverflow.com/q/52654302
tags question: http://stackoverflow.com/q/52732174
tags question: http://stackoverflow.com/q/52630158
tags question: http://stackoverflow.com/q/52743305
tags question: http://stackoverflow.com/q/52731546
tags question: http://stackoverflow.com/q/52689004
tags question: http://stackoverflow.com/q/52626888
tags question: http://stackoverflow.com/q/52643184
tags question: http://stackoverflow.com/q/52682861
tags question: http://stackoverflow.com/q/52664005
tags question: http://stackoverflow.com/q/52649343
tags question: http://stackoverflow.com/q/52738208
tags question: http://stackoverflow.com/q/52658729
tags question: http://stackoverflow.com/q/52618450
tags question: http://stackoverflow.com/q/52661564
tags question: http://stackoverflow.com/q/52697394
tags question: http://stackoverflow.com/q/52719472
tags question: http://stackoverflow.com/q/52601526
tags question: http://stackoverflow.com/q/52652634

http://stackoverflow.com/a/64692697
type: Answer
answers question: http://stackoverflow.com/q/52591190
score: 0
has body: There are various ways by which we can extract the emojis from a string in Python. On of the prominent is by using the emoji library. If you are processing a file then make sure that you are read the file with encoding utf-8(while saving utf-8-sig too) Here will show how to list all the emoji present in the string along with the no. of emojis in the string and type of each emoji Code: #import required libraries import emoji from emoji import UNICODE_EMOJI #getting all emojis as lists all_emojis = list(UNICODE_EMOJI.keys()) #defining sentence sentence = "schuld van de sossen SP.a: wij hebben niks gedaan Groen: we gaan energie VERBIEDEN!" #getting Emoji Count emoji_count = sum([sentence.count(emoj) for emoj in UNICODE_EMOJI]) #listing all Emojis listed_emojis = ','.join(re.findall(f"[{''.join(all_emojis)}]", str(sentence))) #listing all Emoji Types emoji_types = ','.join([UNICODE_EMOJI[detect_emoji].upper()[1:-1] for detect_emoji in listed_emojis.split(',')]) #Displaying Sentence, Emoji Count, Emojis and Emoji Types print(f"Sentence: {sentence}\nListed Emojis: {listed_emojis}\nCount: {emoji_count}\nEmoji Types: {emoji_types}") Output: Sentence: schuld van de sossen SP.a: wij hebben niks gedaan Groen: we gaan energie VERBIEDEN! Listed Emojis: , Count: 2 Emoji Types: POUTING_FACE,SLEEPING_FACE I hope this will helpful.. If anyone have query please write here. I will try to fix.. :)

http://stackoverflow.com/a/74054984
answers question: http://stackoverflow.com/q/52657223
score: 1
downvote count: 0
has body: This is likely a result of an unwanted float to string conversion. To repair it, just reverse it by adding string-to-float conversion (assuming data is convertible to a number) using float or np.float64: np.isnan(float(str(np.nan))) True or np.isnan(float(str("nan"))) True rather than: np.isnan(str(np.nan)) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In [164], line 1 ----> 1 np.isnan(str(np.nan)) TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Note that if your data is NOT convertible to numbers (floats), you need to use a string-compatible function such as pd.isna instead of np.isnan.
type: Answer
upvote count: 1

http://stackoverflow.com/a/52646516
answers question: http://stackoverflow.com/q/52646107
type: Answer
has body: You can create unique ids for each of your items that you will be displaying. Each td and its corresponding button will have a trailing digit in the id that can be used to grab the desired text on the button click. Also, It is simpler in this case to use jquery with ajax to communicate with the backend: In your HTML: flights.html {%for row in data%} {{row.name}} Select {%endfor%} Then, in the app: import flask, typing app = flask.Flask(__name__) class Flight(typing.NamedTuple): id:int flight:str name:str @app.route('/', methods=['GET']) def home(): d = [["A100", "oranges"], ["A101", "apples"]] return flask.render_template('flights.html', data=[Flight(i, a, b) for i, [a, b] in enumerate(d)]) @app.route('/get_flight') def get_flight(): d = [["A100", "oranges"], ["A101", "apples"]] flight_id = int(flask.request.args.get('id')) flight_name = flask.request.args.get('flight') flight_abbreviation = flask.request.args.get('name') selected = dict(d)[flight_abbreviation] return flask.jsonify({"result":f' Thank you for choosing {flight_name} '})
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52646107
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92231731
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52649934
type: Comment
has text: Defining columns in the beginning definitely helps it. Thanks!

http://stackoverflow.com/comment/92300786
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52685975
type: AnswerComment
has text: Ok found out I had a typo and got it fixed... thanks for your help, on another note, do you recommend using an html date-time picker to store dates in a database or just a textfield with a jquery layer on top?

http://stackoverflow.com/a/52683026
score: 1
answers question: http://stackoverflow.com/q/52682857
downvote count: 0
type: Answer
upvote count: 1
has body: Your solution works if you replace PDT with UTC - it seems PDT is not recognized: from datetime import datetime date="08/30/2017 10:02 pm (UTC)" dt = datetime.strptime(date, '%m/%d/%Y %I:%M %p (%Z)') print(dt) # 2017-08-30 22:02:00 vs. date="08/30/2017 10:02 pm (PDT)" dt = datetime.strptime(date, '%m/%d/%Y %I:%M %p (%Z)') print(dt) # time data '08/30/2017 10:02 pm (PDT)' does not match format '%m/%d/%Y %I:%M %p (%Z)' (https://pyfiddle.io/ in 2.7 mode)

tensorflow
tags question: http://stackoverflow.com/q/52668857
tags question: http://stackoverflow.com/q/52662727
tags question: http://stackoverflow.com/q/52658755
tags question: http://stackoverflow.com/q/52712301
tags question: http://stackoverflow.com/q/52685768
tags question: http://stackoverflow.com/q/52718451
tags question: http://stackoverflow.com/q/52656737
tags question: http://stackoverflow.com/q/52594468
tags question: http://stackoverflow.com/q/52663701
tags question: http://stackoverflow.com/q/52710671
tags question: http://stackoverflow.com/q/52732267
tags question: http://stackoverflow.com/q/52609798
tags question: http://stackoverflow.com/q/52730778
tags question: http://stackoverflow.com/q/52686639
tags question: http://stackoverflow.com/q/52600836
tags question: http://stackoverflow.com/q/52697996
tags question: http://stackoverflow.com/q/52674895
tags question: http://stackoverflow.com/q/52690283
tags question: http://stackoverflow.com/q/52613977
tags question: http://stackoverflow.com/q/52664110
tags question: http://stackoverflow.com/q/52639289
tags question: http://stackoverflow.com/q/52723753
tags question: http://stackoverflow.com/q/52740744
tags question: http://stackoverflow.com/q/52745754
tags question: http://stackoverflow.com/q/52605067
tags question: http://stackoverflow.com/q/52641501
tags question: http://stackoverflow.com/q/52605783
tags question: http://stackoverflow.com/q/52711895
tags question: http://stackoverflow.com/q/52610740
tags question: http://stackoverflow.com/q/52639165
tags question: http://stackoverflow.com/q/52590787
tags question: http://stackoverflow.com/q/52684581
tags question: http://stackoverflow.com/q/52594650
tags question: http://stackoverflow.com/q/52593481
tags question: http://stackoverflow.com/q/52627519
tags question: http://stackoverflow.com/q/52632301
tags question: http://stackoverflow.com/q/52685774
tags question: http://stackoverflow.com/q/52713304
tags question: http://stackoverflow.com/q/52655087
tags question: http://stackoverflow.com/q/52721616
tags question: http://stackoverflow.com/q/52698202
tags question: http://stackoverflow.com/q/52673987
tags question: http://stackoverflow.com/q/52738335
tags question: http://stackoverflow.com/q/52708821
tags question: http://stackoverflow.com/q/52699654
tags question: http://stackoverflow.com/q/52623614
tags question: http://stackoverflow.com/q/52594956
tags question: http://stackoverflow.com/q/52647115
tags question: http://stackoverflow.com/q/52614786
tags question: http://stackoverflow.com/q/52717181
tags question: http://stackoverflow.com/q/52679454
tags question: http://stackoverflow.com/q/52715499
tags question: http://stackoverflow.com/q/52591291
tags question: http://stackoverflow.com/q/52702653
tags question: http://stackoverflow.com/q/52712782
tags question: http://stackoverflow.com/q/52733761
tags question: http://stackoverflow.com/q/52637493
tags question: http://stackoverflow.com/q/52708764
tags question: http://stackoverflow.com/q/52597523
tags question: http://stackoverflow.com/q/52612435
tags question: http://stackoverflow.com/q/52670667
tags question: http://stackoverflow.com/q/52598959
tags question: http://stackoverflow.com/q/52632647
tags question: http://stackoverflow.com/q/52728958
tags question: http://stackoverflow.com/q/52666624
tags question: http://stackoverflow.com/q/52636943
tags question: http://stackoverflow.com/q/52653656
tags question: http://stackoverflow.com/q/52625844
tags question: http://stackoverflow.com/q/52728131
tag name: tensorflow
tags question: http://stackoverflow.com/q/52623706
tags question: http://stackoverflow.com/q/52743995
tags question: http://stackoverflow.com/q/52724147
tags question: http://stackoverflow.com/q/52742509
tags question: http://stackoverflow.com/q/52627196
tags question: http://stackoverflow.com/q/52612455
tags question: http://stackoverflow.com/q/52624703
tags question: http://stackoverflow.com/q/52678215
tags question: http://stackoverflow.com/q/52599110
tags question: http://stackoverflow.com/q/52738570

http://stackoverflow.com/comment/92194917
comment on: http://stackoverflow.com/q/52629035
has text: @MiguelSantos - Thank you, I tried that just now but it produces the same error.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52603847
has answer: http://stackoverflow.com/a/52603872
tagged with: selenium-webdriver
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49775502
has answer: http://stackoverflow.com/a/52603862
has comment: http://stackoverflow.com/comment/102462800
tagged with: webdriver
type: Question
has answer: http://stackoverflow.com/a/70859309
has answer: http://stackoverflow.com/a/52607451
accepted answer: http://stackoverflow.com/a/52607451
has body: I am using the time library in my script: import time time.sleep(1) It can sleep my Selenium WebDriver for one second, but how is it possible for 250 milliseconds?
downvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/377454
answer count: 4
possible better answer: http://stackoverflow.com/a/52603862
has comment: http://stackoverflow.com/comment/125319635
favorite count: 0
has comment: http://stackoverflow.com/comment/116835338
upvote count: 20
tagged with: webdriverwait
tagged with: selenium
score: 19
has title: How to sleep Selenium WebDriver in Python for milliseconds

http://stackoverflow.com/comment/92152858
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52609316
type: Comment
has text: Additionally, when using the `udf()` function you need to use the return value as the parameter that you pass to `withColumn`! In this case it works because your function uses the Spark API (and it would not work with the return value of `udf()`).

http://stackoverflow.com/q/52651918
duplicate of: http://stackoverflow.com/q/1059559
favorite count: 0
has body: I've been asking about it here lately, but I have one more example that I can not deal with. import re title = "Nad Ziemią / Above Ground – test - filmy i seriale" if title.find('/') &gt;= 0: original_title = (re.split('[-/()]', title)[1]) print(original_title) The result of this will be: Above Ground - test And I need to split another dash to get only the movie title: Above Ground Is it possible to do all in one? Regards.
has answer: http://stackoverflow.com/a/52652299
upvote count: 2
has answer: http://stackoverflow.com/a/52652386
accepted answer: http://stackoverflow.com/a/52652386
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1059559
has comment: http://stackoverflow.com/comment/92235654
type: Question
tagged with: split
possible better answer: http://stackoverflow.com/a/52652299
has answer: http://stackoverflow.com/a/52652312
has title: Python string splitting with more than one separator and non roman characters
tagged with: python-2.7
answer count: 3
downvote count: 0

http://stackoverflow.com/comment/92163906
type: QuestionComment
score: 0
has text: @Serge why would you want to use `getlines`?
comment on: http://stackoverflow.com/q/52614648
type: Comment

http://stackoverflow.com/q/52745290
tagged with: python
downvote count: 1
score: -1
type: Question
upvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/3906137
has body: I'm trying to extract some information from a File. File: ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 CONTENT ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 CONTENT CONTENT CONTENT CONTENTCONTENTCONTENT CONTENTCONTENT CONTENTCONTENTCONTENTCONTENTCONTENT CONTENTCONTENTCONTENTCONTENTCONTENT I wanna execute multiple pattern in this file but when I extract the first information the rest of them (File) comes empty. import re import pdb w = open("extractfile.txt","r") print w.read() print re.findall(r'CONTENT', w.read()) print re.findall(r'\w{3} \d{2}-\d{2}-\d{2}', w.read()) Output: ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 CONTENT ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 CONTENT CONTENT CONTENT CONTENTCONTENTCONTENT CONTENTCONTENT CONTENTCONTENTCONTENTCONTENTCONTENT CONTENTCONTENTCONTENTCONTENTCONTENT [] [] If I change the print order, it always shows the first print, the rest of them comes empty... Another thing that I thought was Multiple Pattern in one line, by using groups, but I don't know if it would work
has title: Python: Matching multiple patterns in File
duplicate of: http://stackoverflow.com/q/3906137
tagged with: regex
has answer: http://stackoverflow.com/a/52745505
type: UnansweredQuestion

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/52632610
tags question: http://stackoverflow.com/q/52673009
tags question: http://stackoverflow.com/q/52620784
tags question: http://stackoverflow.com/q/52651205
tags question: http://stackoverflow.com/q/52593967
tags question: http://stackoverflow.com/q/52727538
tags question: http://stackoverflow.com/q/52616549
tags question: http://stackoverflow.com/q/52692529
type: Tag
tags question: http://stackoverflow.com/q/52623974
tags question: http://stackoverflow.com/q/52613220
tags question: http://stackoverflow.com/q/52715562
tags question: http://stackoverflow.com/q/52731346
tags question: http://stackoverflow.com/q/52696990
tags question: http://stackoverflow.com/q/52621063
tags question: http://stackoverflow.com/q/52713608
tags question: http://stackoverflow.com/q/52590757
tags question: http://stackoverflow.com/q/52619441
tags question: http://stackoverflow.com/q/52607350
tags question: http://stackoverflow.com/q/52727951
tags question: http://stackoverflow.com/q/52722840
tags question: http://stackoverflow.com/q/52651519
tags question: http://stackoverflow.com/q/52628947

http://stackoverflow.com/comment/92278425
score: 0
type: Comment
has text: Is this python 2.7? I got invalid syntax errors. I'm using python3.6.
comment on: http://stackoverflow.com/a/52674421
type: AnswerComment

http://stackoverflow.com/comment/92338259
type: QuestionComment
has text: You realize that python prints strings surrounded with quotes, right? There's nothing wrong with `a = '"3"'`.
comment on: http://stackoverflow.com/q/52705858
score: 3
type: Comment

http://stackoverflow.com/q/52610645
has comment: http://stackoverflow.com/comment/92186553
has comment: http://stackoverflow.com/comment/92199537
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92179919
has comment: http://stackoverflow.com/comment/92190141
favorite count: 0
has answer: http://stackoverflow.com/a/52617815
tagged with: python
has title: Unbuffered python coverage
has body: I want to run application in production with coverage enable. The application is always up and do not stop its execution. In each day I want to see coverage increase. Unfortunately .coverage file appear on the disk only after application stop. To simulate this behavior I have test.py # cat test.py if 1==2: print(1) if 2==2: print(2) import time i = 10 while i: print("sleep") time.sleep(1) i -= 1 print("end") Which is launched like python3 -u -m coverage run test.py 2 sleep sleep sleep sleep # I want to be able to see coverage in this moment sleep sleep sleep sleep sleep sleep end Only after end word is printed I can see coverage file ls -a . .. .coverage test.py How can I force flushing/Unbuffering on py.coverage ?
score: 2
tagged with: code-coverage
upvote count: 2
type: UnansweredQuestion
type: Question
tagged with: coverage.py
has comment: http://stackoverflow.com/comment/92169735
has comment: http://stackoverflow.com/comment/140252973
has comment: http://stackoverflow.com/comment/92211332

http://stackoverflow.com/a/52746047
answers question: http://stackoverflow.com/q/52643306
type: Answer
score: 1
upvote count: 1
has body: For the java client, you need to use the stub generated by the java protobuf plugin, which need to be installed separately. Can you please take a look at this link: https://github.com/grpc/grpc-java/tree/master/compiler
downvote count: 0

http://stackoverflow.com/q/52639603
has body: I tried to work with SO question example @dataclass class WordItem: id: str = field(init=False) phrase: str word_type: WORD_TYPE def __post_init__(self): self.id = f'{self.phrase}_{self.word_type.name.lower()}' I got &lt;ipython-input-3-df20e5b35c67&gt; in WordItem() 3 id: str = field(init=False) 4 phrase: str ----&gt; 5 word_type: WORD_TYPE 6 7 def __post_init__(self): NameError: name 'WORD_TYPE' is not defined My Python version Python 3.6.6 :: Anaconda, Inc. What is exactly WORD_TYPE?
downvote count: 1
type: Question
score: -1
linked to: http://stackoverflow.com/q/52627942
has title: Dataclass: NameError: name 'WORD_TYPE' is not defined
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/47955263
tagged with: python-dataclasses
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52639972
accepted answer: http://stackoverflow.com/a/52639972

http://stackoverflow.com/q/52612693
has comment: http://stackoverflow.com/comment/92160248
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92160263
downvote count: 2
has title: 'Client' object has no attribute 'send_message'
has comment: http://stackoverflow.com/comment/92160609
tagged with: discord.py
has comment: http://stackoverflow.com/comment/92160632
has comment: http://stackoverflow.com/comment/92168673
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92160201
has comment: http://stackoverflow.com/comment/92160090
favorite count: 0
has comment: http://stackoverflow.com/comment/92160157
score: 0
has comment: http://stackoverflow.com/comment/92160588
has answer: http://stackoverflow.com/a/52613974
has body: When run produces this on the console, can you fix it? import feedparser import discord import asyncio url = 'http://blog.counter-strike.net/index.php/feed/' Client = discord.Client() global last_id last_id = [] #---Edit this before running the bot------ #1] Add the App Bot User Token you got from discord here token = ... #2] Add the Discord Channel IDs to which the bot will message when CSGO updates . #bot has to be a part of the group to which the channel belongs . duh channel_id = ['496709417203662848', '496709455816294411', '496709586196365323'] async def print_console(text): await Client.wait_until_ready() print(text) for num in channel_id: await Client.send_message(Client.get_channel(num),text) @Client.event async def on_ready(): await Client.change_presence(game=discord.Game(name='CSGO-Updates')) print('Logged in as') print(Client.user.name) print(Client.user.id) print('------') @Client.event async def on_message(message): if message.content.startswith('!check'): await Client.send_message(message.channel,'bot Running') if message.content.startswith('!help'): help_msg = '***the currently active commands are:***\n ```css\n{}\n``` \n' text = ' !help : displays the help documentation\n !check : checks if the bot is running,returns 0 or no message if bot is having problems\n !madeby : Steam URL of the bot Creator \n ' await Client.send_message(message.channel, help_msg.format(text)) if message.content.startswith('!madeby'): msg = ' *made by:* \n http://steamcommunity.com/id/zero_aak' await Client.send_message(message.channel, msg) async def main(): global last_id feed = feedparser.parse(url) for index in feed.entries: last_id.append(index.id) print('primary scan complete') await print_console('bot started , use !help for help') while True: await asyncio.sleep(20) feed = feedparser.parse(url) for item in feed.entries: if item.id not in last_id: last_id.append(item.id) await print_console(item.link) Client.loop.create_task(main()) Client.run(token) Here's what displ…
has comment: http://stackoverflow.com/comment/92160428
has answer: http://stackoverflow.com/a/57053765
tagged with: python
tagged with: discord

http://stackoverflow.com/comment/92153115
type: Comment
comment on: http://stackoverflow.com/a/52608570
type: AnswerComment
has text: @OptimusPrime - Sure, use `df['pct'] = df.groupby(['city', 'index'])['val'].apply(lambda x: x.pct_change()) `
score: 0

http://stackoverflow.com/q/52661363
favorite count: 0
has answer: http://stackoverflow.com/a/52662907
tagged with: ensemble-learning
linked to: http://stackoverflow.com/q/42920148
has body: I tried to use soft voting on calibration classifiers on sklearn. Since soft voting does not have prefit option so far, I tried to make VotingClassifier.fit() to call CalibratedClassifierCV.fit(). The following is my code: data = load_breast_cancer() # Data spliting. X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25) # Base classifiers. clf_svm = svm.SVC(gamma=0.001, probability=True) clf_svm.fit(X_train, y_train) clf_lr = LogisticRegression(random_state=0, solver='lbfgs') clf_lr.fit(X_train, y_train) svm_isotonic = CalibratedClassifierCV(clf_svm, cv='prefit', method='isotonic') svm_isotonic.fit(X_val, y_val) lr_isotonic = CalibratedClassifierCV(clf_lr, cv='prefit', method='isotonic') lr_isotonic.fit(X_val, y_val) eclf_soft2 = VotingClassifier(estimators=[ ('svm', svm_isotonic), ('lr', lr_isotonic)], voting ='soft') eclf_soft2.fit(X_val, y_val) However, I got some strange errors: Traceback (most recent call last): File "/home/ubuntu/projects/faceRecognition/faceVerif/util/plot_calibration.py", line 127, in &lt;module&gt; main(parse_arguments(sys.argv[1:])) File "/home/ubuntu/projects/faceRecognition/faceVerif/util/plot_calibration.py", line 120, in main eclf_soft2.fit(X_val, y_val) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/sklearn/ensemble/voting_classifier.py", line 189, in fit for clf in clfs if clf is not None) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/sklearn/externals/joblib/parallel.py", line 779, in __call__ while self.dispatch_one_batch(iterator): File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/sklearn/externals/joblib/parallel.py", line 625, in dispatch_one_batch self._dispatch(tasks) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/sklearn/externals/joblib/parallel.py", line 588, in _dispatch job = self._backend.apply_async(batch, callback=cb) File "/home/ubuntu/anaconda3/lib/python3.6/si…
tagged with: python
tagged with: machine-learning
upvote count: 1
accepted answer: http://stackoverflow.com/a/52662907
type: Question
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
tagged with: scikit-learn
has title: Sklearn: NotFittedError: This SVC instance is not fitted yet. Soft Voting on Calibration classifiers

http://stackoverflow.com/a/73509613
upvote count: 3
score: 3
has body: I think it's too late to answer but this may be useful for others:) you can solve your problem this way: class ABCSerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = ('colA', 'colB', 'colC',) def get_fields(self): fields = super().get_fields() if self.instance: fields["colA"].read_only = True return fields When you want to create, the self.instance is None, it will pass the if clause, and in case of updating the if clause will make the field read only and non-editable.
downvote count: 0
answers question: http://stackoverflow.com/q/52686199
type: Answer

python
tags question: http://stackoverflow.com/q/52599673
tags question: http://stackoverflow.com/q/52648147
tags question: http://stackoverflow.com/q/52711175
tags question: http://stackoverflow.com/q/52684463
tags question: http://stackoverflow.com/q/52600983
tags question: http://stackoverflow.com/q/52655087
tags question: http://stackoverflow.com/q/52717510
tags question: http://stackoverflow.com/q/52695445
tags question: http://stackoverflow.com/q/52618490
tags question: http://stackoverflow.com/q/52652616
tags question: http://stackoverflow.com/q/52631573
tags question: http://stackoverflow.com/q/52722840
tags question: http://stackoverflow.com/q/52733545
tags question: http://stackoverflow.com/q/52644714
tags question: http://stackoverflow.com/q/52706238
tags question: http://stackoverflow.com/q/52630131
tags question: http://stackoverflow.com/q/52626682
tags question: http://stackoverflow.com/q/52699861
tags question: http://stackoverflow.com/q/52691566
tags question: http://stackoverflow.com/q/52715727
tags question: http://stackoverflow.com/q/52690093
tags question: http://stackoverflow.com/q/52655948
tags question: http://stackoverflow.com/q/52653663
tags question: http://stackoverflow.com/q/52682229
tags question: http://stackoverflow.com/q/52688614
tags question: http://stackoverflow.com/q/52743748
tags question: http://stackoverflow.com/q/52638157
tags question: http://stackoverflow.com/q/52738741
tags question: http://stackoverflow.com/q/52709719
tags question: http://stackoverflow.com/q/52711885
tags question: http://stackoverflow.com/q/52705564
tags question: http://stackoverflow.com/q/52700878
tags question: http://stackoverflow.com/q/52742457
tags question: http://stackoverflow.com/q/52618755
tags question: http://stackoverflow.com/q/52693799
tags question: http://stackoverflow.com/q/52721099
tags question: http://stackoverflow.com/q/52684954
tags question: http://stackoverflow.com/q/52707075
tags question: http://stackoverflow.com/q/52701964
tags question: http://stackoverflow.com/q/52617091
tags question: http://stackoverflow.com/q/52651074
tags question: http://stackoverflow.com/q/52682345
tags question: http://stackoverflow.com/q/52699358
tags question: http://stackoverflow.com/q/52668985
tags question: http://stackoverflow.com/q/52693042
tags question: http://stackoverflow.com/q/52729412
tags question: http://stackoverflow.com/q/52742319
tags question: http://stackoverflow.com/q/52636566
tags question: http://stackoverflow.com/q/52691196
tags question: http://stackoverflow.com/q/52608193
tags question: http://stackoverflow.com/q/52644393
tags question: http://stackoverflow.com/q/52709540
tags question: http://stackoverflow.com/q/52645108
tags question: http://stackoverflow.com/q/52697792
tags question: http://stackoverflow.com/q/52600484
tags question: http://stackoverflow.com/q/52693651
tags question: http://stackoverflow.com/q/52731229
tags question: http://stackoverflow.com/q/52658157
tags question: http://stackoverflow.com/q/52714845
tags question: http://stackoverflow.com/q/52601564
tags question: http://stackoverflow.com/q/52600067
tags question: http://stackoverflow.com/q/52591965
tags question: http://stackoverflow.com/q/52722001
tags question: http://stackoverflow.com/q/52665981
tags question: http://stackoverflow.com/q/52610380
tags question: http://stackoverflow.com/q/52670538
tags question: http://stackoverflow.com/q/52673987
tags question: http://stackoverflow.com/q/52622210
tags question: http://stackoverflow.com/q/52620202
tags question: http://stackoverflow.com/q/52669755
tags question: http://stackoverflow.com/q/52607405
tags question: http://stackoverflow.com/q/52631795
tags question: http://stackoverflow.com/q/52705038
tags question: http://stackoverflow.com/q/52743774
tags question: http://stackoverflow.com/q/52741990
tags question: http://stackoverflow.com/q/52709482
tags question: http://stackoverflow.com/q/52684858
tags question: http://stackoverflow.com/q/52666677
tags question: http://stackoverflow.com/q/52714026
tags question: http://stackoverflow.com/q/52703805

http://stackoverflow.com/comment/92237898
type: QuestionComment
comment on: http://stackoverflow.com/q/52647266
has text: I agree, I'll follow your advice to implement it throgh the right way, But I'd like to find a implement this dashboard firstly, Then I'll improve it. Do you know how to do it?
score: 0
type: Comment

http://stackoverflow.com/comment/92137434
score: 1
has text: Have you registered this UDF defined in class? , something like this ` sparkContext.udf.register("ProcessLog",LogProcessor.ProcessLog,"Return Type") ` and then later you should be able to invoke it as ` df.withColumn("Result","ProcessLog(col('logfile_dir')") . And also change the method defintion to static. Try this if it works for you. I was able to invoke udf like above.
comment on: http://stackoverflow.com/q/52597455
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52646801
has comment: http://stackoverflow.com/comment/92227572
has comment: http://stackoverflow.com/comment/92225491
score: 0
has comment: http://stackoverflow.com/comment/92225556
answer count: 1
has body: Trying to clean up a txt file from a USB GPS and having trouble with 3rd for loop. Currently have... deletes = ['$GPGGA', '$GPGSA', '$GPGSV', '$PSRF156', ] searchquery = '$GPRMC' with open('Drive_home.txt_rf') as f1: with open('Drive_home_1.txt', 'w+') as f2: for lines in f1: if not any(delete in lines for delete in deletes): f2.write(lines) with open('Drive_home_1.txt') as f2: with open('Drive_home_2.txt', 'w+') as f3: lines = f2.readlines() for i, line in enumerate(lines2): if line.startswith(searchquery): f3.write(line) f3.write(lines[i + 1]) with open('Drive_home_2.txt') as f3: with open('Drive_home_3.txt', 'w+') as f4: for lines in f3: if len(lines.rstrip('\n')) &gt;= 105: f4.write(lines) For some reason, the script is not creating the 'Drive_home_3.txt.' so not sure why its not. Also, is it possible just to create one .txt with all for loop? Update: Currently, Drive_home_1.txt and Drive_home_2.txt will be created to the desktop but Drive_home_3.txt is not. I have tried a quick search of that file but nothing comes up so I was assuming it was just not being created. This is the exact code that I'm using. I just noticed that lines2 should just be lines. I also get the error... Traceback (most recent call last): File "C:\Users****\Desktop\TestV6.py", line 16, in f3.write(lines[i + 1]) IndexError: list index out of range I assume that error is just from the data collection at the end of my file which looks like... $GPRMC 211536 A 3512.0329 N 8507.6987 W 0.24 220.94 300818 A*70 96.5 50 2 3 -3 236 0 1 1 30-08-18 17:15:36:551 $GPRMC 211537 A 3512.0329 N 8507.6987 W 0 220.94 300818 A*77 96.5 49 2 3 -4 236 0 1 1 30-08-18 17:15:37:549 $GPRMC 211538 A 3512.0325 N 8507.6985 W 0.31 220.94 300818 A*74 96.5 49 2 3 -2 236 0 1 1 30-08-18 17:15:38:469 $GPRMC 211539 A 3512.0325 N 8507.6985 W 0 220.94 300818 A*77 $GPRMC 211540 A 3512.0324 N 8507.6986 W 0.07 220.94 300818 A*7C $GPRMC 211540 A 3512.0324 N 8507.6986 W 0.07 220.94 300818 A*7C $GPRMC 211541 A 3512.0324 N 8507.6986 W 0…
has comment: http://stackoverflow.com/comment/92227564
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92225779
type: Question
has title: Cannot create more than 2 txt.files in Python
has answer: http://stackoverflow.com/a/52648619

http://stackoverflow.com/a/52598005
has comment: http://stackoverflow.com/comment/92133201
downvote count: 0
has body: Here's one possible solution. You could use itertools.groupby to identify runs of identical strings, and count how many appear in a row: &gt;&gt;&gt; import itertools &gt;&gt;&gt; seq = ['','','','A','','','B','','C','','D','','',''] &gt;&gt;&gt; runs = [(c, len(list(g))) for c,g in itertools.groupby(seq)] &gt;&gt;&gt; runs [('', 3), ('A', 1), ('', 2), ('B', 1), ('', 1), ('C', 1), ('', 1), ('D', 1), ('', 3)] Then remove the first and last elements if they are empty strings: &gt;&gt;&gt; if runs[0][0] == '': runs = runs[1:] ... &gt;&gt;&gt; if runs[-1][0] == '': runs = runs[:-1] ... &gt;&gt;&gt; runs [('A', 1), ('', 2), ('B', 1), ('', 1), ('C', 1), ('', 1), ('D', 1)] Then remove any interior groups that are composed of one empty string: &gt;&gt;&gt; runs = [(char, count) for char, count in runs if not (char == '' and count == 1)] &gt;&gt;&gt; runs [('A', 1), ('', 2), ('B', 1), ('C', 1), ('D', 1)] Then reconsitute the runs into a flat list. &gt;&gt;&gt; result = [char for char, count in runs for _ in range(count)] &gt;&gt;&gt; result ['A', '', '', 'B', 'C', 'D']
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52597760
has comment: http://stackoverflow.com/comment/92133847
answers question: http://stackoverflow.com/q/52597760
type: Answer
has comment: http://stackoverflow.com/comment/92132454
score: 3

http://stackoverflow.com/a/52682965
has comment: http://stackoverflow.com/comment/92296668
has comment: http://stackoverflow.com/comment/92377116
has comment: http://stackoverflow.com/comment/92306201
accepted answer of: http://stackoverflow.com/q/52681765
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92307160
has body: To scrape the subcategories, you will have to use selenium to interact with the dropdowns. A simple traversal over the second category of links will yield the pages, however, to find all the subcategories, recursion is needed to properly group the data. The code below utilizes a simple variant of the breadth-first search to determine when to stop looping over the dropdown toggle objects generated at each iteration of the while loop: from selenium import webdriver import time from bs4 import BeautifulSoup as soup def block_data(_d): return {_d.find('h3').text:[[i.a.attrs.get('title'), i.a.attrs.get('href')] for i in _d.find('ul').find_all('li')]} def get_pages(source:str) -&gt; dict: return [block_data(i) for i in soup(source, 'html.parser').find('div', {'id':'mw-pages'}).find_all('div', {'class':'mw-category-group'})] d = webdriver.Chrome('/path/to/chromedriver') d.get('https://en.wikipedia.org/wiki/Category:Computer_science') all_pages = get_pages(d.page_source) _seen_categories = [] def get_categories(source): return [[i['href'], i.text] for i in soup(source, 'html.parser').find_all('a', {'class':'CategoryTreeLabel'})] def total_depth(c): return sum(1 if len(b) ==1 and not b[0] else sum([total_depth(i) for i in b]) for a, b in c.items()) def group_categories(source) -&gt; dict: return {i.find('div', {'class':'CategoryTreeItem'}).a.text:(lambda x:None if not x else [group_categories(c) for c in x])(i.find_all('div', {'class':'CategoryTreeChildren'})) for i in source.find_all('div', {'class':'CategoryTreeSection'})} while True: full_dict = group_categories(soup(d.page_source, 'html.parser')) flag = False for i in d.find_elements_by_class_name('CategoryTreeToggle'): try: if i.get_attribute('data-ct-title') not in _seen_categories: i.click() flag = True time.sleep(1) except: pass else: _seen_categories.append(i.get_attribute('data-ct-title')) if not flag: break Output: all_pages: [{'\xa0': [['Computer science', '/wiki/Computer_science'], ['Glossary of computer science…
has comment: http://stackoverflow.com/comment/92295465
type: Answer
has comment: http://stackoverflow.com/comment/92377294
has comment: http://stackoverflow.com/comment/92302327
has comment: http://stackoverflow.com/comment/92307061
upvote count: 3
has comment: http://stackoverflow.com/comment/92378847
downvote count: 1
has comment: http://stackoverflow.com/comment/92305127
has comment: http://stackoverflow.com/comment/92306961
answers question: http://stackoverflow.com/q/52681765

http://stackoverflow.com/q/52648593
type: Question
has comment: http://stackoverflow.com/comment/92229438
has comment: http://stackoverflow.com/comment/92229871
has comment: http://stackoverflow.com/comment/92229812
has body: I'm trying to create a Config Python 3 class where users set configuration params as either plain class attributes on a super class or as properties on a super class that users can set override/shadow on instances of the (sub)class. I'd rather not have require users to define setter methods for attributes that were created using property methods. Is there a way I can clobber an attribute set in a parent class even when it was created using a property decorator? class Configuration: param1 = 'a' @property def param2(self): return self.param1 + 'x' class Proj1(Configuration): param3 = 'blah' config = Proj1() config.param2 = 'new_val' This code snippet would throw an AttributeError with the attempted assignment to the pram2 attrbute because of the property decorate in the superclass. Is there a way I can easily clobber this existing property and shadow it with an arbitrary attribute value?
linked to: http://stackoverflow.com/q/52559922
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92229665
has comment: http://stackoverflow.com/comment/92230180
has answer: http://stackoverflow.com/a/52649151
tagged with: decorator
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92229949
has comment: http://stackoverflow.com/comment/92230911
has comment: http://stackoverflow.com/comment/92229107
has answer: http://stackoverflow.com/a/52649190
has comment: http://stackoverflow.com/comment/92229626
has title: How can I clobber a property within a subcass?
has comment: http://stackoverflow.com/comment/92230816
has comment: http://stackoverflow.com/comment/92229435

pyqt
type: Tag
tags question: http://stackoverflow.com/q/52618980
tags question: http://stackoverflow.com/q/52627074
tags question: http://stackoverflow.com/q/52657066
tags question: http://stackoverflow.com/q/52656526
tags question: http://stackoverflow.com/q/52744873
tags question: http://stackoverflow.com/q/52591246
tags question: http://stackoverflow.com/q/52743155
tags question: http://stackoverflow.com/q/52636230
tags question: http://stackoverflow.com/q/52658724
tags question: http://stackoverflow.com/q/52626888
tags question: http://stackoverflow.com/q/52645352
tags question: http://stackoverflow.com/q/52670875
tags question: http://stackoverflow.com/q/52623040
tags question: http://stackoverflow.com/q/52599765
tags question: http://stackoverflow.com/q/52689047
tags question: http://stackoverflow.com/q/52703840
tags question: http://stackoverflow.com/q/52594018
tags question: http://stackoverflow.com/q/52692448
tags question: http://stackoverflow.com/q/52745817
tags question: http://stackoverflow.com/q/52589982
tags question: http://stackoverflow.com/q/52602091
tags question: http://stackoverflow.com/q/52684858
tags question: http://stackoverflow.com/q/52591542
tags question: http://stackoverflow.com/q/52686009
tags question: http://stackoverflow.com/q/52699527
tags question: http://stackoverflow.com/q/52746894
tags question: http://stackoverflow.com/q/52615115
tags question: http://stackoverflow.com/q/52717004
tags question: http://stackoverflow.com/q/52629587
tags question: http://stackoverflow.com/q/52592977
tags question: http://stackoverflow.com/q/52654805
tags question: http://stackoverflow.com/q/52716273
tags question: http://stackoverflow.com/q/52671838
tags question: http://stackoverflow.com/q/52673468
tags question: http://stackoverflow.com/q/52728462
tags question: http://stackoverflow.com/q/52644371
tags question: http://stackoverflow.com/q/52745442
tags question: http://stackoverflow.com/q/52605821
tags question: http://stackoverflow.com/q/52609229
tags question: http://stackoverflow.com/q/52629572
tags question: http://stackoverflow.com/q/52647548
tag name: pyqt
tags question: http://stackoverflow.com/q/52735921
tags question: http://stackoverflow.com/q/52678120
tags question: http://stackoverflow.com/q/52691998
tags question: http://stackoverflow.com/q/52592663
tags question: http://stackoverflow.com/q/52713809
tags question: http://stackoverflow.com/q/52623799
tags question: http://stackoverflow.com/q/52616553

http://stackoverflow.com/comment/92154532
comment on: http://stackoverflow.com/a/52610136
score: 3
type: AnswerComment
has text: ignore_index=True ?
type: Comment

http://stackoverflow.com/comment/92230574
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52637852
type: AnswerComment
has text: I'm afraid I too don't have sufficient understanding about the algorithm. I just increased/decreased the parameters step by step to find the best results. All that I know is that `param1` determines the sensitivity of edge detection algorithm while `param2` determines the sensitivity of center detection algorithm https://docs.opencv.org/3.1.0/d4/d70/tutorial_hough_circle.html

http://stackoverflow.com/comment/92360157
comment on: http://stackoverflow.com/q/52716792
type: QuestionComment
type: Comment
has text: Not the same, but very close to: https://stackoverflow.com/q/52689949/842935
score: 0

http://stackoverflow.com/q/52597757
has answer: http://stackoverflow.com/a/52597939
has body: In one of my codes, I use numpy for matrices calculations. At one point, I have to do the outer product between 2 vectors to get a matrix. That's where I'm stuck. At first, I tried numpy.dot, or other matrix product, but when the arguments are both 1D, it only does the scalar product, which not what I want. Then I found that numpy.outer does exactly what I want : a column * a line. The thing is, my vectors are not arrays. Since they result from a numpy.dot operation, they are ndarray objects. But ndarrays do not have an outer method. I have tried everything I found on the Internet to convert my ndarrays to simple arrays. But nothing works, I still have a ndarray and the same attribute error again and again. Now I don't know what to try, so I wanted to check if you knew another way to do this outer product, before I do some nasty things implying cloning the values in a array. Thank you very much for your help.
score: 2
type: AnsweredQuestion
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92130269
has comment: http://stackoverflow.com/comment/92130579
accepted answer: http://stackoverflow.com/a/52597939
downvote count: 0
has title: Outer product with Numpy and Ndarray
has comment: http://stackoverflow.com/comment/92130546
favorite count: 0
has comment: http://stackoverflow.com/comment/92130310
tagged with: multidimensional-array
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92130504
upvote count: 2

http://stackoverflow.com/a/52725323
has comment: http://stackoverflow.com/comment/92376364
has comment: http://stackoverflow.com/comment/92376287
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/92376085
has comment: http://stackoverflow.com/comment/92381853
answers question: http://stackoverflow.com/q/52723212
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52723212
has body: The key difference between polyfit() and the Orthogonal Distance Regression (ODR) fit is that polyfit works under the assumption that the error on x is negligible. If this assumption is violated, like it is in your data, you cannot expect the two methods to produce similar results. In particular, ODR() is very sensitive to the errors you specify. If you do not specify any error/weighting, it will assign a value of 1 for both x and y, meaning that any scale difference between x and y will affect the results (the so-called numerical conditioning). On the contrary, polyfit(), before computing the fit, applies some sort of pre-whitening to the data (see around line 577 of its source code) for better numerical conditioning. Therefore, if you want ODR() to match polyfit(), you could simply fine-tune the error on Y to change your numerical conditioning. I tested that this works for any numerical conditioning between 1e-10 and 1e10 of your Y (it is / 10. or 1e-1 in your example). mydata = odr.RealData(X, Y) # equivalent to: odr.RealData(X, Y, sx=1, sy=1) to: mydata = odr.RealData(X, Y, sx=1, sy=1/np.var(Y)) (EDIT: note there was a typo on the line above) I tested that this works for any numerical conditioning between 1e-10 and 1e10 of your Y (it is / 10. or 1e-1 in your example). Note that this would only make sense for well-conditioned fits.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92401590

http://stackoverflow.com/a/52591659
score: 0
answers question: http://stackoverflow.com/q/52590886
type: Answer
has body: This answer aims to be the simplest one... The data sentences = ["I", "am", "good", ".", "I", "like", "you", ".", "We", "are", "not", "friends", "."] We initialize the output list and represent that we are starting a new sentence l, start = [], 1 We loop on the data list, using w to address the current word if we are at the start of a new sentence we clear the flag and add an empty list to the tail of the output list we append the current word to the last sublist (note that ① we are guaranteed that there is at least a last sublist (do you like alliterations?) and ② every word gets appended) if we are at the end — we have met a "." — we raise again the flag. Note the single comment… for w in sentences: if start: start = l.append([]) # l.append() returns None, that is falsey... l[-1].append(w) if w == ".": start = 1

http://stackoverflow.com/q/52601988
type: Question
has comment: http://stackoverflow.com/comment/92138287
has comment: http://stackoverflow.com/comment/92162287
answer count: 2
has answer: http://stackoverflow.com/a/52613818
downvote count: 0
has comment: http://stackoverflow.com/comment/92139914
score: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92161727
tagged with: time
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52632477
has title: Python time.sleep interrupted after click on terminal
has comment: http://stackoverflow.com/comment/92184081
tagged with: python
linked to: http://stackoverflow.com/q/30418886
has comment: http://stackoverflow.com/comment/92138320
upvote count: 1
has comment: http://stackoverflow.com/comment/92162307
has body: I am building a command line tools using Python script. it's a loop to check data and print out some stuff after some delay seconds. It works fine until I click anything or selecting text by mouse on the terminal without keyboard event. it doesn't do anything after that, doesn't print and recheck import time import sys print('some thing') for remaining in range(10, 0, -1): sys.stdout.write("\r") sys.stdout.write("recheck in {:2d}.".format(remaining)) sys.stdout.flush() time.sleep(1) sys.stdout.write("\rComplete! \n") input() My environment is anaconda 64bit on windows 10
tagged with: sleep
has comment: http://stackoverflow.com/comment/92184112

http://stackoverflow.com/a/77938582
answers question: http://stackoverflow.com/q/52622210
has body: You can disable zorder automatically and adjust it by yourself: fig=plt.figure(computed_zorder=False)
type: Answer
score: 0

http://stackoverflow.com/q/52629796
type: AnsweredQuestion
has title: Reduce Seaborn KDE Plot Margins
has answer: http://stackoverflow.com/a/52630650
type: Question
has body: Hi I have code below that produces multiple KDE plot on the margins of a jointplot h = sns.JointGrid('SECS', 'EPOCH', df) for name, group in df.groupby("QUERY"): sns.kdeplot(group["SECS"], ax=h.ax_marg_x, legend=False) sns.kdeplot(group["EPOCH"], ax=h.ax_marg_y, vertical=True, legend=False) h.ax_joint.plot(group["SECS"], group["EPOCH"], ".", ms=5) I'd be interested to know how to limit the margins so that the graph starts from 0 and not from -20000, there's lot of dead space there.
tagged with: charts
tagged with: matplotlib
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52630650
tagged with: seaborn
tagged with: python

http://stackoverflow.com/q/52736337
score: 2
tagged with: amazon-s3
has body: I am using the following piece of boto3 code to add new tags to the S3 bucket without deleting the existing tags. s3 = boto3.resource('s3') bucket_tagging = s3.BucketTagging('bucket_name') tags = bucket_tagging.tag_set tags.append({'Key':'Owner', 'Value': owner}) Set_Tag = bucket_tagging.put(Tagging={'TagSet':tags}) This gets the existing tags, adds a new one, and then puts them all back in. But if my bucket contains 'aws:' as prefix, it gives the following error: 'An error occurred (InvalidParameterValue) when calling the CreateTags operation: Value ( aws:cloudformation:stack-name ) for parameter key is invalid. Tag keys starting with 'aws:' are reserved for internal use.' How to add new tags without deleting the existing tags in this case using boto3?
type: Question
downvote count: 0
has title: How to add new tags to an AWS S3 Bucket using Boto3 if the existing tags on the bucket contains 'aws:' prefixes?
tagged with: boto3
tagged with: amazon-web-services
favorite count: 0
has answer: http://stackoverflow.com/a/64866160
has comment: http://stackoverflow.com/comment/92406373
answer count: 1
tagged with: python
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/52659616
has comment: http://stackoverflow.com/comment/92252969
tagged with: python
tagged with: pandas-apply
has title: Applying new row within second level index
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
accepted answer: http://stackoverflow.com/a/52661370
type: Question
tagged with: numpy
score: 0
tagged with: pandas-groupby
tagged with: pandas
linked to: http://stackoverflow.com/q/24917700
answer count: 1
has answer: http://stackoverflow.com/a/52661370
has body: I have a data frame that looks something like: +-----------+---------+-------+-------+-------+ | | | Day 1 | Day 2 | Day 3 | +-----------+---------+-------+-------+-------+ | Product 1 | Revenue | 0 | 0 | 0 | | | Cost | 0 | 0 | 0 | | Product 2 | Revenue | 0 | 0 | 0 | | | Cost | 0 | 0 | 0 | | Product 3 | Revenue | 0 | 0 | 0 | | | Cost | 0 | 0 | 0 | +-----------+---------+-------+-------+-------+ Essentially a two level index on the vertical. The first level is the product and the second either revenue or cost. I would like to add a Profit row to all products below Revenue and Cost (simply Revenue - Cost). Or even the average of that products Revenue etc. However, after much experimentation with apply, I cannot seem to get this to work with the multi levels. Product 1 Revenue 0 Cost 0 Profit 0 How could this be achieved?

http://stackoverflow.com/a/52730991
score: 0
has body: Aim of saving complete model is modifying the model in the future. If you are not planning to modify your model, you can just save the weights and use them for the prediction. This will save a huge space for you.
type: Answer
answers question: http://stackoverflow.com/q/52729048

http://stackoverflow.com/comment/92123765
score: 1
type: AnswerComment
has text: No problem! The `decision_function` and `predict_proba` depends on the classifier you're using in sklearn. Not all of them will have those methods.
comment on: http://stackoverflow.com/a/52593267
type: Comment

http://stackoverflow.com/comment/92382735
comment on: http://stackoverflow.com/q/52728432
score: 2
has text: Is this a 1:1, 1:many many:1 or many:many merge?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92150922
comment on: http://stackoverflow.com/q/52607356
type: Comment
has text: I've edited the question, with the precise scenario for anyone who encounters this is the future. Thanks for your help @Matthias!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92254483
comment on: http://stackoverflow.com/q/52661318
score: 0
has text: No it's completely upto you, Input image can implicitly be a gray scale image. Generally input images are in BGR example, hence the assumption of that text.
type: Comment
type: QuestionComment

numpy
tags question: http://stackoverflow.com/q/52746840
tags question: http://stackoverflow.com/q/52673780
tags question: http://stackoverflow.com/q/52649568
tags question: http://stackoverflow.com/q/52659777
tags question: http://stackoverflow.com/q/52664583
tags question: http://stackoverflow.com/q/52653734
tags question: http://stackoverflow.com/q/52694627
tags question: http://stackoverflow.com/q/52688113
tags question: http://stackoverflow.com/q/52636288
tags question: http://stackoverflow.com/q/52740339
tags question: http://stackoverflow.com/q/52594650
tags question: http://stackoverflow.com/q/52623692
tags question: http://stackoverflow.com/q/52641975
tags question: http://stackoverflow.com/q/52672317
tags question: http://stackoverflow.com/q/52635539
tags question: http://stackoverflow.com/q/52735060
tags question: http://stackoverflow.com/q/52721283
tags question: http://stackoverflow.com/q/52700894
tags question: http://stackoverflow.com/q/52674923
tags question: http://stackoverflow.com/q/52715727
tags question: http://stackoverflow.com/q/52709719
tags question: http://stackoverflow.com/q/52700878
tags question: http://stackoverflow.com/q/52644393
tags question: http://stackoverflow.com/q/52645108
tags question: http://stackoverflow.com/q/52735334
tags question: http://stackoverflow.com/q/52743774
tags question: http://stackoverflow.com/q/52660757
tags question: http://stackoverflow.com/q/52727099
tags question: http://stackoverflow.com/q/52694146
tags question: http://stackoverflow.com/q/52628445
tags question: http://stackoverflow.com/q/52684944
tags question: http://stackoverflow.com/q/52735825
tags question: http://stackoverflow.com/q/52730753
tags question: http://stackoverflow.com/q/52731884
tags question: http://stackoverflow.com/q/52656929
tags question: http://stackoverflow.com/q/52715049
tags question: http://stackoverflow.com/q/52619874
tags question: http://stackoverflow.com/q/52673223
tags question: http://stackoverflow.com/q/52588867
tags question: http://stackoverflow.com/q/52645152
tags question: http://stackoverflow.com/q/52703659
tags question: http://stackoverflow.com/q/52736914
tags question: http://stackoverflow.com/q/52636716
tags question: http://stackoverflow.com/q/52669019
tags question: http://stackoverflow.com/q/52685560
tags question: http://stackoverflow.com/q/52715621
tags question: http://stackoverflow.com/q/52620063
tags question: http://stackoverflow.com/q/52594392
tags question: http://stackoverflow.com/q/52698145
tags question: http://stackoverflow.com/q/52683117
tags question: http://stackoverflow.com/q/52729910
tags question: http://stackoverflow.com/q/52601258
tags question: http://stackoverflow.com/q/52642130
tags question: http://stackoverflow.com/q/52690632
tags question: http://stackoverflow.com/q/52708265
tags question: http://stackoverflow.com/q/52725314
tags question: http://stackoverflow.com/q/52603487
tags question: http://stackoverflow.com/q/52701932
tags question: http://stackoverflow.com/q/52597454
tags question: http://stackoverflow.com/q/52632718
tags question: http://stackoverflow.com/q/52730328
tags question: http://stackoverflow.com/q/52718911
tags question: http://stackoverflow.com/q/52713261
tags question: http://stackoverflow.com/q/52629222
tags question: http://stackoverflow.com/q/52714245
tags question: http://stackoverflow.com/q/52657097
tags question: http://stackoverflow.com/q/52694947
tags question: http://stackoverflow.com/q/52708297
tags question: http://stackoverflow.com/q/52669277
tags question: http://stackoverflow.com/q/52633962
tags question: http://stackoverflow.com/q/52694220
tags question: http://stackoverflow.com/q/52600897
tags question: http://stackoverflow.com/q/52728493
tags question: http://stackoverflow.com/q/52598012
tags question: http://stackoverflow.com/q/52731563
tags question: http://stackoverflow.com/q/52668072
tags question: http://stackoverflow.com/q/52630771
tags question: http://stackoverflow.com/q/52717821
tags question: http://stackoverflow.com/q/52717753
tags question: http://stackoverflow.com/q/52673933

http://stackoverflow.com/q/52708759
downvote count: 0
favorite count: 0
upvote count: 3
has body: I am interested in a way to increase the thickness of the axes in matplotlib (without cutting into the domain of the plot). That is, I want the thickness of the axes to extend outwards from the plot, rather than inwards. Is such a thing possible? Traditional methods (e.g., see below) do not seem to work: from pylab import * close("all") #rc('axes', linewidth=30) # Make a dummy plot plot([0.01, 0, 1], [0.5, 0, 1]) fontsize = 14 ax = gca() for axis in ['top','bottom','left','right']: ax.spines[axis].set_linewidth(30) xlabel('X Axis', fontsize=16, fontweight='bold') ylabel('Y Axis', fontsize=16, fontweight='bold')
tagged with: axis-labels
tagged with: python
has answer: http://stackoverflow.com/a/78129484
type: UnansweredQuestion
tagged with: yaxis
tagged with: plot
score: 3
linked to: http://stackoverflow.com/q/30081846
has title: Increase Axis Thickness in Matplotlib (Without Cutting into Plot Domain!)
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52709714
type: Question
answer count: 2

http://stackoverflow.com/comment/92304940
has text: bit does it mean we "increment" the day? Is `24:00` the *start* or the *end* of the day?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52688645

http://stackoverflow.com/q/52733625
type: Question
has body: I have a menu named Portal Form. I want that menu to be visible for users with Portal group. So far I have created users and assigned portal them Portal group. I have also added access rights of my model for the portal group. Everything as suggested in the previous question similar to mine, I have done followed all the solutions. Yet my custom menu is not visible to Portal users. Can anybody tell me how is it achieved in Odoo 11?
tagged with: odoo
has answer: http://stackoverflow.com/a/56236186
has title: How to add my custom menu to the portal users menu list?
tagged with: security
has answer: http://stackoverflow.com/a/52737862
answer count: 3
has answer: http://stackoverflow.com/a/52753815
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: odoo-11
upvote count: 2

http://stackoverflow.com/q/52600980
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
tagged with: function
has answer: http://stackoverflow.com/a/52601015
downvote count: 0
answer count: 1
favorite count: 0
has body: If I were to use compile() and exec() to execute some code that the user inputed, can functions or variables defined in the code be used again outside? For example: code = "" while 1: line = input("") if line == "": break code += line exec(compile(code, "code", "exec")) print(test()+1) This will not return 6 like I would expect. It gives a NameError but there is no problem with compiling or executing the code. There is no error if code is just a string and not input. Is there any way to use the function test()?
accepted answer: http://stackoverflow.com/a/52601015
has title: Using exec()/compile() with user input
upvote count: 1
tagged with: input

http://stackoverflow.com/q/52596847
answer count: 0
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/92153467
has comment: http://stackoverflow.com/comment/92157406
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: Below is my test module: import tkinter as tk def startUi(): window = tk.Tk() window.title("Parent Window") window.geometry("500x200") rgButton = tk.Button(window,text=" Open Child",command=openChildWindow) rgButton.pack() window.mainloop() def openChildWindow(): window = tk.Toplevel() window.title("Child Window") window.geometry("200x200") startUi() After running the above code why am I not able to lift the parent window to front just after clicking the button. i.e after clicking the button the child window will show in front of parent window, however when I click on the space area of the parent window I am not able to bring the parent window up to the front. I am able to bring it up to front only by: Clicking on the border of the parent window Clicking on child window once and then clicking on the Parent again. This not a normal behavior. Why is it so? And How will I solve it? I want to achieve the normal behavior i.e. I want to bring the parent window up in front of the child on clicking anywhere on the parent window.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92158926
score: 2
has title: Unable to lift parent window exist under child window in Tkinter? (Python 3.6.6, Windows 7 Ultimate)
tagged with: tkinter

http://stackoverflow.com/a/52652299
upvote count: 2
answers question: http://stackoverflow.com/q/52651918
has body: Investigating your question further it looks like that character isn't a normal hyphen (it's slightly higher), copy it into your regex expression and you'll see: import re title = "Nad Ziemią / Above Ground – test - filmy i seriale" if title.find('/') &gt;= 0: original_title = (re.split('[–\-/()]', title)[1]) print(original_title) Bonus points if anyone can work out what the character is.
downvote count: 0
has comment: http://stackoverflow.com/comment/92236315
type: Answer
score: 2

http://stackoverflow.com/a/52722030
answers question: http://stackoverflow.com/q/52722001
has comment: http://stackoverflow.com/comment/92369368
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/92370239
type: Answer
upvote count: 4
downvote count: 0
has body: You can use itertools.islice() to iterate over a subset of values, by index: from itertools import islice for element in islice(list_1, i, j): This will still iterate over all i - 1 initial values of list_1, but will do so in C and not keep skipped values in memory. Demo: &gt;&gt;&gt; from itertools import islice &gt;&gt;&gt; list_1 = [42, 81, 117, 3103, 17, 22] &gt;&gt;&gt; for elem in islice(list_1, 2, 5): ... print(elem) ... 117 3103 17
has comment: http://stackoverflow.com/comment/92373434
accepted answer of: http://stackoverflow.com/q/52722001

http://stackoverflow.com/comment/92263177
has text: To my understanding, Anaconda is a python installation+ some useful data-science packages, like numpy. However, when I create new envs with conda, these packages are not automatically installed, for the reason you mentioned in your answer. My question is: Why install anaconda then, when these packages are not readily available but only in the root/base directory of anaconda? To my understanding they are pre-installed but you can not use them when you create a new env. Or can you also just use the anaconda root/base directory as python interpreter, to enjoy all the packages being pre-installed?
comment on: http://stackoverflow.com/a/52649179
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52645182
tagged with: subprocess
answer count: 2
linked to: http://stackoverflow.com/q/13691827
upvote count: 1
has body: I'm trying to open a file with spaces in path with subprocess.call function but I can't get it working. import subprocess subprocess.call(['cmd','/c','start C:/Users/akg/Desktop/file 1.png']) I've tried also import subprocess file= '"C:/Users/akg/Desktop/file 1.png"' subprocess.call(['cmd','/c','start '+file]) But I still getting this error 1st case : , 2nd case even spliting the command whenever there is a whitespace is not working
linked to: http://stackoverflow.com/q/11846232
has comment: http://stackoverflow.com/comment/92223322
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52646056
downvote count: 0
possible better answer: http://stackoverflow.com/a/52645306
has answer: http://stackoverflow.com/a/52645306
has title: open file with spaces in path
tagged with: python-2.7
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/92222763
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52646056

http://stackoverflow.com/comment/92367307
score: 0
comment on: http://stackoverflow.com/q/52719258
type: Comment
type: QuestionComment
has text: thanks i made the changes and it worked..

http://stackoverflow.com/comment/92369613
type: QuestionComment
has text: What have you tried so far to check for redirects?
score: 0
comment on: http://stackoverflow.com/q/52721619
type: Comment

http://stackoverflow.com/comment/95666949
has text: [The latest Conda version (4.6.1) ](http://www.anaconda.com/blog/developer-blog/conda-4-6-release/) now apparently supports powershell and 'a wide variety of shells'. However, after update and initialization, powershell is still not recognizing the commands. . : File C:\Users\User\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 cannot be loaded because running scripts is disabled on this system. See about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.Will create a separate stackoverflow post and link here. Please add comment if you have a solution.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/54043739

http://stackoverflow.com/a/52607461
has comment: http://stackoverflow.com/comment/92149117
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92149213
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52606882
has comment: http://stackoverflow.com/comment/92149181
has body: In a language that does not have properties (eg. java) this is so common that it has become a standard, and all frameworks assume that getters/setters already exist. However, in python you can have properties, which are essentially getters/setters that can be added later without altering the code that uses the variables. So, no reason to do it in python. Use the fields as public, and add properties if something changes later. Note: use single instead of double underscore in your "private" variables. Not only it's the common convention, but also, double underscore is handled differently by the interpreter.
score: 1
answers question: http://stackoverflow.com/q/52606882

http://stackoverflow.com/comment/92305414
type: Comment
has text: Well, that's what you're doing. If you let `df_nan = df.iloc[:, 2:].astype(float).replace(0, np.nan)`, then you could print `df_nan.mean()` first, then `df_nan.mean(1)` afterwards.
comment on: http://stackoverflow.com/a/52689225
score: 0
type: AnswerComment

http://stackoverflow.com/q/52710760
has title: Python Code128 encoder for Code128 barcode font
type: Question
accepted answer: http://stackoverflow.com/a/52713446
tagged with: python
has body: Like the title says, I have a Code128 font that I would like to print barcodes with. However, the string needs to be encoded in Code128 to make the barcode font work. My app uses the Python3 language. There used to be an example on the web somewhere how to encode the string for a Code128 font, but I can't find it anymore. I do NOT want a string to .svg converter. I specifically want to convert a string to a Code128 encoded string. Any references, code snippets in Python3 or documentation would be appreciated. EDIT: I use the font from here.
upvote count: 6
tagged with: barcode
tagged with: python-3.x
score: 5
downvote count: 1
has comment: http://stackoverflow.com/comment/92347760
has answer: http://stackoverflow.com/a/52713446
type: AnsweredQuestion
answer count: 1
tagged with: code128
favorite count: 0
has comment: http://stackoverflow.com/comment/92347828

http://stackoverflow.com/q/52743440
answer count: 0
type: UnansweredQuestion
tagged with: package
tagged with: pip
upvote count: 1
tagged with: python
has body: Let's say I have 3 Python projects, foo, foodep, and foodepdep, all in the same directory on my filesystem. Down the line these will be pushed to a private package index, so in the install_requires section of setup.py for foo I have "foodep", and for foodep I have "foodepdep". Just doing pip install -e . will fail because all of these projects are local to my filesystem, not a package index. I tried using a requirements.txt file for foo containing -e ../foodep, but that tries to use the install_requires of foodep to get foodepdep and fails. Is there some way to keep all of this local to my filesystem while still referencing each package by name in the install_requires?
score: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/92453744
favorite count: 0
has title: Installing dependencies of dependencies on the filesystem using pip

http://stackoverflow.com/comment/92507652
comment on: http://stackoverflow.com/q/52615414
type: Comment
type: QuestionComment
has text: That is a useful trick, thanks for the input.
score: 0

http://stackoverflow.com/comment/92230571
comment on: http://stackoverflow.com/a/52649060
has text: Thanks for the quick answer! For the sake of completeness: in the case of random forest - regr_multi_RF.estimators_[0].feature_importances_
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/92346674
score: 0
has text: Possible duplicate of [How do I include negative decimal numbers in this regular expression?](https://stackoverflow.com/questions/15814592/how-do-i-include-negative-decimal-numbers-in-this-regular-expression)
comment on: http://stackoverflow.com/q/52710165
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53940694
has body: Your Best bet is datetime.datetime.strptime() function: Since you have a datetime.datetime object with you, Year can be extrected using .year attribute : Datetime Code Explanation : # Import Datetime from Datetime Package : from datetime import datetime # Initialise the String Value : string = "2018-27-12 19:21:10" # Using strptime method from datetime # Convert the String to Date in '%Y-%m-%d %H:%M:%S' Format : # Note : %m denotes 'Month' and %M denotes 'Minute' : date_time = datetime.strptime(string, '%Y-%m-%d %H:%M:%S') # Extract the Year using .year Attribute : print(date_time.year) Output : 2018 Edit : This can also be achieved using pandas.to_datetime method
answers question: http://stackoverflow.com/q/52726072
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52726072
downvote count: 0

http://stackoverflow.com/q/52720270
tagged with: python
tagged with: knn
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has title: sci-kit learn: KNeighborsClassifier - Population matrix vs. Class labels
has body: I'm trying to trying to get the class labels corresponding to the k Nearest Neighbors. Going through the docs for KNeighborsClassifier, the predict() function returns the Class labels for each data sample, and the kneighbors() function returns Indices of the nearest points in the population matrix. Here is my code: from sklearn.neighbors import KNeighborsClassifier X_train = [[1.0,2.0], [2.0, 3.0], [4.0, 5.0], [6.0, 7.0]] y_train = ['Hello', 'this', 'is', 'test'] neigh = KNeighborsClassifier(n_neighbors=2, n_jobs=8) neigh.fit(x_train, y_train) X_test = [[3.0, 3.0]] &gt;&gt;&gt; neigh.predict(xtest) array(['Hello'], dtype='&lt;U5') &gt;&gt;&gt; neigh.kneighbors(xtest) (array([[1. , 2.23606798]]), array([[1, 0]])) I want to get the class labels for the k Nearest Neighbors. What is the relationship between the population matrix and the class labels as specified in the docs?
accepted answer: http://stackoverflow.com/a/52720566
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/52720614
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/52720614
has answer: http://stackoverflow.com/a/52720566

http://stackoverflow.com/comment/92413673
comment on: http://stackoverflow.com/q/52744139
type: Comment
type: QuestionComment
has text: that's what I mean by *defined over the dataframe*. That function is just doing two comparisons, which evaluate to False and False, landing on the else condition that returns 'Other'
score: 0

http://stackoverflow.com/comment/92204514
comment on: http://stackoverflow.com/a/52621441
type: AnswerComment
type: Comment
score: 0
has text: Can you clarify what you mean by running your function in an infinite loop. A truly infinite loop would crash your program.

http://stackoverflow.com/q/52699616
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92325918
accepted answer: http://stackoverflow.com/a/52699851
has title: Writing list of items to excel sheet by separating with comma
favorite count: 0
has answer: http://stackoverflow.com/a/52699851
tagged with: python
has comment: http://stackoverflow.com/comment/92325675
has comment: http://stackoverflow.com/comment/92325717
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92325832
type: Question
has comment: http://stackoverflow.com/comment/92326022
has body: I am using xlwt package and I want to export lists to excel spreadsheet which can be written in single cells separated by comma , just like the spreadsheet below: id=['1','2','3','4'] sheet1.write(0, 0,'id') sheet1.write(0, 1,id) EXCEL OUTPUT A B id 1,2,3,4 Current output is 1234 without any comma
score: 0
upvote count: 1

http://stackoverflow.com/comment/92239486
type: QuestionComment
has text: By default np.genfromtxt uses dtype=float. You can ask np.genfromtxt to try to guess the actual type of your columns by using dtype=None. Can you share some of the data inside your .csv file.
score: 0
comment on: http://stackoverflow.com/q/52653656
type: Comment

http://stackoverflow.com/q/52722559
upvote count: 1
answer count: 1
has title: How to filter the list elements within list based on another list in python?
has comment: http://stackoverflow.com/comment/92370481
has comment: http://stackoverflow.com/comment/92370529
has comment: http://stackoverflow.com/comment/92370427
score: 0
has comment: http://stackoverflow.com/comment/92385880
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/92375891
has answer: http://stackoverflow.com/a/52722752
type: UnansweredQuestion
downvote count: 1
type: Question
has body: I have a list which contains a list as elements. Now i want to filter the elements of list based on another list when the list element consist more than 3 elements that is in another list within list. For more understanding lets say i have a list called a. a = [(1, 5, 20, 22, 24, 25), (1, 5, 20, 22, 24, 29), (1, 5, 20, 22, 24, 31), (1, 5, 20, 22, 24, 36), (1, 5, 20, 22, 24, 41), (1, 5, 20, 22, 25, 29)] Now i have another list which is b. b = [(5,20,24,25,29,36),(1,22,25,29,31,41)] What i want is i want to delete the sub-list i.e element of list a that consist more than 3 elements that is in sub-list b. Here a[0] consist of 4 elements that is in b[0] so i want to delete it. I do not want any sub list in list a that has more than 3 elements in either sub-list of b. I am so confused, what shall i do?
has comment: http://stackoverflow.com/comment/92370467

http://stackoverflow.com/comment/92413517
comment on: http://stackoverflow.com/q/52744139
score: 0
type: Comment
type: QuestionComment
has text: @Yuca it returns 'other'. So it must be an issue within the function itself. I am at a loss as to why. I did verify that running each contains() portion of the code does return True/False values.

http://stackoverflow.com/comment/92162363
score: 0
comment on: http://stackoverflow.com/q/52609695
has text: @gyx-hh added text data. Thanks for asking edits.
type: Comment
type: QuestionComment

pandas
tags question: http://stackoverflow.com/q/52728997
tags question: http://stackoverflow.com/q/52672803
tags question: http://stackoverflow.com/q/52706457
tags question: http://stackoverflow.com/q/52640007
tags question: http://stackoverflow.com/q/52614267
tags question: http://stackoverflow.com/q/52663908
tags question: http://stackoverflow.com/q/52722400
tags question: http://stackoverflow.com/q/52650413
tags question: http://stackoverflow.com/q/52645742
tags question: http://stackoverflow.com/q/52627413
tags question: http://stackoverflow.com/q/52721283
tags question: http://stackoverflow.com/q/52705423
tags question: http://stackoverflow.com/q/52630601
tags question: http://stackoverflow.com/q/52668209
tags question: http://stackoverflow.com/q/52594525
tags question: http://stackoverflow.com/q/52700894
tags question: http://stackoverflow.com/q/52681444
tags question: http://stackoverflow.com/q/52676296
tags question: http://stackoverflow.com/q/52639563
tags question: http://stackoverflow.com/q/52669226
tags question: http://stackoverflow.com/q/52730907
tags question: http://stackoverflow.com/q/52625106
tags question: http://stackoverflow.com/q/52717440
tags question: http://stackoverflow.com/q/52735334
tags question: http://stackoverflow.com/q/52634512
tags question: http://stackoverflow.com/q/52640598
tags question: http://stackoverflow.com/q/52741043
tags question: http://stackoverflow.com/q/52624832
tags question: http://stackoverflow.com/q/52707913
tags question: http://stackoverflow.com/q/52714316
tags question: http://stackoverflow.com/q/52593111
tags question: http://stackoverflow.com/q/52625864
tags question: http://stackoverflow.com/q/52662781
tags question: http://stackoverflow.com/q/52631868
tags question: http://stackoverflow.com/q/52732364
tags question: http://stackoverflow.com/q/52693081
tags question: http://stackoverflow.com/q/52677658
tags question: http://stackoverflow.com/q/52665955
tags question: http://stackoverflow.com/q/52619565
tags question: http://stackoverflow.com/q/52720634
tags question: http://stackoverflow.com/q/52699945
tags question: http://stackoverflow.com/q/52623820
tags question: http://stackoverflow.com/q/52737636
tags question: http://stackoverflow.com/q/52655834
tags question: http://stackoverflow.com/q/52731191
tags question: http://stackoverflow.com/q/52689108
tags question: http://stackoverflow.com/q/52617018
tags question: http://stackoverflow.com/q/52702676
tags question: http://stackoverflow.com/q/52657676
tags question: http://stackoverflow.com/q/52694057
tags question: http://stackoverflow.com/q/52596340
tags question: http://stackoverflow.com/q/52645495
tags question: http://stackoverflow.com/q/52685239
tags question: http://stackoverflow.com/q/52595775
tags question: http://stackoverflow.com/q/52601904
tags question: http://stackoverflow.com/q/52655656
tags question: http://stackoverflow.com/q/52726935
tags question: http://stackoverflow.com/q/52641121
tags question: http://stackoverflow.com/q/52728139
tags question: http://stackoverflow.com/q/52612393
tags question: http://stackoverflow.com/q/52744692
tags question: http://stackoverflow.com/q/52642200
tags question: http://stackoverflow.com/q/52656351
tags question: http://stackoverflow.com/q/52671308
tags question: http://stackoverflow.com/q/52744150
tags question: http://stackoverflow.com/q/52737336
tags question: http://stackoverflow.com/q/52721403
tags question: http://stackoverflow.com/q/52645514
tags question: http://stackoverflow.com/q/52595395
tags question: http://stackoverflow.com/q/52655615
tags question: http://stackoverflow.com/q/52590439
tags question: http://stackoverflow.com/q/52590752
tags question: http://stackoverflow.com/q/52732029
tags question: http://stackoverflow.com/q/52634085
tags question: http://stackoverflow.com/q/52669019
tags question: http://stackoverflow.com/q/52589054
tags question: http://stackoverflow.com/q/52594959
tags question: http://stackoverflow.com/q/52607438
tags question: http://stackoverflow.com/q/52633245
tags question: http://stackoverflow.com/q/52732174

http://stackoverflow.com/a/52643293
has comment: http://stackoverflow.com/comment/92219130
has comment: http://stackoverflow.com/comment/92219676
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/52642838
has comment: http://stackoverflow.com/comment/92219447
has body: 1. Your way to plot seems right, you can probably simplify abline_values = [slope * i + yIntercept for i in X] to abline_values = slope * X + yIntercept 2. Did you set m=0.85 in your example? It seems so, but I can not tell since you did not provide the call to the cost function. Shouldn't it be the size of the sample? If you add up all the squared errors and divide them by 2*0.85, the size of the error depends on your sample size. And since it is not a relative error and the values are rather big, it is possible that all these errors add up to that huge number. Try to set m to the size of your sample. In addition there is an error in the sign of the computation of the hypothesis value, it should be a +. Otherwise you would have a negative slope, which explains large errors as well. def computeCost(parameters, x, y): [yIntercept, slope] = parameters hypothesis = yIntercept + np.dot(x, slope) loss = hypothesis - y cost = np.sum(loss ** 2) / (2 * len(x)) return cost
downvote count: 0
has comment: http://stackoverflow.com/comment/92218976

http://stackoverflow.com/comment/92377679
type: AnswerComment
has text: I would expect a different error if that was the issue, something like loadtxt not defined
comment on: http://stackoverflow.com/a/52726248
type: Comment
score: 0

http://stackoverflow.com/comment/92137211
score: 0
comment on: http://stackoverflow.com/q/52600611
type: Comment
type: QuestionComment
has text: @Ash i tried `for i, col in enumerate(feature_cols): my_knn_for_cs4661.fit(X_train[:, i], y_train` and I got `TypeError: unhashable type: 'slice'`

http://stackoverflow.com/comment/126831969
type: QuestionComment
has text: @SuperShoot: That wouldn't work because `obj.close` is a bound method, and bound methods contain a strong reference to the object they were called on (in this case, `obj`); as a result, `obj` would always have a live reference stored within the `finalizer` itself, which would never be released to be finalized. In theory, the docs wouldn't forbid the `weakref.proxy` solution the OP used, but in practice, the `proxy` seems to be finalized first, so by the time the `finalizer` calls the finalization function, you get the `ReferenceError` the OP sees.
score: 1
comment on: http://stackoverflow.com/q/52648418
type: Comment

http://stackoverflow.com/comment/92546941
type: Comment
has text: @DavidCulbreth tbh I removed `--strict` as it wasn't necessary for the error
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52744713

http://stackoverflow.com/comment/92317719
score: 0
comment on: http://stackoverflow.com/q/52695632
type: Comment
type: QuestionComment
has text: No I’m starting with a variable (x) and it equals 0 to start off with. I am trying to scan certain columns for a certain number and every time it finds that number it does x= x + 1

http://stackoverflow.com/comment/92358866
comment on: http://stackoverflow.com/q/52708678
score: 0
type: Comment
type: QuestionComment
has text: Is this bit of code in a function that you call or just run at the start of the program before mainloop?

http://stackoverflow.com/q/52730494
has title: How to extract the minimum position of a string in a nested list
tagged with: list
score: 1
upvote count: 1
type: Question
tagged with: enumerate
has answer: http://stackoverflow.com/a/52750088
has answer: http://stackoverflow.com/a/52730663
tagged with: python-3.7
answer count: 3
has body: I have a nested list of words with lots of duplicates, and a list of uniquewords which is a set of the list words. I want to find the minimum starting point of an item in word. For instance: words = [['apple',5],['apple',7],['apple',8],['pear',9], ['pear',4] ['grape',6],['baby',3],['baby',2],['baby',87]] uniquewords = ['apple','pear','grape','baby'] I want a final result as: [0,3,5,6] I tried using enumerate(), because index() does not work on a nested list. a = [] &gt;&gt;&gt; for i in range(len(uniquewords)): ... for index,sublist in enumerate(words): ... if uniquewords[i] in sublist: ... a.append(min(index)) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 4, in &lt;module&gt; TypeError: 'int' object is not iterable I'm sensing that this does not work, because I'm not telling python to append the indexes for each of the uniquewords. How would I get there?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52730650
has comment: http://stackoverflow.com/comment/92386218
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/99159609
type: Comment
has text: instead of ```plotly.offline.plot``` , can i use something like ```plotly.offline.json``` so that i can export json with valid plotly js options so i can plot this json as per my need instaed of html
comment on: http://stackoverflow.com/a/54947575
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92256768
comment on: http://stackoverflow.com/a/52663371
has text: @NiladryKar: the main idea is that in the queryset, you use `my_date_field__range=(from_date, to_date)`, but filtering in a detail-view is already quite strange in itself.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52717364
tagged with: choregraphe
type: Question
linked to: http://stackoverflow.com/q/43153688
tagged with: zbar
has title: windows: pip install zbar cannot open include file and failed with exit status 2
score: 0
tagged with: nao-robot
answer count: 1
has answer: http://stackoverflow.com/a/52961756
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92434920
tagged with: windows
tagged with: python
has body: I need to install the zbar-library because I need it to use the qrtools-library in Python 2.7 on Windows 10. When I run pip install zbar in the windows shell I get the following response: I already followed this lead but it didn't worked. Downloading a C/C++ Compiler didn't changed anything. Then I downloaded the linked binary wheel, but then I got on my shell the following response: How can I install zbar? Edit: I need to use the qrtools library on a nao robot. I tried to install pip using putty. I tried the way described by Jordan B. (look here)So I downloaded the python file and uploaded it to the robot per File Transfer(Choregraphe). When I call python get-pip.py --user I get this error: How can I install zbar and pip on the robot?

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

http://stackoverflow.com/q/52712899
has title: How do I remove the last row in the printed list?
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92351547
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92351562
has body: The question asked of me is to do the following Print the 2-dimensional list mult_table by row and column. Hint: Use nested loops. Sample output for the given program: 1 | 2 | 3 2 | 4 | 6 3 | 6 | 9 So far I have this: mult_table = [ [1, 2, 3], [2, 4, 6], [3, 6, 9] ] for row in mult_table: for cell in row: print(cell, end=' | ') print() The output this gives me is: 1 | 2 | 3 | 2 | 4 | 6 | 3 | 6 | 9 | I need to know how I can remove the last column of | that is being printed. Thank you for your help in advance.
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92351564
has answer: http://stackoverflow.com/a/52712949

http://stackoverflow.com/comment/92406014
comment on: http://stackoverflow.com/q/52738741
score: 0
type: QuestionComment
has text: Please only use relevant tags (machine-learning removed).
type: Comment

http://stackoverflow.com/comment/111100757
comment on: http://stackoverflow.com/a/52636871
has text: `msg` is one of the parsed JSON log entries returned by `driver.get_log('performance')` see also [selenium.webdriver.chrome.webdriver.execute_cdp_cmd](https://www.selenium.dev/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.webdriver.html#selenium.webdriver.chrome.webdriver.WebDriver.execute_cdp_cmd)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92251365
type: AnswerComment
score: 0
type: Comment
has text: No, I've left them out to make the code smaller. I've added 3 dots to show that now.
comment on: http://stackoverflow.com/a/52660442

http://stackoverflow.com/a/52725297
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52725195
score: 1
downvote count: 0
has body: If you want to build a dictionary, a simple foris enough. def DogYears(): small_dog = {} small_dog[1] = 15 i = 2 for j in range(24, 80, 4): small_dog[i] = j i = i + 1

http://stackoverflow.com/q/52744484
type: Question
has body: I want configure Dask for distribute DAG's in Airflow. I have read https://airflow.apache.org/howto/executor/use-dask.html and https://distributed.readthedocs.io/en/latest/, but I don't understand how it works. I have two servers of Apache Aiflow, where to run dask-shedulers and dask-workers, that at falling of the first server everything automatically worked at the second? As I understand it Airflow put tasks in the dask-sheduler. I don't undestand how to make friends of the dask-shedulers on two servers. I don't understand why need dask-workers and what it do, I think this is some kind of unnecessary component. I don't want use CeleryExecutor and configure RabbitMQ or Redis for Celery
has answer: http://stackoverflow.com/a/56103453
tagged with: airflow
has title: How to configure DaskExecuter in Apache Airflow
answer count: 3
downvote count: 0
favorite count: 0
tagged with: dask
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/53655280
upvote count: 2
has answer: http://stackoverflow.com/a/57584093

machine-learning
tags question: http://stackoverflow.com/q/52625358
tags question: http://stackoverflow.com/q/52715621
tags question: http://stackoverflow.com/q/52643184
tags question: http://stackoverflow.com/q/52716590
tags question: http://stackoverflow.com/q/52708764
tags question: http://stackoverflow.com/q/52673694
tags question: http://stackoverflow.com/q/52660985
tags question: http://stackoverflow.com/q/52598959
tags question: http://stackoverflow.com/q/52664110
tags question: http://stackoverflow.com/q/52742509
tags question: http://stackoverflow.com/q/52729048
tags question: http://stackoverflow.com/q/52712295
tags question: http://stackoverflow.com/q/52596553
tags question: http://stackoverflow.com/q/52728417
tags question: http://stackoverflow.com/q/52678215
tags question: http://stackoverflow.com/q/52636899
tags question: http://stackoverflow.com/q/52644634
tags question: http://stackoverflow.com/q/52590111
tags question: http://stackoverflow.com/q/52696039
tags question: http://stackoverflow.com/q/52634226
tags question: http://stackoverflow.com/q/52724468
tags question: http://stackoverflow.com/q/52624870
tags question: http://stackoverflow.com/q/52677977
tags question: http://stackoverflow.com/q/52666845
tags question: http://stackoverflow.com/q/52692912
tags question: http://stackoverflow.com/q/52673610
tags question: http://stackoverflow.com/q/52592434
tags question: http://stackoverflow.com/q/52591291
tags question: http://stackoverflow.com/q/52648383
tags question: http://stackoverflow.com/q/52666862
tags question: http://stackoverflow.com/q/52598117
tags question: http://stackoverflow.com/q/52597523
tags question: http://stackoverflow.com/q/52664626
tags question: http://stackoverflow.com/q/52671474
tags question: http://stackoverflow.com/q/52648516
tags question: http://stackoverflow.com/q/52672516
tag name: machine-learning
tags question: http://stackoverflow.com/q/52675842
tags question: http://stackoverflow.com/q/52655995
tags question: http://stackoverflow.com/q/52702986
tags question: http://stackoverflow.com/q/52600611
tags question: http://stackoverflow.com/q/52706996
tags question: http://stackoverflow.com/q/52674498
tags question: http://stackoverflow.com/q/52699598
tags question: http://stackoverflow.com/q/52642940
tags question: http://stackoverflow.com/q/52684331
tags question: http://stackoverflow.com/q/52616670
tags question: http://stackoverflow.com/q/52733290
type: Tag
tags question: http://stackoverflow.com/q/52725511
tags question: http://stackoverflow.com/q/52612841
tags question: http://stackoverflow.com/q/52616650
tags question: http://stackoverflow.com/q/52595782
tags question: http://stackoverflow.com/q/52691538
tags question: http://stackoverflow.com/q/52705471
tags question: http://stackoverflow.com/q/52694636
tags question: http://stackoverflow.com/q/52701594
tags question: http://stackoverflow.com/q/52742168
tags question: http://stackoverflow.com/q/52742370
tags question: http://stackoverflow.com/q/52647892
tags question: http://stackoverflow.com/q/52690303
tags question: http://stackoverflow.com/q/52724444
tags question: http://stackoverflow.com/q/52661363
tags question: http://stackoverflow.com/q/52627739
tags question: http://stackoverflow.com/q/52595477
tags question: http://stackoverflow.com/q/52656293
tags question: http://stackoverflow.com/q/52735334
tags question: http://stackoverflow.com/q/52634512
tags question: http://stackoverflow.com/q/52637106
tags question: http://stackoverflow.com/q/52601631
tags question: http://stackoverflow.com/q/52633319
tags question: http://stackoverflow.com/q/52730922
tags question: http://stackoverflow.com/q/52737844
tags question: http://stackoverflow.com/q/52658375
tags question: http://stackoverflow.com/q/52704990
tags question: http://stackoverflow.com/q/52681601
tags question: http://stackoverflow.com/q/52642838
tags question: http://stackoverflow.com/q/52735975
tags question: http://stackoverflow.com/q/52599933
tags question: http://stackoverflow.com/q/52717630

http://stackoverflow.com/q/52664110
tagged with: tensorflow
type: Question
has body: I have got some problem for the below code of the following line new_model = load_model('124446.model', custom_objects=None, compile=True) Here is the code: import tensorflow as tf from tensorflow.keras.models import load_model mnist = tf.keras.datasets.mnist (x_train,y_train), (x_test,y_test) = mnist.load_data() x_train = tf.keras.utils.normalize(x_train,axis=1) x_test = tf.keras.utils.normalize(x_test,axis=1) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128,activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(128,activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax)) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train,y_train,epochs=3) tf.keras.models.save_model(model,'124446.model') val_loss, val_acc = model.evaluate(x_test,y_test) print(val_loss, val_acc) new_model = load_model('124446.model', custom_objects=None, compile=True) prediction = new_model.predict([x_test]) print(prediction) Errors are: Traceback (most recent call last): File "C:/Users/TanveerIslam/PycharmProjects/DeepLearningPractice/1.py", line 32, in new_model = load_model('124446.model', custom_objects=None, compile=True) File "C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\keras\engine\saving.py", line 262, in load_model sample_weight_mode=sample_weight_mode) File "C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 426, in _method_wrapper method(self, *args, **kwargs) File "C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\keras\engine\training.py", line 525, in compile metrics, self.output_names) AttributeError: 'Sequential' object has no attribute 'output_names' So can any one give me ant solution. Note: I use pycharm as IDE.
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/92258141
downvote count: 0
has answer: http://stackoverflow.com/a/56291662
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/53980337
has answer: http://stackoverflow.com/a/52711716
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92262893
answer count: 4
score: 7
has answer: http://stackoverflow.com/a/53474769
has title: AttributeError: 'Sequential' object has no attribute 'output_names'
tagged with: machine-learning
upvote count: 7

deep-learning
tags question: http://stackoverflow.com/q/52656692
tags question: http://stackoverflow.com/q/52614786
tags question: http://stackoverflow.com/q/52702653
tags question: http://stackoverflow.com/q/52712782
tags question: http://stackoverflow.com/q/52621995
tags question: http://stackoverflow.com/q/52643184
tags question: http://stackoverflow.com/q/52660985
tags question: http://stackoverflow.com/q/52598959
tags question: http://stackoverflow.com/q/52718451
tags question: http://stackoverflow.com/q/52697996
tags question: http://stackoverflow.com/q/52664110
tags question: http://stackoverflow.com/q/52642756
tags question: http://stackoverflow.com/q/52716910
tags question: http://stackoverflow.com/q/52690881
tags question: http://stackoverflow.com/q/52732128
tags question: http://stackoverflow.com/q/52696039
tags question: http://stackoverflow.com/q/52634226
tags question: http://stackoverflow.com/q/52677977
tags question: http://stackoverflow.com/q/52708821
tags question: http://stackoverflow.com/q/52664626
tags question: http://stackoverflow.com/q/52671474
tags question: http://stackoverflow.com/q/52628270
tags question: http://stackoverflow.com/q/52710348
tags question: http://stackoverflow.com/q/52616670
tags question: http://stackoverflow.com/q/52643866
tags question: http://stackoverflow.com/q/52607063
type: Tag
tags question: http://stackoverflow.com/q/52600215
tags question: http://stackoverflow.com/q/52691538
tags question: http://stackoverflow.com/q/52594994
tags question: http://stackoverflow.com/q/52710878
tags question: http://stackoverflow.com/q/52655995
tags question: http://stackoverflow.com/q/52731782
tags question: http://stackoverflow.com/q/52619535
tags question: http://stackoverflow.com/q/52663982
tags question: http://stackoverflow.com/q/52627649
tag name: deep-learning
tags question: http://stackoverflow.com/q/52717630
tags question: http://stackoverflow.com/q/52745754
tags question: http://stackoverflow.com/q/52733480

http://stackoverflow.com/q/52680207
type: Question
answer count: 2
has title: How to calculate the position difference between 2 values in a list
upvote count: 1
has answer: http://stackoverflow.com/a/52680379
favorite count: 0
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
tagged with: python
has body: Train_stations = [ "Perrache", "Ampere", "Bellecour", "Cordeliers", "Louis", "Massena" ] I started this : start_station = input("Where are you now?") ending_station = input("Where would you like to go,") final = range(start_station) - range(ending_station) print(final) It does not work because apparently I can not user range with this type of value..
has comment: http://stackoverflow.com/comment/92289097
score: 1
has answer: http://stackoverflow.com/a/52680413

http://stackoverflow.com/a/52632915
answers question: http://stackoverflow.com/q/52632832
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52632832
has body: The client-size (your ajax request), and server-size (django) are two separate entities. Thus, you will have to parse the data coming into your getAppointments route like any other request body. Regardless, request.POST in django is already a dictionary-like object: https://docs.djangoproject.com/en/2.1/ref/request-response/#querydict-objects

http://stackoverflow.com/comment/92218198
score: 0
type: QuestionComment
type: Comment
has text: Doesn't work with `'0.20.3'` :(
comment on: http://stackoverflow.com/q/52642976

http://stackoverflow.com/a/77621757
has body: You can Do This, with open(json_file) as j: try : json_config = json.load(j) except ValueError as e: json_config = e if isinstance(json_config, ValueError) : raise Exception('Invalid json: {}'.format(json_config)) As, Someone mention there The try-except block use to handle an exception and not make the program fail, but in this case you're raising another exception while already handling one, which is what python is telling you
answers question: http://stackoverflow.com/q/52725278
score: 0
type: Answer

http://stackoverflow.com/q/52727251
has comment: http://stackoverflow.com/comment/92379919
tagged with: line
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92379778
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/92380023
has comment: http://stackoverflow.com/comment/92380044
answer count: 1
has body: Suppose I have a string (not a file) that spans many lines: multiline_string = '''I met a traveller from an antique land Who said: Two vast and trunkless legs of stone Stand in the desert... near them, on the sand, Half sunk, a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them and the heart that fed; And on the pedestal these words appear: 'My name is Ozymandias, king of kings; Look on my works, ye Mighty, and despair!' Nothing beside remains. Round the decay Of that colossal wreck, boundless and bare The lone and level sands stretch far away.''' I want to get only certain lines of the string, as a single string (not as a list of strings). One way of doing it is this: pedestal_lines = "\n".join(multiline_string.splitlines()[9:12]) print(pedestal_lines) Output: And on the pedestal these words appear: 'My name is Ozymandias, king of kings; Look on my works, ye Mighty, and despair!' But that way is not very good: it has to split the string into a list of strings, index this list, then join the lists back together with the str.join() method. Not to mention, it's ugly-looking and not very readable. Is there a more elegant/pythonic way of achieving this?
tagged with: string
accepted answer: http://stackoverflow.com/a/52727455
tagged with: python
has comment: http://stackoverflow.com/comment/92379936
has comment: http://stackoverflow.com/comment/92380728
has comment: http://stackoverflow.com/comment/92379963
has title: What is the most pythonic way of printing only certain lines of a string?
has comment: http://stackoverflow.com/comment/92379939
favorite count: 0
has answer: http://stackoverflow.com/a/52727455
score: 2
downvote count: 0

http://stackoverflow.com/comment/92161129
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52613256
type: QuestionComment
has text: @Rohit-Pandey that sorts `"1000" < "200"`. Plus what if one of the numbers is negative? `strip` is safer here.

http://stackoverflow.com/q/52646055
tagged with: setup.py
type: Question
type: AnsweredQuestion
has body: I have a python project that I want to call from a c++ application. I would like to bundle all python sources together in a single shared library and link the c++ application to that library. Right now my cython setup.py creates one *.so per python source, which is very inconvenient. Here is the setup.py file: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize sourcefiles = ['project_interface.pyx', 'impl_file1.pyx'] setup( ext_modules = cythonize(sourcefiles) ) project_interface.pyx : # distutils: language = c++ import impl_file1 cdef public void HelloWorld(): print "Calling Hello World" impl_file1.helloworld_func() impl_file1.pyx : def helloworld_func(): print 'Hello World' I tried to modify setup.py to bundle all python code in a single library like this: setup( ext_modules = cythonize([Extension("my_project", sourcefiles, language='c++')]) ) Unfortunately, when executing void HelloWorld(), the application cannot file impl_file1 anymore. I get : Calling Hello World NameError: name 'impl_file1' is not defined Exception NameError: "name 'impl_file1' is not defined" in 'project_interface.HelloWorld' ignored The c++ program driving this is: #include &lt;Python.h&gt; #include "project_interface.h" int main(int argc, const char** argv){ Py_Initialize(); initproject_interface(); HelloWorld(); Py_Finalize(); return 0; } This application works correctly when compiling with multiple *.so files. Compilation is very straightforward in either cases: python setup.py build_ext --inplace mv my_project.so libmy_project.so g++ main.cpp -o main `python2-config --cflags --ldflags` -L. -lmy_project Is there any way to get the single shared library solution to work?
has answer: http://stackoverflow.com/a/52670820
has answer: http://stackoverflow.com/a/52698794
tagged with: cython
upvote count: 4
answer count: 2
possible better answer: http://stackoverflow.com/a/52698794
has title: Calling a cython library with multiple pyx files through c++
downvote count: 0
linked to: http://stackoverflow.com/q/8772966
score: 4
accepted answer: http://stackoverflow.com/a/52670820
tagged with: distutils
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/30157363

http://stackoverflow.com/comment/92165448
type: Comment
type: QuestionComment
has text: A suggestion: You could define your letters like this: `import string; letters = list(string.ascii_letters)`. Never underestimate the power of the Python standard library.
comment on: http://stackoverflow.com/q/52614470
score: 0

http://stackoverflow.com/q/52645326
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92244433
has body: A person list is displayed perfectly in person.html, but when I click the persondetails anchor tag I'm getting an error. Please let me know how to rectify this. Project urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include('example.urls')), ] app urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='home'), url(r'^about/$', views.AboutPageView.as_view(), name='about'), url(r'^data/$', views.DataPageView.as_view(), name='data'), url(r'^person/$', views.PersonPageView.as_view(), name='person'), url(r'^persondetails/(?P<pk>[-\w]+)/$', views.PersonDetailPageView.as_view(), name='persondetails'), ] views.py class PersonDetailPageView(DetailView): def details(self,pk): personDetail=get_object_or_404(Person, pk=self.kwargs.get("pk")) return redirect(request,'example/persondetails.html', {'personDetail':personDetail}) person.html {% for persons in person %} {{persons.first_name}} {{persons.first_name}} {{persons.last_name}} {{persons.email}} {% endfor %}
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52660701
has comment: http://stackoverflow.com/comment/92244479
tagged with: django-views
type: Question
has comment: http://stackoverflow.com/comment/92244390
has title: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:4000/person/persondetails/3
has answer: http://stackoverflow.com/a/52697964

http://stackoverflow.com/comment/92300581
type: QuestionComment
has text: @vash_the_stampede, if item refer to pair of strings, yes. I am trying to remove similar pair.
comment on: http://stackoverflow.com/q/52686600
score: 0
type: Comment

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

http://stackoverflow.com/comment/92355952
comment on: http://stackoverflow.com/q/52715130
score: 0
type: Comment
has text: Use a list comprehension: `[tup[0] for tup in array]`
type: QuestionComment

http://stackoverflow.com/comment/92298785
has text: Nice! This approach seems to be ~ 200 ns faster than OP's approach :)
score: 1
comment on: http://stackoverflow.com/a/52685636
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52654062
score: 4
has body: For text parsing, I would recommend using regex: import re # Read the File with open("file.txt", "r") as file: text = file.read() # replace newline with blank text.replace('\n', '') # parse the text result = re.findall(r'(?P&lt;before&gt;\w+ ){30}target(P?&lt;after&gt;\w+ ){30}', text) From there, all 30 words before are in a group called 'before' and all 30 words after are in a group called 'after' the target word -- in this example 'target'. RegEx can be really specific or really generic, depending on the pattern used. For example, the code above only allows for one space after a word and no punctuation. For a guide on python regex: https://docs.python.org/3/howto/regex.html
type: Answer
answers question: http://stackoverflow.com/q/52653805
has comment: http://stackoverflow.com/comment/92240307
has comment: http://stackoverflow.com/comment/92277512
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/52618430
score: 2
answers question: http://stackoverflow.com/q/52618355
upvote count: 2
downvote count: 0
type: Answer
has body: Given that all dictionaries in your list will have the same keys, you can use a dictionary and list comprehension: &gt;&gt;&gt; {k: [d.get(k) for d in my_list_of_dicts] for k in my_list_of_dicts[0]} {50: [2, 5, 8], 75: [3, 6, 9], 99: [4, 7, 10]}

http://stackoverflow.com/q/52634514
has comment: http://stackoverflow.com/comment/92202363
has title: subprocess gunzip throws decompression failed
tagged with: python
has body: I am trying to gunzip using subprocess but it returns the error - ('Decompression failed %s', 'gzip: /tmp/tmp9OtVdr is a directory -- ignored\n') What is wrong? import subprocess transform_script_process = subprocess.Popen( ['gunzip', f_temp.name, '-kf', temp_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE)(transform_script_stdoutdata, transform_script_stderrdata ) = transform_script_process.communicate() self.log.info("Transform script stdout %s", transform_script_stdoutdata) if transform_script_process.returncode &gt; 0: shutil.rmtree(temp_dir) raise AirflowException("Decompression failed %s", transform_script_stderrdata)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52634640
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92202539
has comment: http://stackoverflow.com/comment/92202431
has answer: http://stackoverflow.com/a/52634640

http://stackoverflow.com/comment/92234424
score: 1
type: AnswerComment
type: Comment
has text: Could you please be more specific in how to use it for a given `list`? Also, could please you produce some timings?
comment on: http://stackoverflow.com/a/52651292

http://stackoverflow.com/comment/92119548
comment on: http://stackoverflow.com/q/52590716
score: 0
has text: I think you are right. I managed to convert the labels into a float 32 by using the .values command. Then subsequently into a tensor by doing as such: data_trainlabels = np.asarray(train_labels, np.float32) data_tl = tf.convert_to_tensor(data_trainlabels, np.float32) However, the train_data will not oblige to the same thing. You say I need to get rid of the second dimension. I'll see what I can do and get back to you. Thank you
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52663536
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/92259108
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52663130
has body: Your file is quite big (11G) so you shouldn't keep all those strings in memory. Instead, process the file line by line and write the result before reading next line. This should be efficient : with open('test.txt', 'r') as input_file: with open('result.txt', 'w') as output_file: for line in input_file: prefix = line.split('@')[0] output_file.write(prefix + '\n')
type: Answer
answers question: http://stackoverflow.com/q/52663130

http://stackoverflow.com/a/52742929
has comment: http://stackoverflow.com/comment/92414540
answers question: http://stackoverflow.com/q/52741990
has comment: http://stackoverflow.com/comment/92414860
downvote count: 0
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92412776
has body: Question: Parse tabular output, loop until results a IP Address import time, re # Limit to 5 loops for n in range(5): result = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True) # Make a List from the result, spliting at NewLine _list = result.decode().split('\n') # DEBUG print("list:{}".format(_list)) # Check if Value 2 (Index==1) matches a IP Address if re.match(r'(\d+\.\d+\.\d+\.\d+)', _list[1]): print("match:{}".format(_list[1])) # End the loop break # Wait a second, before next try time.sleep(1) Tested with Python: 3.4.2

http://stackoverflow.com/q/52588733
has comment: http://stackoverflow.com/comment/92113094
has comment: http://stackoverflow.com/comment/92112976
duplicate of: http://stackoverflow.com/q/47506092
favorite count: 0
has comment: http://stackoverflow.com/comment/92112890
has comment: http://stackoverflow.com/comment/92142028
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92147235
tagged with: python
has title: Unable to get complete source code of web page using Python
has comment: http://stackoverflow.com/comment/92112844
linked to: http://stackoverflow.com/q/26393231
has comment: http://stackoverflow.com/comment/92113281
score: 2
has comment: http://stackoverflow.com/comment/92113219
answer count: 0
type: UnansweredQuestion
has body: I am learning web scraping with python and using some libraries(Beautifulsoup and requests) to get the results. But when i am trying to pull the data of any web page let's say sears product url - https://www.sears.com/tradesman-talg1670-70-inch-economy-line-aluminum-gull/p-00937054000P?plpSellerId=Sears&amp;prdNo=1&amp;blockNo=1&amp;blockType=G1 , so here i am not getting complete page source, i need to get product title, price, specifications etc. I have found a url while checking in browser's console and it contains all product details in json format but i am still unable to pull these json data. Here is a url for json format - https://www.sears.com/content/pdp/config/products/v1/products/04403935070P?site=sears And below are the codes for pulling source code: from bs4 import BeautifulSoup import requests import re import json s = requests.session() #start requests session page = s.get("https://www.sears.com/tradesman-talg1670-70-inch-economy-line-aluminum-gull/p-00937054000P?plpSellerId=Sears&amp;prdNo=1&amp;blockNo=1&amp;blockType=G1") #get the page soup = BeautifulSoup(page.content) #print(soup.encode("utf-8")) print(soup) Please check these codes and suggest me for better solution, Thanks in advance.
upvote count: 7
tagged with: python-requests
has comment: http://stackoverflow.com/comment/92113211
has comment: http://stackoverflow.com/comment/92134670
has comment: http://stackoverflow.com/comment/92113008
downvote count: 5
has comment: http://stackoverflow.com/comment/92112968
type: Question
has comment: http://stackoverflow.com/comment/92112765
has comment: http://stackoverflow.com/comment/92112993
has comment: http://stackoverflow.com/comment/92113371

http://stackoverflow.com/a/52658829
answers question: http://stackoverflow.com/q/52658795
has comment: http://stackoverflow.com/comment/92248268
has body: Since you already have the key weapon1, you really only need the value, which is already stored in selectedItem since you assigned inventoryitems["weapon1"] to it. There's no need for any further call or iteration here.
type: Answer
has comment: http://stackoverflow.com/comment/92248130
score: 0

http://stackoverflow.com/q/52738605
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: computer-vision
downvote count: 1
tagged with: opencv
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/92404086
has comment: http://stackoverflow.com/comment/92402159
tagged with: image-processing
has comment: http://stackoverflow.com/comment/92403124
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92406749
has comment: http://stackoverflow.com/comment/92462363
has body: I am writing a keypoint description procedure using opencv and python.The following picture represent a window that covers a keypoint. The features are aggregated from the pixels that this window covers. The issue I am having is with pixels that are near the edges. Is there any good way to handle the keypoint description for keypoint that are near the limits (edges) of the image. I couldn't find how this case is handled by famous feature extractors such as SIFT or SURF PS: I am using a window of 16x16 pixels
has title: Near edge keypoint feature extraction
favorite count: 0

http://stackoverflow.com/comment/130236615
type: Comment
type: QuestionComment
has text: you can check my answer here https://stackoverflow.com/a/73754249/10382054
comment on: http://stackoverflow.com/q/52662037
score: 0

http://stackoverflow.com/q/52693081
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 2
tagged with: performance
downvote count: 0
tagged with: dataframe
type: Question
upvote count: 2
tagged with: pandas
has title: Slow performance using .head() with pandas in loop
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52693649
has body: I was amazed to discover how much of a performance slowdown I incurred when using a for loop and the .head() method in pandas. I am looking for any advice to my problem, which I illustrate below. import pandas as pd import numpy as np #create dictionary of 10000 dataframes numdfs = 10000 alldf = {i:pd.DataFrame({'a':np.random.randn(250),'b':np.random.randn(250),'c':np.random.randn(250),'d':np.random.randn(250)}) for i in range(numdfs)} count = 250 runningsum = 0 for i in range(numdfs): df = alldf[i].head(count) df['is negative'] = (df['b'] &lt; 0).cummax().astype(int) runningsum += df['is negative'].max() The above code takes about 15 minutes to execute on my machine, while removing the .head(count) from the first line after the for loop makes it execute in under a minute! can someone share some perspective on why this is, and how i can enhance performance? the .head() is used because in the real example, i want to evaluate the condition up to potentially a different number of samples in the dataframes
accepted answer: http://stackoverflow.com/a/52693649

http://stackoverflow.com/q/52597614
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52597642
tagged with: mathematical-optimization
downvote count: 0
score: 1
type: Question
has title: Some Gurobi-python functions are not correctly recognized
tagged with: gurobi
has body: : My problem is the following: When I use some Gurobi functions, for example quicksum() I always get the a warning like this: " 'quicksum' may be undefined, or defined from start imports: gurobipy." The following code solve the TSP correctly. import numpy as np import matplotlib.pyplot as plt import scipy as sp import networkx as nx from gurobipy import * from openpyxl import Workbook import xlrd import networkx as nx print("") print("TRAVELING SALESMAN PROBLEM") print("---------------------------------------------------------------------") print("") wb = Workbook() ws = wb.active book = xlrd.open_workbook('TSP.xlsx') #LECTURA DE PARÁMETROS. sheet = book.sheet_by_name("C") C=[[sheet.cell_value(r,c) for c in range(sheet.ncols)] for r in range(sheet.nrows)] C=np.matrix(C) print("") print("MATRIZ DE DISTANCIAS") print("") print(C) def TSP(C): nodos=range(len(C)) nodos1=range(1,len(C),1) #CONJUNTOS. model=Model('TSP') #NOMBRE DEL MODELO. model.ModelSense=GRB.MINIMIZE #SENTIDO DE OPTIMIZACIÓN. x,u={},{} #VARIABLES - MATRIZ DE ASIGNACIÓN DE RUTAS. for i in nodos: for j in nodos: x[i,j]=model.addVar(vtype=GRB.BINARY,name="x[%s][%s]"%(i,j)) for i in nodos1: u[i]=model.addVar(vtype=GRB.INTEGER,lb=1.0,ub=len(C)-1,name="u[%s]"%(i)) model.update() costo=quicksum((C[i,j]*x[i,j] for i in nodos for j in nodos)) model.setObjective(costo) #FUNCIÓN OBJETIVO model.update() for j in nodos: model.addConstr(quicksum(x[i,j] for i in nodos)==1.0,name="R1[%s]"%(j)) #CONJUNTO 1 DE RESTRICCIONES. for i in nodos: model.addConstr(quicksum(x[i,j] for j in nodos)==1.0,name="R2[%s]"%(i)) #CONJUNTO 2 DE RESTRICCIONES. for i in nodos1: for j in nodos1: if i!=j: model.addConstr(u[i]-u[j]+(len(C)-1)*x[i,j]&lt;=len(C)-2,name="R3[%s][%s]"%(i,j)) model.update() model.__data=x,u return model model=TSP(C) model.optimize() x,u=model.__data print("") print("VALOR OPTIMO TSP= ", model.ObjVal) edges = [(i,j) for (i,j) in x if x[i,j].X == 1] model.write('ruteo.lp') print(u) print("Arcos utilizados:", edges) pri…
upvote count: 1
answer count: 1

http://stackoverflow.com/q/52723472
tagged with: glut
has body: If I run this code from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from OpenGL.GLUT.freeglut import * def on_wheel(wheel, direction, x, y): print(wheel, direction, x, y) glutInit() glutInitWindowSize(100, 100) glutCreateWindow("glutMouseWheelFunc test") glutMouseWheelFunc( on_wheel ) # Error here glutMainLoop() I get this error Traceback (most recent call last): File "...", line 28, in &lt;module&gt; glutMouseWheelFunc( on_wheel ) File ".../OpenGL/GLUT/special.py", line 148, in __call__ self.wrappedOperation( cCallback, *args ) File ".../OpenGL/GLUT/special.py", line 116, in failFunction typeName, 'glut%sFunc'%(typeName), OpenGL.error.NullFunctionError: Undefined GLUT callback function MouseWheel, check for bool(glutMouseWheelFunc) before calling Here's the solution for Windows: How to use FreeGLUT glutMouseWheelFunc in PyOpenGL program? But how can I call glutMouseWheelFunc() in pyopengl on Mac or linux? Or better: is there a portable solution?
has answer: http://stackoverflow.com/a/56553885
tagged with: pyopengl
type: Question
linked to: http://stackoverflow.com/q/10359407
has title: Using glutMouseWheelFunc from FreeGLUT in PyOpenGL?
tagged with: freeglut
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1

http://stackoverflow.com/comment/92267374
has text: @cryptonome Doesn't exactly quite address my problem being it a 2D array and counting each empty array in a easy manner.
comment on: http://stackoverflow.com/q/52668701
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92327021
type: QuestionComment
score: 2
type: Comment
has text: But what you're actually asking it seems is "can I pass a key to `sorted()` to ignore the case", the answer is yes of course (like `sorted(dict.items(), key = lambda x: x[0].casefold())`); and you could feed that to an `OrderedDict` to retain the sorted structure
comment on: http://stackoverflow.com/q/52700212

http://stackoverflow.com/a/52720192
answers question: http://stackoverflow.com/q/52719781
has body: You can use the occurence of each color/number in flist as an indication. I assume flist is a two dimensional list. import numpy as np farray = np.array(flist) prob_yellow = (farray==1).sum()/ (farray.shape[0] * farray.shape[1]) prob_purple = (farray==-1).sum()/ (farray.shape[0] * farray.shape[1]) prob_turqoise = (farray==0).sum()/ (farray.shape[0] * farray.shape[1]) another way would be to integrate nummerically if you have the x and y arrays of the lines splitting the colored planes. For example: from scipy import integrate import numpy as np x = np.arange(0,1,0.1) y_purple = np.exp(-x) prob_purple = integrate.simps(y_purple,x) Edit: I understand now that flist is not evenly distributed. In that case I would first convert it to an evenly distributed list and then use the first method mentioned. I create the points and flist: points = np.array([[0,0],[0.4, 0.5],[0.5, 0.6],[1, 1]]) flist = np.random.randint(-1,2, size=len(points)) Then do the interpolation: import scipy.interpolate as intp fintp = intp.NearestNDInterpolator(points, flist) x = np.linspace(0,1,6) y = np.linspace(0,1,6) xx, yy = np.meshgrid(x, y) positions = np.column_stack((xx.ravel(),yy.ravel())) f_evenly = fintp(positions).reshape(len(x), len(y)) and calculate the probability: prob_yellow = (f_evenly==1).sum()/ (f_evenly.shape[0] * f_evenly.shape[1]) prob_turqoise = (f_evenly==0).sum()/ (f_evenly.shape[0] * f_evenly.shape[1]) prob_purple = (f_evenly==-1).sum()/ (f_evenly.shape[0] * f_evenly.shape[1]) Check the outcome: plt.imshow(f_evenly, extent=[0,1,0,1]) plt.show() print('probabilities: \nyellow: %.2f\nturqoise: %.2f\npurple: %.2f'%(prob_yellow, prob_turqoise, prob_purple)) probabilities: yellow: 0.47 turqoise: 0.36 purple: 0.17
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92368062
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92365658

http://stackoverflow.com/a/52696753
has comment: http://stackoverflow.com/comment/92323727
has comment: http://stackoverflow.com/comment/92323396
has comment: http://stackoverflow.com/comment/92323763
has body: Yes, Pytest has inbuilt parser option for the testcase. Defined the below method in conftest.py. def pytest_addoption(parser): """ Command line options for the pytest tests in this module. :param parser: Parser used for method. :return: None """ parser.addoption("--o", default=None, actions="store" help="specify operation to be performed") Kindly refer https://docs.pytest.org/en/latest/example/simple.html for more detail. Use command:-- pytest -vsx test_custom_calculations.py --a= --o= In test method, test_custom_calculations.py def test_cal(request): value_retrieved = request.config.getoption("--a")
has comment: http://stackoverflow.com/comment/92329590
has comment: http://stackoverflow.com/comment/92324153
has comment: http://stackoverflow.com/comment/92323589
score: 0
has comment: http://stackoverflow.com/comment/92326145
has comment: http://stackoverflow.com/comment/92323556
has comment: http://stackoverflow.com/comment/92323137
has comment: http://stackoverflow.com/comment/92327882
type: Answer
has comment: http://stackoverflow.com/comment/92322870
answers question: http://stackoverflow.com/q/52695727

http://stackoverflow.com/q/52729428
tagged with: python-imaging-library
upvote count: 14
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/44636152
score: 14
has body: How to write CUSTOM metadata into JPEG with Python? I tried import piexif exif_dict = { 'uwi': myvalue1, 'activity_type': myvalue2, 'prediction': myvalue3, 'url_current': myvalue4, 'url_previous': mavalue5 } exif_bytes = piexif.dump(exif_dict) with open(filename, "w") as fp: test_image.save(fp, "JPEG", exif=exif_bytes) but see nothing in images with XnView. What am I doing wrong? P.S. I don't need to write camera model, exposure and other stuff. I want to write my own custom metadata.
has answer: http://stackoverflow.com/a/63400376
downvote count: 0
favorite count: 0
has title: How to write CUSTOM metadata into JPEG with Python?
has answer: http://stackoverflow.com/a/52729876
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/109225888
tagged with: exif

http://stackoverflow.com/comment/92360759
type: Comment
type: QuestionComment
has text: @Tomalak the "other guy" needs it that way.
score: 0
comment on: http://stackoverflow.com/q/52717176

http://stackoverflow.com/a/52596826
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92128662
type: Answer
accepted answer of: http://stackoverflow.com/q/52596200
has comment: http://stackoverflow.com/comment/92128594
answers question: http://stackoverflow.com/q/52596200
has body: You need to change the method (GET to POST) in the html file and add the method in the decorator @app.route too. Do not forget that in this case a return (GET) is required to render the html file. @app.route("/login", methods = ['GET', 'POST']) def login(): if request.method == "POST": # import pdb; pdb.set_trace() un = request.form.get('username', None) return un return render_template('form.html') Tip: Learn about pdb to debug your programs more easily. https://realpython.com/python-debugging-pdb/ https://docs.python.org/3/library/pdb.html

http://stackoverflow.com/comment/92215726
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52641676
type: Comment
has text: You'll need to use the `script_A_process` in your script B and get the returned value there. do, `from script_A import value, script_A_processs` and then do the process in script B. **Also, can you instead write down some code example, i'm not sure I got it right**

http://stackoverflow.com/q/52635152
has comment: http://stackoverflow.com/comment/92203902
has answer: http://stackoverflow.com/a/52635298
has comment: http://stackoverflow.com/comment/92234238
has comment: http://stackoverflow.com/comment/92203788
has title: Parent method being overwritten by child
upvote count: 0
answer count: 1
tagged with: inheritance
linked to: http://stackoverflow.com/q/222877
favorite count: 0
accepted answer: http://stackoverflow.com/a/52635298
has body: Let's say we have: class Parent(): def __init__(self): foo() def foo(self): //do stuff class Child(Parent): def __init__(self): Parent.__init__() class Grandchild(Child): def __init__(self): Child.__init__() def foo(self): //different stuff There are a lot of classes at the Child level that use the same foo(). Grandchild level has a slightly different version of foo, but when Grandchild is initiated, the foo() call in Parent.__init__() uses the Parent.foo() instead of Grandchild.foo(). Is there a correct practice when in comes to this kind of situation?
tagged with: python
score: -2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92203835
downvote count: 2
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/52706700
type: AcceptedAnswer
type: Answer
upvote count: 1
has body: I see in the error message that you tried to search for the value dcu alpha in the field Restaurant.campus_id (which is a ForeignKey, so in the database it will have the type of the PK of the model Campus, which is an integer). Django tries to cast the search value to an int because the field is an integer. Maybe you want to search a different field, maybe: name (the name of the Restaurant instances) or campus_id__name (the name of the Campus instance belonging to the Restaurant instances)? Or you could add error handling: def restaurants(request): query = request.GET.get('search', None) context = {} if query and request.method == 'GET': try: query_int = int(query) except ValueError: query_int = -1 results = Restaurant.objects.filter(campus_id=query_int) context.update({'results':results}) return render(request, 'eatatdcu/restaurants.html', context)
answers question: http://stackoverflow.com/q/52704505
score: 1
accepted answer of: http://stackoverflow.com/q/52704505
downvote count: 0

http://stackoverflow.com/q/52704840
has comment: http://stackoverflow.com/comment/92337035
type: AnsweredQuestion
score: 7
linked to: http://stackoverflow.com/q/26307932
type: Question
accepted answer: http://stackoverflow.com/a/52705349
tagged with: concatenation
has body: my question is very similar to Merge pandas dataframe, with column operation but it doesn't answer my needs. Let's say I have two dataframes such as (note that the dataframe content could be float numbers instead of booleans): left = pd.DataFrame({0: [True, True, False], 0.5: [False, True, True]}, index=[12.5, 14, 15.5]) right = pd.DataFrame({0.7: [True, False, False], 0.5: [True, False, True]}, index=[12.5, 14, 15.5]) right 0.5 0.7 12.5 True True 14.0 False False 15.5 True False left 0.0 0.5 12.5 True False 14.0 True True 15.5 False True As you can see they have the same indexes and one of the column is common. In real life there might be more common columns such as one more at 1.0 or other numbers not yet defined, and more unique columns on each side. I need to combine the two dataframes such that all unique columns are kept and the common columns are combined using a specific function e.g. a boolean OR for this example, while the indexes are always identical for both dataframes. So the result should be: result 0.0 0.5 0.7 12.5 True True True 14.0 True True False 15.5 False True False In real life there will be more than two dataframes that need to be combined, but they can be combined sequentially one after the other to an empty first dataframe. I feel pandas.combine might do the trick but I can't figure it out from the documentation. Anybody would have a suggestion on how to do it in one or more steps.
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52705349
tagged with: python
upvote count: 7
tagged with: merge
has title: merge two dataframes with some common columns where the combining of the common needs to be a custom function

http://stackoverflow.com/q/52635681
has answer: http://stackoverflow.com/a/52636811
score: 0
answer count: 1
tagged with: python-3.x
has body: I have the following JSON file: a_lis= [ { "id": "0394820934", "obj": [ { "fruit": "mint", "origin": "brazil", "seller": "unknown", "record": false } ], "available": false, "count": 0 }, { "id": "0239840394", "obj": [ { "fruit": "grapes", "origin": "origin", "seller": "unknown", "record": false }, { "fruit": " ", "record": false }, { "fruit": "ARN", "origin": "destination", "seller": "unknown", "record": true }, { "fruit": " no ", "record": false }, { "fruit": "apple", "origin": "unknown", "seller": "walmart", "record": false } ], "available": false, "count": 0 }, { "id": "0928293820982309", "obj": [ { "fruit": "tomato", "origin": "COL", "seller": "unknown", "record": false }, { "fruit": "Watermelon", "origin": "destination", "seller": "unknown", "record": false }, { "fruit": " ", "record": false }, { "fruit": "pear", "origin": "return_date", "seller": "walmart", "record": true } ], "available": false, "count": 0, "updated": 0 }, { "id": "23423423", "obj": [ { "fruit": "10", "origin": "usa", "seller": "cotsco", "record": false } ], "available": false, "count": 0 }, { "id": "230948", "obj": [ { "fruit": " ", "record": false }, { "fruit": "pear", "origin": "adult_companion", "seller": "sears", "record": true }, { "fruit": "apple", "record": false }, { "fruit": "Watermelon", "origin": "Japan", "seller": "unknown", "record": true }, { "fruit": " apple ", "record": false }, { "fruit": " lemon ", "origin": "Canada", "seller": "unknown", "record": true }, { "fruit": " the apple is good ", "record": false }, { "fruit": " apple ", "origin": "COL", "seller": "sears", "record": true } ], "available": false, "count": 0 } ] The above file is a list of dicts. How can I duplicate and append to a_list all the sub dictionaries that contain the word 'apple' replacing that word for the word lemon?. For example: a_lis = [ { "id": "0394820934", "obj": [ { "fruit": "mint", "origin": "brazil", "seller": "unknown", "record": false } ], "available": false, "count": 0 }, { "id": "0239840394"…
has title: How to reformat the following JSON a specific value?
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/json
type: Question

http://stackoverflow.com/comment/92344262
score: 1
comment on: http://stackoverflow.com/a/52660011
type: AnswerComment
has text: With Python 3.6+, ordered insertion into dict may obviate this recipe. `Counter`s may be ordered already.
type: Comment

http://stackoverflow.com/comment/92227941
type: Comment
has text: Maybe I just have to create manually the good dict ? `d = {'AAA' : 'group1', 'BBB' : 'group1', 'EEE' : 'group2'}` etc...
type: AnswerComment
comment on: http://stackoverflow.com/a/52647878
score: 0

http://stackoverflow.com/a/52690222
has body: On the 4th line, you define the variable config (by assigning to it) within the scope of the function definition that started on line 1. Then on line 11, outside the function (notice indentation), you try to access a variable named config in global scope (and refer to its attribute yaml) - but there isn't one. Probably you didn't mean to access the variable on that last line. Did you mean to pass the string config.yaml as the filename? Then it needs to be in quotes.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52690131

http://stackoverflow.com/a/52644406
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
has body: It's very simple. Let take step by step to clear your question. It is count the matches by 2 tuple and get the max. maxCount = 0 index = 0 for i,item in enumerate(x): count = 0 for a in element: if a in item[1]: count+=1 if maxCount &lt; count: index = i print(x[i])
type: Answer
accepted answer of: http://stackoverflow.com/q/52644046
answers question: http://stackoverflow.com/q/52644046

http://stackoverflow.com/comment/92328072
comment on: http://stackoverflow.com/q/52672939
type: Comment
type: QuestionComment
score: 1
has text: Hey @G.Anderson, I GOT IT!!!!! I broke it down the way you said....printed after every line until I figured it out. This is awesome! Thanks so much.

http://stackoverflow.com/q/52730924
upvote count: 1
possible better answer: http://stackoverflow.com/a/52730965
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52731262
score: 1
has title: Web scraping in Python - how to capture all elements
has answer: http://stackoverflow.com/a/52730980
has answer: http://stackoverflow.com/a/52730963
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has body: I'm using beautifulsoup4 to scrape data from the lyrics.com website, specifically this link: https://www.lyrics.com/album/1447935. From this block, I'm trying to extract both elements: [ # Song Duration 1 Make You Feel My Love 3:32 2 Painting Pictures 3:33 ] This is my code: url = "http://www.lyrics.com" + album_url page = r.get(url) soup = bs(page.content, "html.parser") songs = [a.get('href') for a in (table.find('a') for table in soup.findAll('table')) if a] However, it's only returning the first : ['/lyric/15183453/Make+You+Feel+My+Love'] What could be wrong? Edit: Thank you all for the answers! I upvoted but I don't have enough rep for it to show
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/52730980
has answer: http://stackoverflow.com/a/52730965
tagged with: web-scraping

http://stackoverflow.com/q/52737571
has answer: http://stackoverflow.com/a/52738225
has comment: http://stackoverflow.com/comment/92400130
has title: view function not found in django
accepted answer: http://stackoverflow.com/a/52738225
tagged with: routes
score: 0
answer count: 1
tagged with: url
tagged with: python
has body: When trying to click on a button to redirect to getonboard.html I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'getonboard' not found. 'getonboard' is not a valid view function or pattern name. artdb/urls.py: path('getonboard/',views.getonboard,name='getonboard'), templates/artdb/base.html: &lt;p&gt;&lt;a class="btn btn-primary btn-lg" href="{% url 'getonboard' %}" role="button"&gt;Get onboard &amp;raquo;&lt;/a&gt;&lt;/p&gt; artdb/views.py: def getonboard(request): return render(request,'artdb/getonboard.html') templates/artdb/getonboard.html: {% extends "artdb/base.html" %} {% block content %} &lt;h2&gt;getonboard template&lt;/h2&gt; &lt;p&gt;this is the getonboard text&lt;/p&gt; {% endblock content %} full main urls.py: """winmalist URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('artdb/', include('artdb.urls')), path('admin/', admin.site.urls), ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) full artdb/urls.py: from django.urls import path from django.views.generic import TemplateView from artdb.views import PersonList from . import views app_name='artdb' urlpatterns = [ # path('base/',views.base,name='base.html'), path('getonboard/',views.getonboard,name='getonboard'), path('index/',views.index,name='index'), path('person…
has comment: http://stackoverflow.com/comment/92400754
type: AnsweredQuestion
tagged with: django
tagged with: match
has comment: http://stackoverflow.com/comment/92400513
type: Question

http://stackoverflow.com/a/52604909
has comment: http://stackoverflow.com/comment/92151761
answers question: http://stackoverflow.com/q/52604732
has body: If you're in development environment; you can simply specify it in your Flask.run as specified here. Example: app.run(host='0.0.0.0', port='8080', debug=True) You can also take another approach at modifying the default_config as shown here. Example: app.config['DEBUG'] = True app.run(host='0.0.0.0', port='8080') or even exporting FLASK_DEBUG=1 - Keep in mind that FLASK_DEBUG overrides FLASK_ENV=development. As you can see below Flask denotes the following: Do not enable debug mode when deploying in production. Although as you stated you'd love to have debugging enabled on production; hence why I wouldn't use the Flask.run since it's meant to be used on a development environment, and I would certainly not set the FLASK_ENV to development. I would suggest you rethink the concept of debugging on production, since production is not meant for debugging; simply put, I believe your reasoning of wanting to debug on production is wrong. Another possible solution is to use the following (forked, multi-process): from werkzeug.debug import DebuggedApplication application = DebuggedApplication(app, True)
has comment: http://stackoverflow.com/comment/92144013
has comment: http://stackoverflow.com/comment/92152969
has comment: http://stackoverflow.com/comment/92149943
has comment: http://stackoverflow.com/comment/92153148
has comment: http://stackoverflow.com/comment/92152547
upvote count: 4
has comment: http://stackoverflow.com/comment/92155905
has comment: http://stackoverflow.com/comment/92155587
has comment: http://stackoverflow.com/comment/92144081
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/92144509
type: Answer
has comment: http://stackoverflow.com/comment/92150715
has comment: http://stackoverflow.com/comment/92151743

http://stackoverflow.com/comment/92226678
comment on: http://stackoverflow.com/q/52643398
has text: It happened to me, Scrapy process just gets KILLED if enough resources not available on server
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92389857
score: 0
has text: @conrad Python 3.6 (see tags)
type: QuestionComment
comment on: http://stackoverflow.com/q/52713100
type: Comment

http://stackoverflow.com/a/52618257
type: Answer
has comment: http://stackoverflow.com/comment/92191690
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52618197
has body: There are several issues with your code: You shadow sum and dict built-ins. Never do this. You correctly calculate an array of percentages but haven't linked them to keys. There is no logic to retrieve a weighted sample from your keys. The built-in random.choice already has this functionality. For efficiency, you can use sum with dict.values directly and use a dictionary comprehension to calculate weights. Since random.choices returns a list, we can use next with iter to extract the only element. from random import choices d_weights = {'A': 10, 'B': 30, 'C': 60} def percent_return(d): val_sum = sum(d.values()) d_pct = {k: v/val_sum for k, v in d.items()} return next(iter(choices(population=list(d_pct), weights=d_pct.values(), k=1))) res = percent_return(d_weights)
downvote count: 0
has comment: http://stackoverflow.com/comment/92191726

http://stackoverflow.com/comment/92207104
score: 0
comment on: http://stackoverflow.com/q/52636943
type: QuestionComment
type: Comment
has text: The answer on this question might be able to help a little, even though it's about Keras: https://stackoverflow.com/questions/41695117/understanding-stateful-lstm

http://stackoverflow.com/comment/92315419
score: 0
type: Comment
type: QuestionComment
has text: can u explain further the code, so i can accept it
comment on: http://stackoverflow.com/q/52694251

flask
tags question: http://stackoverflow.com/q/52674932
tags question: http://stackoverflow.com/q/52633511
tags question: http://stackoverflow.com/q/52647713
tags question: http://stackoverflow.com/q/52604864
tags question: http://stackoverflow.com/q/52665888
tags question: http://stackoverflow.com/q/52666182
tags question: http://stackoverflow.com/q/52637653
tags question: http://stackoverflow.com/q/52611305
tags question: http://stackoverflow.com/q/52644035
tags question: http://stackoverflow.com/q/52697848
tags question: http://stackoverflow.com/q/52735449
tags question: http://stackoverflow.com/q/52641780
tags question: http://stackoverflow.com/q/52590484
tags question: http://stackoverflow.com/q/52597057
tags question: http://stackoverflow.com/q/52641110
tags question: http://stackoverflow.com/q/52595247
tags question: http://stackoverflow.com/q/52742657
tags question: http://stackoverflow.com/q/52714103
tags question: http://stackoverflow.com/q/52705784
tags question: http://stackoverflow.com/q/52636452
tags question: http://stackoverflow.com/q/52610130
tags question: http://stackoverflow.com/q/52657775
tags question: http://stackoverflow.com/q/52680148
tags question: http://stackoverflow.com/q/52603324
tags question: http://stackoverflow.com/q/52648045
tags question: http://stackoverflow.com/q/52652775
tags question: http://stackoverflow.com/q/52736134
tags question: http://stackoverflow.com/q/52605769
tags question: http://stackoverflow.com/q/52728928
tags question: http://stackoverflow.com/q/52734352
tags question: http://stackoverflow.com/q/52629639
tags question: http://stackoverflow.com/q/52687929
tags question: http://stackoverflow.com/q/52656339
tags question: http://stackoverflow.com/q/52596096
tags question: http://stackoverflow.com/q/52709008
tags question: http://stackoverflow.com/q/52668883
tags question: http://stackoverflow.com/q/52718053
type: Tag
tags question: http://stackoverflow.com/q/52729749
tags question: http://stackoverflow.com/q/52594285
tags question: http://stackoverflow.com/q/52704407
tags question: http://stackoverflow.com/q/52730739
tags question: http://stackoverflow.com/q/52604732
tags question: http://stackoverflow.com/q/52662675
tags question: http://stackoverflow.com/q/52605853
tags question: http://stackoverflow.com/q/52715072
tags question: http://stackoverflow.com/q/52665707
tags question: http://stackoverflow.com/q/52683386
tags question: http://stackoverflow.com/q/52631660
tags question: http://stackoverflow.com/q/52647408
tags question: http://stackoverflow.com/q/52698395
tags question: http://stackoverflow.com/q/52637311
tags question: http://stackoverflow.com/q/52625193
tags question: http://stackoverflow.com/q/52662037
tags question: http://stackoverflow.com/q/52692975
tags question: http://stackoverflow.com/q/52677254
tags question: http://stackoverflow.com/q/52698767
tags question: http://stackoverflow.com/q/52726807
tags question: http://stackoverflow.com/q/52646854
tags question: http://stackoverflow.com/q/52641082
tags question: http://stackoverflow.com/q/52705248
tags question: http://stackoverflow.com/q/52730150
tags question: http://stackoverflow.com/q/52600262
tags question: http://stackoverflow.com/q/52722274
tags question: http://stackoverflow.com/q/52740796
tags question: http://stackoverflow.com/q/52733540
tags question: http://stackoverflow.com/q/52702273
tags question: http://stackoverflow.com/q/52699212
tags question: http://stackoverflow.com/q/52670097
tags question: http://stackoverflow.com/q/52620992
tags question: http://stackoverflow.com/q/52729483
tags question: http://stackoverflow.com/q/52621585
tags question: http://stackoverflow.com/q/52595741
tags question: http://stackoverflow.com/q/52657058
tags question: http://stackoverflow.com/q/52710492
tags question: http://stackoverflow.com/q/52713100
tags question: http://stackoverflow.com/q/52661209
tags question: http://stackoverflow.com/q/52682074
tag name: flask
tags question: http://stackoverflow.com/q/52745237

http://stackoverflow.com/comment/92305413
has text: @DanielPryden Thanks daniel for your answer, I currently have 2 set with 5 input raster file(.tif file for combination) taken in different visible range(blue, red, green ,red edge, nir). One data set has just one band and another data set with 2 bands. I have added two pictures to myquestion(inspection of property of the file using qgis). I want to perform raster calculation in these data(5 tif file and get 1 output .tif). I guess it means getting the data in array format and performing logical operation. Am I missing something?
comment on: http://stackoverflow.com/q/52688614
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92126570
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52595483
score: 0
has text: What makes you think the `parse()` method is even being called? Please [edit] your question again and add code showing how the class is actually being **used**.

http://stackoverflow.com/a/52674264
type: AcceptedAnswer
type: Answer
upvote count: 9
downvote count: 0
has body: You can do the following for example, to get all the pods and their status: api_response = api_instance.list_namespaced_pod(namespace, pretty=pretty, timeout_seconds=timeout_seconds, watch=watch) for i in api_response.items: print(i.metadata.name + " " + i.status.phase)
accepted answer of: http://stackoverflow.com/q/52668642
answers question: http://stackoverflow.com/q/52668642
has comment: http://stackoverflow.com/comment/119654776
has comment: http://stackoverflow.com/comment/119653754
has comment: http://stackoverflow.com/comment/119636324
score: 9

http://stackoverflow.com/q/52652339
has title: Filtering packets by src mac in scapy
type: Question
linked to: http://stackoverflow.com/q/24386000
score: 0
answer count: 1
tagged with: wifi
has answer: http://stackoverflow.com/a/52668504
accepted answer: http://stackoverflow.com/a/52668504
has body: When I filter the packets using this filter in wireshark: wlan.sa == 04.b1.67.14.bd.64 All goes perfect. However, I'm trying to do it with the following python script using scapy, but it never filter by the source mac: from scapy.all import * from datetime import datetime import traceback # import MySQLdb def getAverageSSI(): global ssiFinal return ssiFinal def setParams(): global window global timestamp global SSID global datetime global iterator1 window = 1 timestamp = datetime.now() SSID='DefaultName' iterator1 = 0 global ssiArray ssiArray = [] def myPacketHandler(pkt) : global SSID global timestamp global iterator1 global ssiArray try : if pkt.haslayer(Dot11) : ssiNew = -(256-ord(pkt.notdecoded[-4:-3])) ssiArray.append(ssiNew) diffT=(datetime.now()-timestamp).seconds if diffT&gt;window: print 'With MAC dst = %s with SSI Power= %s' %(pkt.addr1, sum(ssiArray)/len(ssiArray)) print ssiArray ssiArray = [] timestamp=datetime.now() except Exception as e: print 'Exception' print e traceback.print_exc() sys.exit(0) setParams() try: sniff(iface="wlan1", filter="ether src 04:b1:67:14:bd:64", prn = myPacketHandler, store=0) except Exception as e: print e print "Sniff AP1 Off" I have also tried to remove the filter in sniff, and put an if like the following: if pkt.addr1 == '04:b1:67:14:bd:64' : # mac xiaomi mi a1 # SSID = pkt.info; ssiNew = -(256-ord(pkt.notdecoded[-4:-3])) ssiArray.append(ssiNew) diffT=(datetime.now()-timestamp).seconds if diffT&gt;window: # query = "START TRANSACTION;" # queryBack=cur.execute(query) # query = "INSERT INTO RSSI VALUES(%d,\"AP1\",%d);"%(iterator1,ssiNew) # queryBack = cur.execute(query) print 'MAC = %s with SSI Power= %s' %(pkt.addr1, sum(ssiArray)/len(ssiArray)) ssiArray = [] # Conexion.commit() # iterator1+=1 timestamp=datetime.now() But it is only filtering by destination mac. Do you know how to properly filter by mac like in the following wireshark image? (it needs to be exactly the same behaviour than in the wireshark filter):
has comment: http://stackoverflow.com/comment/92237158
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92240783
tagged with: scapy

http://stackoverflow.com/comment/92185609
type: Comment
type: QuestionComment
score: 2
has text: Shouldn't it be `df = pd.read_html(url[0]).dropna(how='all')`? Anyway, add a `print(url)` as 1st statement in `for url in urls:` and check the output.
comment on: http://stackoverflow.com/q/52626158

http://stackoverflow.com/comment/92834659
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52962713
score: 0
has text: @Nikhil Ah, that seems to be more of an issue with erpnext and the system behind it. This question may be out of the scope of stackoverflow as this community mostly deals with more direct programming frameworks and languages rather than full stack development suites. None the less, to answer a question like this, we would need more information. What the specific javascript and python code is. Most likely additional code would need to be added to the javacscipt or python script. Your best bet would probably be to ask the erpnext community or development team as this might be common issue

http://stackoverflow.com/comment/92237217
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52652503
score: 0
has text: @wpercy -Pipe(|) that works in a shell command. Here the variable and corresponding values are in a python script ( dictionary object) and I need the output to be an input to my bash script. Should I just call the bash script in my python script?

http://stackoverflow.com/q/52673223
has body: &gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; b = np.array(a, copy=False) &gt;&gt;&gt; b array([1, 2, 3]) &gt;&gt;&gt; a[0] = 0 &gt;&gt;&gt; b array([1, 2, 3]) &gt;&gt;&gt; a [0, 2, 3] &gt;&gt;&gt; b array([1, 2, 3]) I was expecting a and b share memory when "copy=False", judging by the argument name "copy".
has comment: http://stackoverflow.com/comment/92276238
tagged with: python
has comment: http://stackoverflow.com/comment/92276228
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92276292
has title: Does np.array share memory with list when the "copy=False" when creating the np.array?
has comment: http://stackoverflow.com/comment/92276865
has comment: http://stackoverflow.com/comment/92276227
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92276249
has comment: http://stackoverflow.com/comment/92276848
score: 0

http://stackoverflow.com/comment/92246330
score: 1
comment on: http://stackoverflow.com/a/52642522
has text: thanks a heap mate ive been stuck on this for 2 days !
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52708031
has body: I have a column for which I want to get Longitude and latitude. I did research on net and folks discussed about using geopy and Nominatim. I also tried this code: def lat(x): try: gn = geocoders.GeoNames(username='yadavk') lat=gn.geocode(x)[1] return(lat) except TypeError: return(0) latitude['lat']=latitude.place.apply(lat) where place is the column name in my dataframe consisting of about 100k cities,state and countries. This code was working fine but gives me server timeout as I am requesting a lot of cities. Can anyone help me me get latitude and longitude of all the 100k cities without the need to buy subscription and also doesn't take very long to give the results. Help is much appreciated.
type: UnansweredQuestion
tagged with: python
has title: Get latitude and Longitude for column in a python dataframe
score: 1
upvote count: 1
tagged with: gis
type: Question
tagged with: geopy
has answer: http://stackoverflow.com/a/52722615
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: latitude-longitude
favorite count: 0

http://stackoverflow.com/a/52697188
downvote count: 0
type: Answer
has body: The standard pandas mean() cannot handle timedeltas. After converting the column to timedeltas, apply a custom lambda function to it: df["duration"] = pd.to_timedelta(df["duration"]) df.groupby(["month", "name"], sort=False).agg({ "name": ["size", "nunique"], "duration": [lambda x: x.mean()]})
answers question: http://stackoverflow.com/q/52697002
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52697002
score: 1
has comment: http://stackoverflow.com/comment/92322167
type: AcceptedAnswer

http://stackoverflow.com/q/52686366
favorite count: 0
upvote count: 5
type: UnansweredQuestion
has title: Can't get attribute 'Word2VecKeyedVectors' on <module 'gensim.models.keyedvectors' >
tagged with: word2vec
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/62221332
has answer: http://stackoverflow.com/a/54008875
type: Question
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/92300426
tagged with: gensim
has comment: http://stackoverflow.com/comment/92300655
tagged with: nlp
has body: I train and save a gensim word2vec model: W2V_MODEL_FN = r"C:\Users\models\w2v.model" model = Word2Vec(X, size=150, window=3, min_count=2, workers=10) model.train(X, total_examples=len(X), epochs=50) model.save(W2V_MODEL_FN) And then: w2v_model = Word2Vec.load(W2V_MODEL_FN) On one enviroment it works perfectly but in another I get the error: {AttributeError}Can't get attribute 'Word2VecKeyedVectors' on module 'gensim.models.keyedvectors' from 'C:\Users\Anaconda3_New\envs\ISP_env\lib\site-packages\gensim\models\keyedvectors.py'> So I guess it might be a package version issue? But I couldn't figure what it is. Any ideas? Thanks!

http://stackoverflow.com/a/52630589
type: Answer
answers question: http://stackoverflow.com/q/52630219
has body: Your description of what you want isn't very clear, but this produces what it seems like you want (w/o printing GET each time): def tv(): base = "ABCD" nums = "123" s4 = base[3]+nums s3 = base[2]+nums s2 = base[1]+nums for c4 in s4: for c3 in s3: for c2 in s2: for c1 in nums: print(c1+c2+c3+c4) s2 = nums s3 = nums
score: 0

http://stackoverflow.com/q/52709448
possible better answer: http://stackoverflow.com/a/52709512
type: Question
has answer: http://stackoverflow.com/a/52709512
has body: So, I have an issue that I have been trying to solve countless times over the past few hours which is: I have been trying to have the program pick a certain line in a text file, and once it has done that, it needs to use the line number that it has selected to use in another file. So let's say that the file is called "a.txt" and the other file is called "b.txt", I need the program to pick a random line (1,50) and then display the line it picked out, but then it needs to do the same with the other file, so that the same line number is picked in both files. The code that I currently have: import random with open("a.txt") as word_file: words = word_file.read().split() randomw = random.choice(words) with open("b.txt") as artist_file: words = artist_file.read().split() randname=random.choice(words) print(randomw +" "+ randname) Thanks for any help!
has answer: http://stackoverflow.com/a/52709522
score: 0
tagged with: random
has title: How do I allow Python to choose a random line from 2 text files (that are the same line) and then store them as variables?
answer count: 5
accepted answer: http://stackoverflow.com/a/52709522
has answer: http://stackoverflow.com/a/52709591
tagged with: python
has answer: http://stackoverflow.com/a/52709807
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52709538
has comment: http://stackoverflow.com/comment/92345085

http://stackoverflow.com/q/52708315
downvote count: 0
has answer: http://stackoverflow.com/a/52708373
accepted answer: http://stackoverflow.com/a/52708373
type: Question
has comment: http://stackoverflow.com/comment/92373927
has comment: http://stackoverflow.com/comment/92373644
upvote count: 3
has comment: http://stackoverflow.com/comment/92373672
answer count: 1
tagged with: regex
tagged with: delimiter
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/92343268
has body: I'm writing a Python script that should be able to split a string by two delimiters: '_' and '.', capitalize both the words that are split by the delimiters (encasing the delimiters), and then finally have the delimiters placed back where they were. So something like: this_is.an_Example string for.You should turn into: This_Is.An_Example string For.You Right now I have this: return '_'.join(x.capitalize() for x in re.split('_|\.', str)) + '\n' which is not really doing what I want it to. Any clean ways of doing this? Thanks for your help!
tagged with: python
has title: Best way to split a string by two different delimiters, capitalize the two words encasing either delimiter only, and adding both delimiters back in?
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/92180917
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52623231
has text: I have venv running already. I'm asking a more nuanced question: How do I tell venv to use a different version of python? (I'm guessing that I need to somehow install it in a local dir, and then add some line into requirements.txt ??)
score: 0

http://stackoverflow.com/a/52591963
has comment: http://stackoverflow.com/comment/92126969
accepted answer of: http://stackoverflow.com/q/52591299
has body: You can iterate over the td elements: import requests from bs4 import BeautifulSoup as soup d = soup(requests.get('http://86.43.106.118/weather/cumulus/').text, 'html.parser') new_data = [[[c.text for c in b.find_all('td')] for b in i.find_all('tr')] for i in d.find_all('table')] _, *result = new_data *new_results, footer = [list(filter(None, i)) for b in result for i in b] grouped = [{c[i]:c[i+1] for i in range(0, len(c), 2)} for c in new_results if len(c) &gt; 1] Output: [{'Dawn:': '06:42', 'Sunrise:': '07:16', 'Moonrise:': '18:03'}, {'Dusk:': '20:10', 'Sunset:\xa0': '19:36', 'Moonset:': '01:55'}, {'Daylight:': '13:28', 'Length:': '12:20', 'Phase:': 'Waxing Gibbous'}, {'Temperature': '7.9\xa0°C', 'Dew\xa0Point ': '7.1\xa0°C'}, {'Windchill': '7.4\xa0°C', 'Humidity': '95%'}, {'Heat Index': '7.9\xa0°C', 'Apparent Temperature': '5.8\xa0°C'}, {'Solar Radiation': '0\xa0W/m²', 'Evapotranspiration Today': '0.10\xa0mm'}, {'Rainfall\xa0Today': '0.2\xa0mm', 'Rainfall\xa0Rate': '0.0\xa0mm/hr'}, {'Rainfall\xa0This\xa0Month': '33.4\xa0mm', 'Rainfall\xa0This\xa0Year': '749.8\xa0mm'}, {'Rainfall\xa0Last Hour': '0.2\xa0mm', 'Last rainfall': '2018-09-20 21:52'}, {'Wind\xa0Speed\xa0(gust)': '12.2\xa0kts', 'Wind\xa0Speed\xa0(avg)': '4.1\xa0kts'}, {'Wind Bearing': '329° NNW', 'Beaufort\xa0F2': 'Light breeze'}, {'Barometer\xa0': '1000.14\xa0mb', 'Rising quickly': '1.28\xa0mb/hr'}] Then, to write to csv: import csv headers = set([i for b in grouped for i in b]) with open('cork_weather.csv', 'w') as f: write = csv.writer(f) write.writerows([list(headers), *[[c.get(i, '') for i in headers] for c in grouped]]) Output: Rainfall Today,Dusk:,Sunrise:,Dawn:,Humidity,Last rainfall,Rainfall Rate,Sunset: ,Heat Index,Phase:,Wind Speed (avg),Rising quickly,Temperature,Windchill,Rainfall Last Hour,Barometer ,Dew Point ,Rainfall This Year,Apparent Temperature,Daylight:,Beaufort F2,Moonrise:,Rainfall This Month,Length:,Evapotranspiration Today,Solar Radiation,Wind Speed (gust),Moonset:,Wind Bearing ,,…
has comment: http://stackoverflow.com/comment/92127316
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92119046
answers question: http://stackoverflow.com/q/52591299
score: 1
has comment: http://stackoverflow.com/comment/92126766
has comment: http://stackoverflow.com/comment/92127096
has comment: http://stackoverflow.com/comment/92120584
type: Answer
has comment: http://stackoverflow.com/comment/92128255
has comment: http://stackoverflow.com/comment/92119517
has comment: http://stackoverflow.com/comment/92118907
has comment: http://stackoverflow.com/comment/92118741
upvote count: 1
has comment: http://stackoverflow.com/comment/92119448
has comment: http://stackoverflow.com/comment/92128022
downvote count: 0

http://stackoverflow.com/comment/92295936
type: QuestionComment
comment on: http://stackoverflow.com/q/52683554
has text: @roganjosh "CPython can't use all cores because of the Global Interpreter Lock (GIL) that was built in" – CPython can't manipulate Python objects in more than one **thread** at the same time, though it can do it in as many **processes** as you want, thus utilising as many **cores** as you want. Moreover, there is no GIL when handling non-Python objects in CPython, therefore it can also utilise as many **cores** as you want using **threads**, as long as the GIL is released.
score: 0
type: Comment

http://stackoverflow.com/comment/92314805
type: Comment
type: QuestionComment
has text: @Infern0 This does not change the error, unfortunately.
score: 0
comment on: http://stackoverflow.com/q/52684900

http://stackoverflow.com/q/52646162
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92224885
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52646396
has body: New to pandas, so apologies if this has been asked before. I have the following: import pandas as pd d = { 'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4] } df = pd.DataFrame(d) # We want to remove values above 2. cutoff = 2 boolean_filter = df &lt; cutoff new_df = df[boolean_filter].dropna() print(new_df.head()) It's my understanding that pandas will coerce values if there's multiple types. As such, I thought the presence of nan was causing the numbers to be coerced to floats. However, even after adding .dropna() the resulting DataFrame has floats. Why is this, and how can I keep the values as ints? Replit link here.
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has title: Why does pandas boolean filtering result in floats?
has answer: http://stackoverflow.com/a/52646396

http://stackoverflow.com/comment/92238505
comment on: http://stackoverflow.com/q/52651116
score: 0
has text: What takes 350ms? How is `c` going to become 27 in a loop in which it doesn't change? Why are you using Python for something if it is time-critical? You say a maximum delay of 50ms is permissible - 50ms between what and what? Are you running on a Raspberry Pi? What's the camera? What resolution are you acquiring at because you seem happy enough to resize by a factor of 2 so why not acquire at the lower resolution up-front and only transfer 25% as much data?
type: Comment
type: QuestionComment

mkdocs
tags question: http://stackoverflow.com/q/52624102
tag name: mkdocs
type: Tag

http://stackoverflow.com/comment/92417931
score: 0
has text: Thank you, do you have any suggestions for my code? @trincot
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52746084

http://stackoverflow.com/q/52721619
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92391512
tagged with: python-3.x
has title: Check if link exist, and if redirect 301 follow redirect and check again, and if is the same domain
has comment: http://stackoverflow.com/comment/92369663
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92369613
tagged with: python
has body: I want to check if some old links are still valid: I use: response = requests.get(url).status_code if response == 200: return True But I have this cases: the url redirects to https or www, keeping the domain the url redirects to a region version, example url/en, keeping the domain the url redirect to a different domain (like a hosting page, bad domain etc) I want to follow 1,2 and if they return 200, return True, but I want to return False if the domain change , case 3 I figure out how to extract the domain: "{0.scheme}://{o.netloc}//".format(urlsplit(url)) but, I need to follow 301 redirects.
answer count: 0
tagged with: python-requests

http://stackoverflow.com/comment/140148479
has text: Also at [https://dafarry.github.io/tkinterbook/text.htm](https://dafarry.github.io/tkinterbook/text.htm)
score: 0
comment on: http://stackoverflow.com/q/52679038
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92309196
type: Comment
has text: Okay, that's clever. :-)
comment on: http://stackoverflow.com/a/52691060
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92408731
type: AnswerComment
has text: @RyszardStyczynski Given your example code, this should be enough. I guess you mean to say that your actual code & data requires a bit more work. But if this code does not work for the code in your question, let me know: perhaps I've overlooked something or there is something off.
type: Comment
comment on: http://stackoverflow.com/a/52739425
score: 0

http://stackoverflow.com/comment/92534888
type: QuestionComment
has text: I see, thanks for that. My aim was to make a table with the 4 variables as columns- basically for every time, lat, lon, there would also be a value for total.
comment on: http://stackoverflow.com/q/52680199
score: 0
type: Comment

http://stackoverflow.com/comment/92241790
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52653203
type: QuestionComment
has text: `data = s.recv(1024).decode('utf-8')` will give you *up to* 1024 bytes if they are available. What you get might be a part of a command, or it might be 10 commands. TCP is a stream protocol, which means you **cannot** assume that the data you receive will correspond to some higher-level entity like a command. You must build a protocol for that higher level entity. A simple protocol might be: a 4-byte big-ending integer length followed by that many bytes for the command. Now you can loop until you read in 4 bytes, and then loop until you read in the number of bytes specified.

http://stackoverflow.com/q/52687155
tagged with: python
possible better answer: http://stackoverflow.com/a/52687221
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52687357
tagged with: web-scraping
downvote count: 1
type: Question
score: -1
answer count: 2
accepted answer: http://stackoverflow.com/a/52687357
upvote count: 0
has body: I'm trying to do some webscraping to download all the results of euromillions, stuck with errors now. I'm using jupyter and python 3 with the modules specified. With just one link the code worked just fine but now I added a loop and some modifications and rip xD import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup years = list(range(2004,2018)) for year in years: my_urls = ('https://www.euro-millions.com/pt/arquivo-de-resultados-' + str(year),) my_url = my_urls[0] for my_url in my_urls: Client = uReq(my_url) html = Client.read Client.close() euro = soup(html, "html") containers = euro.findAll("div",{"class":"archives"}) print(containers) container = containers[0] for container in containers: data = container.a["href"].replace('/pt/resultados/','') #Usamos os [] como num dicionario, .strip tbm retira o lixo sometimes bolasN = container.ul.findAll("li",{"class":"ball"}) bolasS = container.ul.findAll("li",{"class":"lucky-star"}) bola1 = bolasN[0].text bola2 = bolasN[1].text bola3 = bolasN[2].text bola4 = bolasN[3].text bola5 = bolasN[4].text star1 = bolasS[0].text star2 = bolasS[1].text TUDO = [data, bola1, bola2, bola3, bola4, bola5, star1, star2] print(TUDO) TRACEBACK: TypeError Traceback (most recent call last) &lt;ipython-input-31-b11e2044b5ea&gt; in &lt;module&gt; 12 html = Client.read 13 Client.close() ---&gt; 14 euro = soup(html, "html") 15 containers = euro.findAll("div",{"class":"archives"}) 16 print(containers) /usr/local/lib/python3.5/dist-packages/bs4/__init__.py in __init__(self, markup, features, builder, parse_only, from_encoding, exclude_encodings, **kwargs) 244 if hasattr(markup, 'read'): # It's a file-type object. 245 markup = markup.read() --&gt; 246 elif len(markup) &lt;= 256 and ( 247 (isinstance(markup, bytes) and not b'&lt;' in markup) 248 or (isinstance(markup, str) and not '&lt;' in markup) TypeError: object of type 'method' has no len()
has comment: http://stackoverflow.com/comment/92301692
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52687221
has title: Strange error, TypeError: object of type 'method' has no len()

http://stackoverflow.com/q/52745556
type: Question
answer count: 2
has body: I tried to use len(self.inbox) before to return how many elements are in the list that holds the tuples, however, I couldn't get that to work, so I'm trying to make it so when a new element is added to inbox list, it will add one to x which will basically take the role of len(). class inbox: """Inbox class: add_new_arrival, message_count, get_unread_indexes, get_message, delete, clear""" def __init__(self): self.inbox = [] self.x = 0 def add_new_arrival(self, from_number, time_arrived, text_of_SMS): # Makes new SMS tuple, inserts it after other messages in the store. # When creating this message, its has_been_viewed status is set to False. self.x += 1 self.inbox.append(tuple([from_number, time_arrived, text_of_SMS, False])) def message_count(self): # Returns the number of sms messages in inbox return self.x inbox().add_new_arrival("from number", "time arrived", "text") print(inbox().message_count()) However, when I run the program, the print at the end will return 0, even though I add a new message with inbox().add_new_arrival(...). It should return 1 but it doesn't, and I'm not understanding.
has comment: http://stackoverflow.com/comment/92418449
has answer: http://stackoverflow.com/a/52745606
accepted answer: http://stackoverflow.com/a/52745606
has title: self variable changed in class not returning
possible better answer: http://stackoverflow.com/a/52746900
score: 0
has answer: http://stackoverflow.com/a/52746900
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52730965
has body: Was able to make it work with: for a in soup.findAll('a'): if a.parent.name == 'strong': if a.parent.parent.name == 'td': print(a["href"]) Still not sure why the other method doesn't work, though, since I've used it elsewhere in my program with no issues.
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/92387597
has comment: http://stackoverflow.com/comment/92387600
downvote count: 0
answers question: http://stackoverflow.com/q/52730924
score: 1

logging
tags question: http://stackoverflow.com/q/52708756
tags question: http://stackoverflow.com/q/52657522
tags question: http://stackoverflow.com/q/52671002
tags question: http://stackoverflow.com/q/52743879
tags question: http://stackoverflow.com/q/52604298
tag name: logging
tags question: http://stackoverflow.com/q/52613196
tags question: http://stackoverflow.com/q/52644217
tags question: http://stackoverflow.com/q/52595684
tags question: http://stackoverflow.com/q/52674257
tags question: http://stackoverflow.com/q/52653184
tags question: http://stackoverflow.com/q/52626467
tags question: http://stackoverflow.com/q/52681748
tags question: http://stackoverflow.com/q/52606526
tags question: http://stackoverflow.com/q/52743317
tags question: http://stackoverflow.com/q/52641266
type: Tag

http://stackoverflow.com/comment/92242202
type: Comment
type: QuestionComment
has text: When you say "remove non digits", Should '1A' become '1', or should it be removed
comment on: http://stackoverflow.com/q/52655415
score: 0

http://stackoverflow.com/comment/92417145
score: 1
has text: What do you mean by "not having luck"? If you want to ignore files that are already tracked you have to tell git that these files should be deleted from source control `git rm --cached setting_staging.py`
comment on: http://stackoverflow.com/q/52746223
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52728575
tagged with: python
has body: I have a 21:9 image with 1920x816 resolution, and i want to add black bars on top and bottom in order to comapre it with same one with 1920x1080 resolution . I tried 2 solutions for that, one using OpenCV and second using Image from Pillow. However, both of those reduced quality of images. Not edited images are taken from video file using VapourSynth and FFMS2. Comparison between files: (1920x816 frame.png and 1920x1080 frame.png are not edited files) https://diff.pics/rKVbxTRRPG35 Am i missing some important options that will prevent quality loss? Or should i use different library for that? Code that i used for OpenCV: import cv2 img = cv2.imread('1920x816 frame.png') color = [0, 0, 0] top, bottom, left, right = [132, 132, 0, 0] img_with_border = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) cv2.imwrite("1920x1080 after OpenCV.png", img_with_border) And for Pillow: from PIL import Image, ImageOps old_im = Image.open("1920x816 frame.png") new_im = ImageOps.expand(old_im, border=(0, 132)) new_im.save("1920x1080 after Pillow.png", "PNG")
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52729536
type: Question
has comment: http://stackoverflow.com/comment/92383351
tagged with: image-processing
answer count: 2
has answer: http://stackoverflow.com/a/52728975
score: 0
has title: Adding black borders to image without quality loss

http://stackoverflow.com/comment/98308148
has text: Thank you for this answer! To explain my own confusion: The `pytz` documentation says to avoid setting `tzinfo` when creating a `datetime.datetime`, but it doesn't really say anything about not using `combine()` with a localized `datetime.time` instance (it never mentions `datetime.time` at all). I could have guessed to do it this way, though I wouldn't have known if it is recommended... Seeing this question and your answer is helpful!
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52734072

http://stackoverflow.com/comment/92268481
comment on: http://stackoverflow.com/a/52652101
type: AnswerComment
score: 0
type: Comment
has text: I can be done, but every instance has different backgrounds and different codes for the on_press event. Both still need to be edited after the instantiation.

http://stackoverflow.com/q/52705416
tagged with: python
has body: DESCRIPTION: I have a string with a word, a number, bracket, and a letter inside the bracket. QUESTION: I want to extract only the numbers with decimal and the bracket with a letter in it. EXAMPLE: , INC., 5.5(b) -------&gt; 5.5(b) Section 13.2(k)(ii) ---------&gt; 13.2(k)(ii) WBNEOGNOFD.)! 82.3(b)(k)(ix) -----------&gt; 82.3(b)(k)(ix) ATTEMPT I MADE: Find the first number then the decimal, followed by '('. But, sometimes, its only 1 number and no brackets after the decimal. SOLUTION I THINK WOULD SOLVE BUT I COULD NOT SOLVE IT: curly brace repetition qualifiers {} to match exactly three alphabetic characters and exactly four numeric characters. I tried the answer given by Christian Dean to solve for my regex, but it did not give an accurate result. (Extract string with specific format)
tagged with: regex
has comment: http://stackoverflow.com/comment/92337334
type: AnsweredQuestion
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/92337293
downvote count: 1
type: Question
has title: Extract specific format from a string, regex, python
has answer: http://stackoverflow.com/a/52705504
answer count: 1
has comment: http://stackoverflow.com/comment/92337463
tagged with: string
linked to: http://stackoverflow.com/q/45136598
favorite count: 0
accepted answer: http://stackoverflow.com/a/52705504
has comment: http://stackoverflow.com/comment/92337281

recursion
type: Tag
tags question: http://stackoverflow.com/q/52624019
tags question: http://stackoverflow.com/q/52673105
tags question: http://stackoverflow.com/q/52652407
tags question: http://stackoverflow.com/q/52656381
tags question: http://stackoverflow.com/q/52600645
tags question: http://stackoverflow.com/q/52656515
tag name: recursion
tags question: http://stackoverflow.com/q/52642240
tags question: http://stackoverflow.com/q/52741824
tags question: http://stackoverflow.com/q/52744804
tags question: http://stackoverflow.com/q/52703647
tags question: http://stackoverflow.com/q/52745085
tags question: http://stackoverflow.com/q/52664372
tags question: http://stackoverflow.com/q/52746084
tags question: http://stackoverflow.com/q/52639216
tags question: http://stackoverflow.com/q/52667072
tags question: http://stackoverflow.com/q/52693515
tags question: http://stackoverflow.com/q/52695861
tags question: http://stackoverflow.com/q/52684221
tags question: http://stackoverflow.com/q/52638534

http://stackoverflow.com/comment/92197107
has text: @ShadowRanger I'm using mininet which, as far as I know, does not support Python 3. This is the reason I'm using Python 2.7
comment on: http://stackoverflow.com/q/52631809
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52728498
answers question: http://stackoverflow.com/q/52728368
type: Answer
score: 1
upvote count: 1
has body: First I would extend the range to y+1 then take all the odds in that range, after I would check if x and y were even if so i would add them to the list. x = int(input('Enter first number: ')) y = int(input('Enter second number: ')) tot = [i for i in range(x, y+1) if i % 2] if not x % 2: tot.append(x) if not y % 2: tot.append(y) print(sum(tot))
downvote count: 0

http://stackoverflow.com/q/52703522
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/92335464
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/92335177
type: Question
has comment: http://stackoverflow.com/comment/92335859
has body: Environment: OS: redhat python version: 3.6 django: 2.1 django channels: 2.1.3 The following is my logging.conf file (same level as settings.py): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } django_logger = logging.getLogger('django') and the function to log as follows: def log_it(*args): try: django_logger.info(str(args).encode('utf-8')) return True except: django_logger.info('#### Exception in LOGGING!!!!!!') return False I am using this to log inside django consumers as follows: class EchoConsumer(SyncConsumer): def websocket_connect(self, event): try: log_it('inside EchoConsumer connect()', event) self.send({ "type": "websocket.accept", }) return True except: error = traceback.format_exc() write_error_log(error) return False def websocket_receive(self, event): try: log_it('inside EchoConsumer receive()', event) self.send({ "type": "websocket.send", "text": event["text"], }) return True except: error = traceback.format_exc() write_error_log(error) return False The log_it() used inside the consumers aren't being invoked. (Assumption: Integrating channels with django must have overriden the django logging settings) I checked if there was any problem in reaching the consumers in the daphne access logs. I also checked my nginx conf, but the connection requests were recorded as follows: 127.0.0.1:45100 - - [08/Oct/2018:19:00:58] "WSCONNECTING /ws/event/" - - 127.0.0.1:45100 - - [08/Oct/2018:19:00:58] "WSCONNECT /ws/event/" - - Note: I have linked /ws/event to EchoConsumer in routing.py My expectation is: 127.0.0.1:45100 - - [08/Oct/2018:19:00:58] "WSCONNECTING /ws/event/" - - 127.0.0.1:45100 - - [08/Oct/201…
upvote count: 2
has comment: http://stackoverflow.com/comment/92334544
favorite count: 0
has comment: http://stackoverflow.com/comment/92334015
has comment: http://stackoverflow.com/comment/92335922
has comment: http://stackoverflow.com/comment/92334334
has title: logs inside django channels consumers not showing up
type: UnansweredQuestion
tagged with: django-channels
tagged with: django

http://stackoverflow.com/comment/92172640
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52619262
has text: Why not package the results of the parse into a dice, or even an instance of a class designed to hold those results? It avoids hacking the local namespace, and could include the parser function (for neatness) too.

http://stackoverflow.com/q/52727814
score: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92382885
accepted answer: http://stackoverflow.com/a/52729196
upvote count: 2
has body: I've been playing around with activation functions for a binary classification model in keras. For example, I've implemented a logit model with Dense(1, activation='sigmoid'), and I've implemented a cloglog model as follows: import numpy as np from keras.layers import Input, Dense from keras.models import Model import keras.backend as K np.random.seed(42) # Some Data nrows = 1000 ncols = 20 X = np.random.rand(nrows, ncols) - 0.5 CF = np.random.rand(ncols, 1) y = np.sign(X.dot(CF)) y[np.where(y == -1)] = 0 # cloglog model def cloglog(x): return -(K.exp(-K.exp(x))-1) input = Input(shape=(ncols,)) output = Dense(1, activation=cloglog)(input) model = Model(input, output) model.compile(loss='binary_crossentropy', optimizer='adam') model.fit(X, y, epochs=10) I'd really like to try out a probit model, but I'm struggling to implement the link function with just the operations available in keras.backend. Is this going to be possible? Or do I really need the distribution functions (pdf/cdf) available in scipy?
tagged with: classification
has title: probit regression in keras
tagged with: python
possible better answer: http://stackoverflow.com/a/57506865
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/57506865
type: Question
has answer: http://stackoverflow.com/a/52729196
tagged with: keras
answer count: 2
has comment: http://stackoverflow.com/comment/92381623

http://stackoverflow.com/a/52738761
score: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52736933
answers question: http://stackoverflow.com/q/52736933
has body: Figured it out. Turns out you have to you have json.dumps(data_dict) the whole dict after jsonifying the dataframes. You can then reload them in using json.loads(), then dejsonify the dataframe.
type: Answer
upvote count: 4

http://stackoverflow.com/comment/92496035
comment on: http://stackoverflow.com/a/52698781
type: AnswerComment
type: Comment
score: 1
has text: @Farzan the class would execute them in the order they are received.

http://stackoverflow.com/comment/92371540
type: AnswerComment
score: 0
type: Comment
has text: Such a stupid mistake...thank you Jondiedoop for spotting it
comment on: http://stackoverflow.com/a/52723064

http://stackoverflow.com/a/52591391
has comment: http://stackoverflow.com/comment/92121323
has body: Add the keyword start before the command to execute it in a new prompt. to open the python interactive shell in a new cmd prompt. start python to execute a python file new.py in a new cmd prompt. start python new.py EDIT: here is the complete code to execute the scripts on different cmd prompts @echo off echo "this is the main batch script" for /d %%i in (C:\Test\*) do ( start python "%%i\example.py" ) pause
accepted answer of: http://stackoverflow.com/q/52590878
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92120090
answers question: http://stackoverflow.com/q/52590878
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/52609828
type: UnansweredQuestion
has title: The uninstall.dat file cannot be found in postgreSQL
type: Question
has body: I want to uninstall PostgreSQL and reinstall it again. I found out that the application was not properly installed. I have tried all the steps to uninstall it but it still results in the same outcome. After I click "uninstall", I get this message: "The uninstall.dat file cannot be found and is required to uninstall the application, aborting". There is an uninstall.dat file in PostgreSQL. I've tried changing it in Notepad and Editpad but still get the "cannot be found" message. And I've tried many times without success. Please is there any solution to this issue?
tagged with: database
upvote count: 8
answer count: 1
favorite count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/93061720
tagged with: uninstallation
tagged with: python
has answer: http://stackoverflow.com/a/53082640
score: 8
downvote count: 0

http://stackoverflow.com/q/52740009
has answer: http://stackoverflow.com/a/52740355
has answer: http://stackoverflow.com/a/52740219
tagged with: django
tagged with: python
has body: I have a function that does operations on a Django model instance, and I'm trying to break it up into sub operations that can be used independently. However, this means that I end up calling .save on each change and trigger a DB request. def subop1(instance): instance.a1 = 1 instance.save() def subop1(instance): instance.a2 = 2 instance.save() def subop1(instance): instance.a3 = 3 instance.save() def main_op(instance): subop1(instance) # triggers 1 DB request subop2(instance) # triggers 1 DB request subop3(instance) # triggers 1 DB request Is there any way to avoid having .save triggering a DB request every time while still keeping each function independently functional? Maybe some way of deferring the .save operations until some context manager exits and then saving all at once with 1 DB request. Tried to read through transaction documentation but I didn't find anything that fit.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52740064
score: 1
has answer: http://stackoverflow.com/a/52740064
upvote count: 1
has title: Django: any way to execute consecutive model.save() operations as 1 single DB request?
accepted answer: http://stackoverflow.com/a/52740355
type: Question
tagged with: database
answer count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/52766530
has body: Integration of the Gaussian pdf gives the cumulative density function, cdf. So, what you need is scipy.stats.norm.cdf. And that one supports vectorized evaluations, so no need for a for-loop in your code. Note that cdf integrates from the negative infinity. Also, the sigma parameter is called scale.
score: 0
answers question: http://stackoverflow.com/q/52745546
type: Answer

http://stackoverflow.com/comment/92489821
type: Comment
has text: `_Element.addnext()` is an `lxml` method you can find at the link at the bottom of the answer. `._new_r()` is a method added to the `CT_P` class by the metaclass underlying `BaseOxmlElement` (in `docx.oxml.xmlchemy` roughly [here](https://github.com/python-openxml/python-docx/blob/master/docx/oxml/xmlchemy.py#L286) as a result of the `r = ZeroOrMore('w:r')` child element declaration in `CT_P` [here](https://github.com/python-openxml/python-docx/blob/master/docx/oxml/text/paragraph.py#L16). This metaclass is how custom element classes are created customized to the particular element.
comment on: http://stackoverflow.com/a/52745782
score: 0
type: AnswerComment

http://stackoverflow.com/a/52678964
has comment: http://stackoverflow.com/comment/92286645
has body: You could use the histogram function from numpy: import numpy as np import random from collections import Counter L = [] ll, lu = 0, 45 # set bounds for random samples for x in range(0, 2): L.append([]) for y in range(0, 3): L[x].append(random.randint(ll,lu) + 1) bcen=np.linspace(ll, lu, lu+1) # centers bed=np.linspace(ll-0.5, lu+0.5, lu+2) #edges cnts, bed =np.histogram(L, bins=bed) print('Random integers') print(L) print('Counts') print(np.append(bcen.reshape(-1,1),cnts.reshape(-1,1), axis=1)) Note: I made your list smaller, just so that the print out is readable, but just adjust it as you wish.
has comment: http://stackoverflow.com/comment/92286602
answers question: http://stackoverflow.com/q/52678589
score: 0
has comment: http://stackoverflow.com/comment/92286677
type: Answer

http://stackoverflow.com/comment/92388987
comment on: http://stackoverflow.com/q/52731889
score: 0
type: Comment
type: QuestionComment
has text: You're making us guess where the error happens, and you're making us guess how this code is called. Please edit the question to include the full error traceback message, and an example of how you call the code.

http://stackoverflow.com/q/52728641
type: Question
has body: How to get a column values when dates are between some dates like 2015-01-01 and 2015-03-01 or create a new DataFrame of all columns for dates between 2015-01-01 and 2015-03-01 This is my current code: from datetime import date from nsepy import get_history sbin = get_history(symbol='SBIN', start=date(2015,1,1), end=date(2015,1,10)) This is the input data: Symbol Series Prev Close Open High Low Last Close \ Date 2015-01-01 SBIN EQ 311.85 312.45 315.00 310.70 314.0 314.00 2015-01-02 SBIN EQ 314.00 314.35 318.30 314.35 315.6 315.25 2015-01-05 SBIN EQ 315.25 316.25 316.80 312.10 312.8 312.75 2015-01-06 SBIN EQ 312.75 310.00 311.10 298.70 299.9 299.90 2015-01-07 SBIN EQ 299.90 300.00 302.55 295.15 301.4 300.15 I have a DataFarme that has data for many years and i quite often need to plot small samples of it (different samples based on the dates) and i would need a function to split my dataFrame based on some dates. for instance, a new dataFrame with the same columns but for these dates only 2015-01-01 -2015-03-01
has answer: http://stackoverflow.com/a/52728940
answer count: 2
has comment: http://stackoverflow.com/comment/92388406
has comment: http://stackoverflow.com/comment/92412705
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52728865
has comment: http://stackoverflow.com/comment/92388412
type: UnansweredQuestion
has title: Get a column values based on anther column using python

http://stackoverflow.com/comment/92355821
type: Comment
has text: Maybe try make a mask of area you dont want to blur. Then blur the rest and add them ?
comment on: http://stackoverflow.com/a/52715020
type: AnswerComment
score: 0

http://stackoverflow.com/q/52717319
has answer: http://stackoverflow.com/a/52721121
tagged with: ssl
tagged with: ssl-certificate
has comment: http://stackoverflow.com/comment/92364499
upvote count: 3
has answer: http://stackoverflow.com/a/52717582
downvote count: 1
has title: failing at downloading an image with "urllib.request.urlretrieve" in Python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92364461
possible better answer: http://stackoverflow.com/a/52717582
tagged with: python
has comment: http://stackoverflow.com/comment/92364717
score: 2
has comment: http://stackoverflow.com/comment/92367340
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92364891
accepted answer: http://stackoverflow.com/a/52721121
tagged with: web-crawler
type: Question
has body: If possible point the solution as well My Code: import random import urllib.request def download_web_image(url): name = random.randrange(1,1000) fullname = str(name) + ".jpg" urllib.request.urlretrieve(url, fullname) download_web_image("https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg") The Error: 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 do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAIL…
answer count: 2
has comment: http://stackoverflow.com/comment/92364608

http://stackoverflow.com/comment/92150151
has text: Did you switch to that iframe?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52607969
type: Comment

http://stackoverflow.com/comment/136676877
score: 0
has text: I checked the source code and it uses gcs blob.open: https://cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.blob.Blob#google_cloud_storage_blob_Blob_open According to the GCS docs this does indeed as promised and will read only chunks and not the whole blob all at once
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/59936600

http://stackoverflow.com/a/52589536
has body: df["previous"] = df.x.shift(1) df["previous_rolling_sum"] = df.previous.rolling(2).sum() df['x'] = np.where(df["previous_rolling_sum"]&gt;0, 5, 10)
type: Answer
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52589348
answers question: http://stackoverflow.com/q/52589348
score: 1

http://stackoverflow.com/a/52630393
has comment: http://stackoverflow.com/comment/140238359
score: 7
has comment: http://stackoverflow.com/comment/124619305
has body: This is not the optimal solution, but it's better than nothing. Maybe somebody comes with a better answer. Here is what I did 1. alias emb for starting IPython.embed() 1.1. Steps Made ~/.pdbrc file1 with the following contents !print('Use "emb" to enter IPython shell') alias emb from IPython import embed; embed() 1.2. Short explanation When pytest is ran with --pdb flag, it starts standard library pdb, or if installed, pdbpp. The standard library pdb documentation says: If a file .pdbrc exists in the user’s home directory or in the current directory, it is read in and executed as if it had been typed at the debugger prompt. This is particularly useful for aliases. If both files exist, the one in the home directory is - read first and aliases defined there can be overridden by the local file. The exclamation point (!) is a general prefix for python commands in pdb 2. Usage Example Run pytest --pdb (same .py file as in the question). As you can see from the figure, tab completion for the variable some_variable works. [1] ‪C:\Users\<USER>\.pdbrc (Windows) or /home/<USER>/.pdbrc (Linux/Mac)
upvote count: 8
has comment: http://stackoverflow.com/comment/140241730
type: Answer
answers question: http://stackoverflow.com/q/52626799
downvote count: 1

http://stackoverflow.com/comment/92149797
has text: Please the actual code as text and not a picture.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52607862
score: 4

http://stackoverflow.com/comment/92307452
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52690117
has text: the OP does not specify in his question that words will contain punctuation marks.

http://stackoverflow.com/q/52699385
has comment: http://stackoverflow.com/comment/92325305
answer count: 2
tagged with: pandas
has title: How to specify end of a row when reading csv with pandas
has comment: http://stackoverflow.com/comment/92325281
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 2
upvote count: 2
has body: I want to read a csv file that looks something like this: STATIONS_ID;MESS_DATUM;QN_9;TT_TU;RF_TU;eor 1975;2016032200; 3; 5.9; 89.0;eor 1975;2016032201; 3; 5.5; 86.0;eor 1975;2016032202; 3; 5.4; 87.0;eor 1975;2016032203; 3; 4.7; 90.0;eor ... I use: import pandas as pd stats = pd.read_csv('data/temp_fuhlsbuettel_akt.txt', sep=';') And the result is: The eor column looks annoying and I have to get rid of it with: stats = stats.drop('eor', 1) Is there a better way to read this file without creating the eor column?
has answer: http://stackoverflow.com/a/52699483
type: Question
has answer: http://stackoverflow.com/a/52699723

http://stackoverflow.com/a/52651081
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52651039
answers question: http://stackoverflow.com/q/52651039
type: Answer
score: 1
upvote count: 1
has body: Just add in Date to your groupby: df.groupby(['ID_Code','Date']).apply(lambda x: (x'Status1','Status2' == 'Not').all(1).sum()/len(x)*100) ID_Code Date A 01-23-18 0.0 B 01-24-18 50.0 C 01-24-18 100.0 01-25-18 50.0 dtype: float64 # To get as a standard dataframe, add in `.reset_index()` # df.groupby(['ID_Code','Date']).apply(lambda x: (x'Status1','Status2' == 'Not').all(1).sum()/len(x)*100).reset_index()
has comment: http://stackoverflow.com/comment/92235853
type: AcceptedAnswer

c++
tags question: http://stackoverflow.com/q/52613794
tags question: http://stackoverflow.com/q/52744801
tags question: http://stackoverflow.com/q/52691511
tags question: http://stackoverflow.com/q/52701748
tags question: http://stackoverflow.com/q/52691337
tags question: http://stackoverflow.com/q/52700642
tags question: http://stackoverflow.com/q/52709235
tags question: http://stackoverflow.com/q/52745343
tags question: http://stackoverflow.com/q/52690339
type: Tag
tags question: http://stackoverflow.com/q/52658083
tags question: http://stackoverflow.com/q/52600067
tags question: http://stackoverflow.com/q/52657173
tags question: http://stackoverflow.com/q/52688616
tags question: http://stackoverflow.com/q/52736473
tags question: http://stackoverflow.com/q/52700096
tag name: c++
tags question: http://stackoverflow.com/q/52644413
tags question: http://stackoverflow.com/q/52652373

http://stackoverflow.com/comment/92149205
type: Comment
comment on: http://stackoverflow.com/q/52607455
score: 1
type: QuestionComment
has text: If that's your exact full code, then it's not a surprise if "nothing happens" - you need to call your `split()` function at some point. Else please post a proper MVCE. Also, as zwer mentions, you definitly don't need a csv parser here.

http://stackoverflow.com/a/52670777
has comment: http://stackoverflow.com/comment/92273541
answers question: http://stackoverflow.com/q/52670383
score: 1
has body: Here's another variation that avoids doing an if test on every iteration. It also uses randrange, which is slightly more efficient than randint. from random import randrange lst = [randrange(hi) for num, hi in ((5, 51), (2, 13)) for _ in range(num)] print(lst) typical output [10, 31, 46, 25, 23, 6, 5] This is equivalent to lst = [] for num, hi in ((5, 51), (2, 13)): for _ in range(num): lst.append(randrange(hi)) The outer loop selects num, the number of items in the sublist, and hi the size of the random range for that sublist; the inner loop generates the required amount of random numbers in the desired range. FWIW, here's some timeit code comparing the various algorithms that have been submitted. It also verifies that they produce the same results when given the same random seed. My simple verification code uses eval, so it can only test expressions, not statements, so it can't test jpp's or Abhishek's code; besides, jpp's Numpy code gives different results anyway, since it uses a different seeding algorithm. Please see the timeit docs for info on what timeit does, and how to interpret the results. from timeit import Timer import random from random import randint, randrange, seed from itertools import chain, repeat, starmap from functools import partial import numpy as np imports = 'random, randint, randrange, seed, chain, repeat, starmap, partial, np' commands = ( ('Martijn', '', '[randint(0, 50 if i &lt; 5 else 12) for i in range(7)]'), ('Martijn_partial', 'rint50 = partial(randint, 0, 50); rint12 = partial(randint, 0, 12)', '[rint() for rint in [rint50] * 5 + [rint12] * 2]' ), ('Patrick', '', '[randint(*bounds) for bounds in [(0, 50)]*5 + [(0, 12)]*2]'), ('Patrick_chain', '', '[randint(*bounds) for bounds in chain(repeat((0, 50), 5), repeat((0, 12), 2))]' ), ('Ralf', '', '[randint(0,50) for i in range(5)] + [randint(0,12) for i in range(2)]'), ('Abhishek', '', 'l = [random.randint(0,50) for i in range(5)];' 'l.extend([random.randint(0,12) for i in range(2)])' )…
upvote count: 2
downvote count: 1
type: Answer

http://stackoverflow.com/q/52743032
has title: How can I get metrics from cloudwatch with Python?
score: 1
upvote count: 1
tagged with: amazon-cloudwatch
type: Question
has body: I'm trying to get some custom metrics from AWS Cloudwatch with Python, but I'm having some issues. This is the code: import boto3 from datetime import datetime client = boto3.client('cloudwatch', region_name='us-east-1') response = client.get_metric_data( MetricDataQueries=[ { 'Id': 'lambda', 'MetricStat': { 'Metric': { 'Namespace': 'metrics.tcc', 'MetricName': 'responseTime', 'Dimensions': [ { 'Name': 'target', 'Value': 'target' }, { 'Name': 'interval', 'Value': 'interval' }, { 'Name': 'requestId', 'Value': 'coldstarts', }, { 'Name': 'isColdStart', 'Value': 'isColdStart' }, ] }, 'Period': 60, 'Stat': 'Maximum', 'Unit': 'Milliseconds' }, }, ], StartTime = datetime(2018, 10, 8), EndTime = datetime(2018, 10, 9) ) print(response) In the response, I just got a JSON with these elements: [('ResponseMetadata', {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '2217d5b3...', 'HTTPHeaders': {'x-amzn-requestid': '2217d5b3...', 'date': 'Wed, 10 Oct 2018 14:31:10 GMT', 'content-length': '483', 'content-type': 'text/xml'}}), (u'MetricDataResults', [{u'Timestamps': [], u'StatusCode': 'Complete', u'Values': [], u'Id': 'lambda', u'Label': 'responseTime'}])] What I'm doing wrong? I will appreciate your help, I've tried a lot of changes, but it doesn't work.
has answer: http://stackoverflow.com/a/55826559
answer count: 1
downvote count: 0
tagged with: amazon-web-services
favorite count: 0
tagged with: aws-lambda
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52686458
tagged with: python-3.x
tagged with: terminal
accepted answer: http://stackoverflow.com/a/52687641
tagged with: python
tagged with: curses
score: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/566746
type: Question
has body: I am using curses to print a pretty nice console UI, and I need for that something to be dependent of the terminal size. For this, I read here, that I could use shutil.get_terminal_size. So I'm doing this code : def display(self): size_x,size_y = shutil.get_terminal_size() print(size_x,size_y) window_stat = curses.newwin(size_y,size_x//2-5,0,0) window_alert = curses.newwin(size_y,size_x//2-5,0,size_x//2+5) window_alert.addstr("\n " + self.alert2string()) window_stat.addstr("\n " + self.stat2string()) window_alert.box() window_stat.box() self.stdscr.refresh() window_stat.refresh() window_alert.refresh() But the fast is that, it is working perfectly the first time I call the function, but if I use my mouse to change the terminal size and recall the function, the result of shutil.get_terminal_size() will always stay the same. (120 30). Do you have any idea of where it could come from ? (I'm running Windows actually, and I'd like it to work under all common OS) Thanks a lot everyone !
has answer: http://stackoverflow.com/a/52687641
upvote count: 4
has title: shutil.get_terminal_size() does not change
downvote count: 0
answer count: 1
tagged with: shutil
favorite count: 0

http://stackoverflow.com/q/52743882
has comment: http://stackoverflow.com/comment/92423270
has answer: http://stackoverflow.com/a/54547513
has body: Engine.py will import several classes as self object Engine.py from api import api from cloud import cloud class Engine(object): def __init__(self, env): session = dict() self.api = api.API(session) self.cloud= cloud.CLOUD(session) api.py class API(object): def __init__(self, session): self.session = session def api_keyword(self): return SOMETHING My question is : How can I use the keyword under api.py and cloud.py and ONLY import Engine.py into robot file test.robot *** Settings *** Library Engine.py ${env} *** Test Cases *** python class test [Tags] class Engine.api.api_keyword And I got error message: No keyword with name 'Engine.api.api_keyword' found.
upvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/92428121
type: AnsweredQuestion
score: 3
tagged with: oop
accepted answer: http://stackoverflow.com/a/54547513
type: Question
tagged with: robotframework
has title: How could I get self object from python class in robotframework
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92236139
has text: Also note that you might want to add the `PermissionsMixin` into your model if you want to keep the Django permission model with Groups and user permissions. Best thing is to look at Django's source code for how `AbstractUser` is implemented
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52651562

http://stackoverflow.com/comment/92308178
type: AnswerComment
score: 0
type: Comment
has text: I searched every possible search query except for "outer" keyword, although it definitely reminded me of the outer product operation. I should read more docs. Thank you!
comment on: http://stackoverflow.com/a/52690612

http://stackoverflow.com/comment/92151243
type: Comment
type: QuestionComment
score: 0
has text: Don't use "s3"; its been deleted except from the AWS EMR libraries, where it refers to something else entirely. w.r.t that spark-hadoop-cloud module; it's not currently published in the ASF releases, though it comes in from other people's
comment on: http://stackoverflow.com/q/52596370

http://stackoverflow.com/a/52622496
has body: Your problem is not to "access objects from another module", but to resolve an attribute (names defineds in a module become attributes of the module object) by it's name. You'd have the exact same problem for any object, ie: class Foo(): def __init__(self): self.a = 42 f = Foo() name = 'a' # now how to get 'f.&lt;name&gt;' ? And the generic answer is the builtin getattr(object, name[, default]) function: print(f.a) print(getattr(f, name)) So in your case in B.py you'd want print(getattr(A_objects, input)) BUT if you're dealing with user inputs (for the largest possible definition of "user inputs"), you most probably want to explicitely define which names are ok to be accessed this way - using a dict being the most obvious solution: # a.py a = {} b = {} # etc registry = { "a": a, "b": b, # etc } and: # B.py import A input = 'a' print(A.registry[input])
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/92183303
accepted answer of: http://stackoverflow.com/q/52622237
answers question: http://stackoverflow.com/q/52622237

http://stackoverflow.com/a/52644565
upvote count: 1
has comment: http://stackoverflow.com/comment/92221384
accepted answer of: http://stackoverflow.com/q/52644377
has comment: http://stackoverflow.com/comment/92221544
has comment: http://stackoverflow.com/comment/92221593
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92221454
answers question: http://stackoverflow.com/q/52644377
has body: It does not work because you are using the a+ mode to open the file. json.load uses the .read method of the passed file-like object. Since you are using a+ mode, .read will return an empty string (which makes sense as the cursor will be at the end of the file). Change mode to r (or don't provide any mode, r is the default) and your code will work. Alternatively, you can call infile.seek(0) before calling json.load but then I don't see the point of using a+ mode to begin with. import json file_name = 'test.json' with open(file_name, 'a+') as infile: if os.stat(file_name).st_size != 0: infile.seek(0) print(json.load(infile)) # ['1', '1', '1', '1', '1', '1', '1', '11', '1', '1', '1.1.1.1', '11.11.11.11']
has comment: http://stackoverflow.com/comment/92221449

http://stackoverflow.com/a/52638837
has body: If you don't know regex I think you can do something like this but you should learn about them they will give you more robust behavior. data ='''29.607416999999998 ,-95.114007 Pinebrook KinderCare, 4422,Clear Lake City Boulevard, Houston, Harris County, Texas,77059,USA 29.74770501 ,-95.39656199 2345, Commonwealth Street, Houston, Harris County, Texas, 77006, USA 29.707028 ,-95.59624701 Hastings Ninth Grade Center, 6750, Cook Road, Houston, Harris County, Texas, 77072, USA 29.59038673 ,-95.47975719 6333, Court Road, Houston, Fort Bend County, Texas, 77053, USA 29.67591366 ,-95.32867835 7084, Crestmont Street, Houston, Harris County, Texas, 77033, USA''' dl = data.split('USA') # print(dl) # 1) zip_code_lst = [] for addrs in dl: zip_found = addrs.rstrip(', ')[-5:] # --&gt; 77006,whitspace --&gt; 77006 if len(zip_found) == 5: zip_code_lst.append(zip_found) print(zip_code_lst) # ['77059', '77006', '77072', '77053', '77033'] # 2) zip_code_lst_comp = [ addrs.rstrip(', ')[-5:] for addrs in dl ] print(zip_code_lst_comp) # ['77059', '77006', '77072', '77053', '77033', '']
answers question: http://stackoverflow.com/q/52638228
score: 0
type: Answer

http://stackoverflow.com/q/52723520
has answer: http://stackoverflow.com/a/52723693
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92373147
tagged with: operating-system
tagged with: path
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2953834
accepted answer: http://stackoverflow.com/a/52723693
has comment: http://stackoverflow.com/comment/92372402
type: Question
has body: my program should parse /classifiers folder and go throught some calc. Here is a paths for folders: classifiers_path = os.path.join('C:/Users/feature/classifiers') Here is a lines of code, that parses that folder: for i in os.path.join(classifiers_path + '/*.pkl'): # Pulling the model from the path model = joblib.load(i) While debugging i have paths like this: C:/Users/feature/classifiers\\T1.pkl So it breaks with FileNotFoundError, How to avoid this double \, and it should be written, for unix/windows? Thanks
has comment: http://stackoverflow.com/comment/92372455
has title: Avoid double backslash in windows path

http://stackoverflow.com/comment/92414544
comment on: http://stackoverflow.com/q/52744147
score: 0
has text: Again, please read and follow the posting guidelines. This code doesn't execute, and is not minimal to your stated problem.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92153788
has text: There's an easy way. What have *you* tried?
score: 3
comment on: http://stackoverflow.com/q/52609724
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92412641
has text: @bereal not equivalent because the `except` will also catch `ValueError` for invalid literals passed like `int('a')`
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52743921

http://stackoverflow.com/q/52607081
tagged with: scheduler
favorite count: 0
has title: Schedule a python script on heroku
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52607616
upvote count: 1
downvote count: 1
tagged with: heroku
type: AnsweredQuestion
has body: I deployed my python script on Heroku and trying to setup scheduler to run it every hour. My Procfile: run: cd src &amp;&amp; python3 main.py I scale this dyno with: heroku ps:scale run=1 And in heroku scheduler I set it for run every hour with command run Deploy and I think that it will runs every hour, but it runs more often than I expect, every 10-15 minutes, how can I solve it?
type: Question
has answer: http://stackoverflow.com/a/52607616
answer count: 1

http://stackoverflow.com/a/52636757
downvote count: 0
has comment: http://stackoverflow.com/comment/92228462
has comment: http://stackoverflow.com/comment/92208263
has comment: http://stackoverflow.com/comment/92207412
type: Answer
has body: Replace your print command for: Python 3.6+: print(f'{item.text:&lt;25} {item.next_sibling}') Python 3 - 3.5: print('{:&lt;25} {}'.format(item.text, item.next_sibling)) Outputs: District: AnyState - At Large Political Highlights: AnyTown City Council, 19XX-XX Born: June X, 19XX; AnyTown, Calif. Residence: Some Town Religion: Episcopalian Family: Wife, Some Name; two children Education: Some State College, A.A. 19XX; Some Other State College, B.A. 19XX Elected: 19XX
accepted answer of: http://stackoverflow.com/q/52636648
answers question: http://stackoverflow.com/q/52636648
upvote count: 5
score: 5
type: AcceptedAnswer

http://stackoverflow.com/comment/92220550
comment on: http://stackoverflow.com/q/52644097
has text: It's *always* an approximation, just sometimes it's more proximate to your desired value and sometimes less so.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/a/52737990
answers question: http://stackoverflow.com/q/52730025
has comment: http://stackoverflow.com/comment/92401867
score: 2
downvote count: 0
upvote count: 2
has body: The error is not related to your wrapper library, there seems to be nothing wrong with your task. The problem arises because you've defined your task with bind=True When done so, celery automatillca injects a parameter to the method containing information about the current task. So you can either remove bind=True, or add a parameter to your task method like so: @shared_task(bind=True) def login_mb(self): mb = APIClient('abc', '123') mb.login() mb.keep_alive()
type: Answer

http://stackoverflow.com/a/52731473
answers question: http://stackoverflow.com/q/52730778
type: Answer
downvote count: 0
score: 1
has body: Here is an idea on how you might you around implementing this (although probably not the best one). def convert_to_classes(vals, splits): out = tf.zeros_like(vals, dtype=tf.int32) for split in splits: out = tf.where(vals &gt; split, out + 1, out) return out def my_acc(splits): def custom_acc(y_true, y_pred): y_true = convert_to_classes(y_true, splits) y_pred = convert_to_classes(y_pred, splits) return K.mean(K.equal(y_true, y_pred)) return custom_acc The function convert_to_classes converts the floats to bucks, assuming the bounds are always +-inf. The closure my_acc lets you define the splits (without +-inf) at compile time (added statically to the graph), and then returns a metric function as expected with keras. Testing using tensorflow: y_true = tf.constant([12.5, 45.5]) y_pred = tf.constant([14.5, 29]) with tf.Session() as sess: print(sess.run(my_acc((10, 20, 30))(y_true, y_pred))) gives the expected 0.5 accuracy. And quick test with Keras: x = np.random.randn(100, 10)*100 y = np.random.randn(100)*100 model = Sequential([Dense(20, activation='relu'), Dense(1, activation=None)]) model.compile(optimizer='Adam', loss='mse', metrics=[my_acc(splits=(10, 20, 30))]) model.fit(x, y, batch_size=32, epochs=10) Given the metric (named as the inner function in the closure custom_acc) 100/100 [==============================] - 0s 2ms/step - loss: 10242.2591 - custom_acc: 0.4300 Epoch 2/10 100/100 [==============================] - 0s 53us/step - loss: 10101.9658 - custom_acc: 0.4200 Epoch 3/10 100/100 [==============================] - 0s 53us/step - loss: 10011.4662 - custom_acc: 0.4300 Epoch 4/10 100/100 [==============================] - 0s 51us/step - loss: 9899.7181 - custom_acc: 0.4300 Epoch 5/10 100/100 [==============================] - 0s 50us/step - loss: 9815.1607 - custom_acc: 0.4200 Epoch 6/10 100/100 [==============================] - 0s 74us/step - loss: 9736.5554 - custom_acc: 0.4300 Epoch 7/10 100/100 [==============================] - 0s 50us/step - loss: …
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92972447
accepted answer of: http://stackoverflow.com/q/52730778

http://stackoverflow.com/a/52673589
type: Answer
has body: You are getting empty strings as a result of your split: "howdy. how are you.".split('.') # = ['howdy', ' how are you', ''] You are getting an exception when you are trying to get the [0]th character of an empty string. In your loop, you should check if the sentence is not empty and skip it (for example, using continue) if it is: for sentence in sentences: if not sentence: continue elif sentence[0] == ' ': # assuming 1 space separates sentences result += ' ' # etc.
upvote count: 5
score: 5
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52673517
accepted answer of: http://stackoverflow.com/q/52673517

http://stackoverflow.com/comment/92287333
has text: Unfortunately this doesn't work, it gives me the following output `[]`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52679339

http://stackoverflow.com/comment/108218115
score: 1
comment on: http://stackoverflow.com/q/52733786
type: Comment
type: QuestionComment
has text: Many more solutions can be found [here](https://stackoverflow.com/questions/48905127/importing-py-files-in-google-colab?noredirect=1&lq=1). I found the `!git clone https://github.com/username/repo_name.git.` from [Aditya Mishra](https://stackoverflow.com/a/49452931/6329629) quite useful.

http://stackoverflow.com/q/52616895
has comment: http://stackoverflow.com/comment/92168024
type: Question
has body: I'm using multiprocessing Pool to manage tesseract processes (OCRing pages of microfilm). Very often in a Pool of say 20 tesseract processes a few pages will be more difficult to OCR, and thus these processes are taking much much longer than the other ones. In the mean time, the pool is just hanging and most of the CPUs are not being leveraged. I want these stragglers to be left to continue, but I also want to start up more processes to fill up the many other CPUs that are now lying idle while these few sticky pages are finishing up. My question: is there a way to load up new processes to leverage those idle CPUs. In other words, can the empty spots in the Pool be filled before waiting for the whole pool to complete? I could use the async version of starmap and then load up a new pool when the current pool has gone down to a certain number of living processes. But this seems inelegant. It would be more elegant to automagically keep slotting in processes as needed. Here's what my code looks like right now: def getMpBatchMap(fileList, commandTemplate, concurrentProcesses): mpBatchMap = [] for i in range(concurrentProcesses): fileName = fileList.readline() if fileName: mpBatchMap.append((fileName, commandTemplate)) return mpBatchMap def executeSystemProcesses(objFileName, commandTemplate): objFileName = objFileName.strip() logging.debug(objFileName) objDirName = os.path.dirname(objFileName) command = commandTemplate.substitute(objFileName=objFileName, objDirName=objDirName) logging.debug(command) subprocess.call(command, shell=True) def process(FILE_LIST_FILENAME, commandTemplateString, concurrentProcesses=3): """Go through the list of files and run the provided command against them, one at a time. Template string maps the terms $objFileName and $objDirName. Example: &gt;&gt;&gt; runBatchProcess('convert -scale 256 "$objFileName" "$objDirName/TN.jpg"') """ commandTemplate = Template(commandTemplateString) with open(FILE_LIST_FILENAME) as fileList: while 1: # Get a batc…
upvote count: 3
answer count: 1
has title: multiprocessing.Pool: How to start new processes as old ones finish?
has answer: http://stackoverflow.com/a/52618410
accepted answer: http://stackoverflow.com/a/52618410
favorite count: 0
tagged with: process-pool
tagged with: python
tagged with: parallel-processing
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: python-multiprocessing
tagged with: multiprocessing

http://stackoverflow.com/q/52633293
has comment: http://stackoverflow.com/comment/92200001
tagged with: microsoft-r
has comment: http://stackoverflow.com/comment/92201456
has title: Passing a python datastructure to MS R Server model that was deployed in R
type: Question
has body: I am running ML server and I have a service deployed that expects one of its inputs to be a data.frame (its a model deployed in R). I'm using the azureml-model-management-sdk https://pypi.org/project/azureml-model-management-sdk/#history would that be something like : opts = { "ntree" :55, "mtry" : 0.1, "sampleSize" : 0.45 } So in short, the environment has R and python models deployed to ML (R) server. I'm trying to get predictions from both of them in python. I have also tried opts = { "ntree" :[55], "mtry" : [0.1], "sampleSize" : [0.45] }
answer count: 1
score: 0
linked to: http://stackoverflow.com/q/52544689
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52650226
has comment: http://stackoverflow.com/comment/92200079

http://stackoverflow.com/comment/92166378
type: QuestionComment
comment on: http://stackoverflow.com/q/52615979
has text: Not enough information. Even so: does `Image.resize` maintain the original aspect ratio?
score: 0
type: Comment

http://stackoverflow.com/comment/92308945
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52690632
score: 0
has text: you also need a skiprows=2, I get a runtime error divide by zero at log10 after the shift. But that's probably okay, as a starting point. I have to put something away and will look at this in a few minutes. It should not take long to sort it out.

http://stackoverflow.com/q/52605630
has comment: http://stackoverflow.com/comment/92152443
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/92146421
score: 4
has comment: http://stackoverflow.com/comment/92145404
has comment: http://stackoverflow.com/comment/92148962
tagged with: virtualenv
favorite count: 0
has comment: http://stackoverflow.com/comment/92146216
has title: python virtual env somehow using wrong pip
has body: strugging to get pip install working with virtualenv. $ virtualenv env $ source env/Scripts/activate I now have two python installations: (env) $ where python D:\my_folder\env\Scripts\python.exe C:\Users\Me\Anaconda3\python.exe I am using the one I want: (env) $ which python D:\my_folder\env\Scripts\python.exe Same with pip: (env) $ where pip D:\my_folder\env\Scripts\pip.exe C:\Users\Me\Anaconda3\Scripts\pip.exe (env) $ which pip D:\my_folder\env\Scripts\pip.exe However I have the following (env) $ pip -V pip 18.0 from C:\Users\Me\Anaconda3\Lib\site-packages\pip (python 3.6) wrong place! (env) $ pip freeze ... dumps out my global packages!! (env) $ pip install requirements.txt ... fails because requirements cannot be met. I have a feeling that I have bad environment variable somewhere but don't really know where to look?! I'm just coming over from node and npm and finding python modules to be a bit of a car crash (although the language is awesome). Anyhow all help appreciated. (EDIT) OK, so (thanks to @alec_djinn) the following works: python -m pip install requirements.txt however python -m pip freeze still dumps my global installations.
has comment: http://stackoverflow.com/comment/92146099
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/92148899
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/92395588
score: 0
comment on: http://stackoverflow.com/q/52735310
type: Comment
type: QuestionComment
has text: @Aran-Fey I am fairly new to python so I needed to look up your terminology, but as far as I can tell yes, that's what my intention is here.

http://stackoverflow.com/q/52740089
has answer: http://stackoverflow.com/a/52898079
answer count: 1
upvote count: 6
tagged with: scikit-learn
tagged with: python
has body: I have been trying to get the classification report in the form of a dictionary. So according to the scikit-learn 0.20 documentation, I do: from sklearn import metrics rep = metrics.classification_report(y_true, y_pred, output_dict=True) But get an error saying TypeError: classification_report() got an unexpected keyword argument 'output_dict' The scikit-learn module in my machine was initially 0.19.1 but even after updating it to 0.20, the same error message shows.
favorite count: 0
tagged with: python-3.x
score: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52898079
has title: How to get output of sklearn.metrics.classification_report as a dict?
downvote count: 0
tagged with: svm
type: Question

http://stackoverflow.com/comment/92176026
type: QuestionComment
comment on: http://stackoverflow.com/q/52621123
has text: Sorry, not understand - `column_order = ["T1","T2","T30","T4","Time"]` should working perfectly.
score: 1
type: Comment

http://stackoverflow.com/comment/94899617
has text: If any answer does what you want, please check it as correct. A reputation of 1 is enough to do so.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52715059
type: Comment

http://stackoverflow.com/a/52699243
answers question: http://stackoverflow.com/q/52676647
upvote count: 25
accepted answer of: http://stackoverflow.com/q/52676647
type: Answer
has comment: http://stackoverflow.com/comment/92488430
has comment: http://stackoverflow.com/comment/137096688
has body: There are several ways to solve circular dependencies like this, see Type hints: solve circular dependency You can always apply the decorator manually (and update the annotations), like @Nearoo's answer shows. However, it might be easier to "forward declare" the class: class A: pass @dataclass class B: a: A @dataclass class A: b: B Or simply use a forward reference: @dataclass class B: a: 'A' @dataclass class A: b: B The cleanest is to import Python 4.0's behavior (if you can): from __future__ import annotations @dataclass class B: a: A @dataclass class A: b: B
score: 25
downvote count: 0
has comment: http://stackoverflow.com/comment/92486562
type: AcceptedAnswer

http://stackoverflow.com/a/52642856
has comment: http://stackoverflow.com/comment/92245470
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52642245
answers question: http://stackoverflow.com/q/52642245
type: Answer
score: 2
downvote count: 0
has body: Here is how I will go about this task: from io import StringIO import pandas as pd from sklearn.cluster import KMeans s = '''indexID RngUni[m] PowUni[dB] 157203 1.292283 132 157201 1.271878 132 157016 1.285481 134 157404 1.305886 136 157500 1.353496 136 157524 1.251474 136 157227 1.292283 132 157543 1.339893 136 157903 1.353496 138 156928 1.299084 134 157373 1.299084 136 156937 1.414709 134 157461 1.353496 136 157718 1.360297 138 157815 1.326290 138 157806 1.271878 134 156899 1.360298 134 157486 1.414709 138 157628 1.271878 136 157405 1.299084 134 157244 1.299084 134 157522 1.258275 136 157515 1.367099 138 157086 1.305886 136 157602 1.251474 134 157131 1.265077 132 157170 1.380702 138 156904 1.360297 134 157209 1.401106 138 157018 1.265077 134''' ss = StringIO(s) df = pd.read_csv(ss, sep=r"\s+") kmeans = KMeans(n_clusters=2, random_state=0).fit(df.values[:,[1,2]]) df['labels']=kmeans.labels_ df['labels']=kmeans.labels_ df.labels.apply(lambda x: 'red' if x==1 else 'blue') plt.scatter(x=df['RngUni[m]'], y=df['PowUni[dB]'], c=df['labels']) The output: Just change the clustering algorithm and play with the parameters to get the desired clusters and colors. Hope it helps.
has comment: http://stackoverflow.com/comment/92314969
has comment: http://stackoverflow.com/comment/92245392
has comment: http://stackoverflow.com/comment/92254819
has comment: http://stackoverflow.com/comment/92245112

http://stackoverflow.com/q/52618451
has body: I'm trying to log in to a website from this URL: "https://pollev.com/login". Since I'm using a school email, the portal redirects to the school's login portal and uses that portal to authenticate the login. It shows up when you type in a uw.edu email (example: myname@uw.edu). After logging in, UW sends a POST request callback to https://www.polleverywhere.com/auth/washington/callback with a SAMLResponse header like this. I think I need to simulate the GET request from pollev's login page and then send the login headers to the UW login page, but what I'm doing right now isn't working. Here's my code: import requests with requests.session() as s: header_data = { 'user - agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', 'referer': 'https://pollev.com/login' } login_data = { 'j_username' : 'username', 'j_password' : 'password', '_eventId_proceed' : 'Sign in' } r = s.get('https://idp.u.washington.edu/idp/profile/SAML2/Redirect/SSO?execution=e2s1', headers=header_data, data=login_data) print(r.text) Right now, r.text shows a NoSuchFlowExecutionException html page. What am I missing? Logging into the website normally requires a login, password, Referrer, and X-CSRF token which I was able to do, but I don't know how to navigate a redirect for authentication.
has answer: http://stackoverflow.com/a/52819440
accepted answer: http://stackoverflow.com/a/52819440
upvote count: 4
has answer: http://stackoverflow.com/a/66640102
favorite count: 0
downvote count: 0
tagged with: python
tagged with: python-requests
possible better answer: http://stackoverflow.com/a/66640102
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78751954
has comment: http://stackoverflow.com/comment/92171231
type: Question
has title: Python Requests - SAML Login Redirect
tagged with: saml
score: 4
answer count: 3

http://stackoverflow.com/q/52670549
tagged with: python
accepted answer: http://stackoverflow.com/a/52670619
score: 1
tagged with: python-3.x
upvote count: 1
answer count: 1
has title: How to create a custom Exception with error message and status code in python3
has answer: http://stackoverflow.com/a/52670619
has body: I am trying to create the following exception and call it in another function: ### The exception class GoogleAuthError(Exception): def __init__(self, message, code=403): self.code = code self.message = message ### Generating the exception raise GoogleAuthError(message="There was an error authenticating") ### printing the exception try: do_something() except GoogleAuthError as e: print(e.message) Basically, I want it to print "There was an error authenticating". How would I do this properly, or is the above the correct way to do it?
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/a/52744662
has comment: http://stackoverflow.com/comment/92413855
has comment: http://stackoverflow.com/comment/92413921
upvote count: 1
has body: Just change your function def label_sub_cat(row): if row.product.str.contains('Proceedings', case=False) is True: return 'Proceedings' elif row.product.str.contains('DVD', case=False) is True: return 'DVD' else: return 'Other' data['product_sub_cat'] = data.apply(label_sub_cat, axis=1)
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52744139
score: 1

http://stackoverflow.com/a/52728640
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52687382
answers question: http://stackoverflow.com/q/52687382
upvote count: 2
type: AcceptedAnswer
has body: https://www.pydoc.io/pypi/websockets-6.0/autoapi/protocol/index.html The iterator yields incoming messages. It exits normally when the connection is closed with the status code 1000 (OK) or 1001 (going away). It raises a ConnectionClosed exception when the connection is closed with any other status code. Closing with a 1000 status from the client prevents the exception.
type: Answer

http://stackoverflow.com/q/52596921
favorite count: 0
has body: I came across a very weird thing with strings and dictionaries in Python today. Can someone explain to me why the print statement works in the first for loop but fails in the second for loop? test = 'ab' test_dict = {} test_dict[test] = 1 for x, y in test_dict: print('%s %s' % (x,y)) for x,y in test: print('%s %s' % (x,y))
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92128515
has title: Why does "in" work for keys but not for strings?
tagged with: python
upvote count: 4
tagged with: dictionary
has comment: http://stackoverflow.com/comment/92128639
has comment: http://stackoverflow.com/comment/92128576
score: 3
has comment: http://stackoverflow.com/comment/92128585
has comment: http://stackoverflow.com/comment/92128728
type: Question
has answer: http://stackoverflow.com/a/52597027
has comment: http://stackoverflow.com/comment/92128505
has comment: http://stackoverflow.com/comment/92128468
has comment: http://stackoverflow.com/comment/92128483
has answer: http://stackoverflow.com/a/52597013
answer count: 3
has comment: http://stackoverflow.com/comment/92128561
has answer: http://stackoverflow.com/a/52597004
has comment: http://stackoverflow.com/comment/92128509
downvote count: 1
tagged with: iterable-unpacking
tagged with: string
has comment: http://stackoverflow.com/comment/92128541

http://stackoverflow.com/comment/92310502
score: 0
has text: @Acccumulation: nooo... There are *two* ranges here: the range of the elements over which we consider numbers, and the `range(..)` that is used to *check* if it is a prime number. Somehow you emit a lot of confusion, omitting any reasoning :)
comment on: http://stackoverflow.com/q/52691721
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52599941
type: Question
upvote count: 0
score: -1
possible better answer: http://stackoverflow.com/a/52600054
has comment: http://stackoverflow.com/comment/92134460
has comment: http://stackoverflow.com/comment/92134418
answer count: 2
accepted answer: http://stackoverflow.com/a/52600109
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92134402
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52600109
downvote count: 1
has body: Currently I'm trying to copy a picture that is half on python and make it symmetrical. Where the picture contains half of the overall pixel number. On the left side is the original. And I want to copy those pixels from left to right and make the entire picture symmetrical The original picture would look like this: a a b b - - - - a b c d - - - - a b a b - - - - And the output picture would be: a a b b b b a a a b c d d c b a a b a b b a b a And the code im working on is as follows: from csmedia import * def symmetry(img): output_image = None w, h = img.size() for y in range(h): for x in range(w): os = img.get(x, y) img.set(w - x - 1, y, os) return output_image if __ name__ == __main__: img = load_picture('img/half_star.png') image = symmetry(img) image.show However when I run the code it gives me "AttributeError: 'NoneType' objects has no attribute 'show'" I hope the question was clear enough. Thank you.
has title: Python, AttributeError: 'NoneType' object has no attribute 'show'
has answer: http://stackoverflow.com/a/52600054

http://stackoverflow.com/a/52687790
answers question: http://stackoverflow.com/q/52687750
has comment: http://stackoverflow.com/comment/92302888
score: 1
has body: You can put all of your guests into an array and use random.choice to set random guest to a variable called random_guest. guests = [guest('human', 'Tom', 'chicken'), guest('dwarf', 'Bjorn', 'potatoes'), guest('orc', 'Orok', 'pork'), guest('elf', 'Eli', 'Salad')] random_guest = random.choice(guests) print('The first guest you meet is a '+ random_guest.race + ' named '+ random_guest.name + '. He really likes '+ random_guest.fav_food + '.')
downvote count: 0
has comment: http://stackoverflow.com/comment/92303608
type: Answer
upvote count: 1

http://stackoverflow.com/comment/98301398
score: 1
type: AnswerComment
has text: pip 1.4.1 under Python 2.7 (Windows 10): "no such option --trusted-host"
type: Comment
comment on: http://stackoverflow.com/a/52656161

http://stackoverflow.com/q/52640677
has body: I need to get albums with there related images .I have two albums in 1st loop abc and abc123 and two images in abc album and 3 images in abc123 album but my response is returning 5 images in each album. i'm not able to create proper response. models.py class Upload(models.Model): image=models.ImageField(upload_to='upload/', blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) # url= models.CharField(max_length=500) def __str__(self): return str(self.id) class Album(models.Model): name = models.CharField(max_length=128) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.name) class AlbumImage(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) image = models.ForeignKey(Upload, on_delete=models.CASCADE) views.py def getalbum(self,request): albums=Album.objects.filter(user=request.user) album={} image_list={} all_results=[] all_images=[] for a in albums: album_images=AlbumImage.objects.filter(album=a) for i in album_images: image_object=Upload.objects.get(id=str(i.image)) image_list=str(image_object.image) all_images.append(image_list) album[a.name]=all_images all_results.append(album) return Response(all_results) response [ { "abc": [ "upload/images_aPWBEcp.jpeg", "upload/images.jpeg", "upload/ic_id_card_placeholder_N0x2KP9.png", "upload/images_jocZcBu.jpeg", "upload/ic_id_card_placeholder_N0x2KP9.png" ], "abc123": [ "upload/images_aPWBEcp.jpeg", "upload/images.jpeg", "upload/ic_id_card_placeholder_N0x2KP9.png", "upload/images_jocZcBu.jpeg", "upload/ic_id_card_placeholder_N0x2KP9.png" ] } ] abc album upload/images_aPWBEcp.jpeg upload/images.jpeg abc123 album upload/ic_id_card_placeholder_N0x2KP9.png upload/images_jocZcBu.jpeg upload/ic_id_card_placeholder_N0x2KP9.png
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/52640877
tagged with: python
has title: Append in two for loop django
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52640886
has answer: http://stackoverflow.com/a/52640877
tagged with: django
type: Question
type: AnsweredQuestion
tagged with: django-views
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/52640886
has answer: http://stackoverflow.com/a/52641168

http://stackoverflow.com/comment/92414238
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52714889
has text: The solution is to use an app that has the correct permissions to run the script: https://stackoverflow.com/a/52655013/463796
score: 0

http://stackoverflow.com/a/53257516
score: 0
answers question: http://stackoverflow.com/q/52602194
type: Answer
has body: Finally is one month plus and I found the solution for Beaglebone Black. Make some changes in the library code if possible to change in the library itself. Change the bus number from 1 to 2. This GitHub link might help you https://github.com/RigacciOrg/py-qmc5883l to get your bearing degree (yaw rotation) in no time.

http://stackoverflow.com/comment/92159480
score: 0
has text: Sorry it's a side effect to two programming language. In javascript we can but not in python.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52612286

http://stackoverflow.com/comment/92117331
type: QuestionComment
has text: how would `list_joined` look if `List_main` was `['a','b','c', 'c']`?
comment on: http://stackoverflow.com/q/52591339
score: 0
type: Comment

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/52644305
type: Tag
tags question: http://stackoverflow.com/q/52651536
tags question: http://stackoverflow.com/q/52594951

http://stackoverflow.com/a/52679554
answers question: http://stackoverflow.com/q/52679502
has body: Try below solution to update @href value: driver.execute_script('arguments[0].href = "www.abc.com/id=12";', view)
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52679502
has comment: http://stackoverflow.com/comment/92290475
type: Answer

http://stackoverflow.com/comment/126111498
type: QuestionComment
type: Comment
has text: For this `SyntaxError`, Can you try escaping the backslashes in the file path, You can refer to this [comment](https://stackoverflow.com/a/37402939/11530462) for more details on the same. Thanks!
score: 0
comment on: http://stackoverflow.com/q/52653656

http://stackoverflow.com/a/52595991
answers question: http://stackoverflow.com/q/52594878
type: Answer
upvote count: 1
score: 1
has body: By default, pandas.to_csv adds an index to the CSV export (from the docs): index: boolean, default True Write row names (index) You can export to CSV without the index: result_25.toPandas().to_csv('mycsv.csv', index=False) and you won't see the additional column _c0 (the column name _c0 is added by pyspark since pandas does not give any name to the index column). If you only use spark (and don't need the saved data frame in human-readable format), another way to avoid this is to write/read pyspark data frames in other formats such as JSON or parquet: # JSON result_25.write.json('mydataframe.json') rr = spark.read.json('mydataframe.json') # parquet result_25.write.parquet('mydataframe.parquet') rr = spark.read.parquet('mydataframe.parquet')
accepted answer of: http://stackoverflow.com/q/52594878
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52688612
has comment: http://stackoverflow.com/comment/92305076
accepted answer of: http://stackoverflow.com/q/52688527
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: Starting the output We use the CGI object to print out the HTTP header for the output: print $q-&gt;header; This gives you the following HTTP header: Content-Type: text/html; charset=ISO-8859-1 If you need to have any extra options in your header, for example you may not want the default 'type', you can just pass them in to the header method: print $q-&gt;header(-type =&gt; "text/plain"); This gives you the following HTTP header: Content-Type: text/plain; charset=ISO-8859-1 For more info visit here.
score: 1
has comment: http://stackoverflow.com/comment/92326094
has comment: http://stackoverflow.com/comment/92308135
has comment: http://stackoverflow.com/comment/92307181
answers question: http://stackoverflow.com/q/52688527

http://stackoverflow.com/q/52745181
score: 0
tagged with: python
type: UnansweredQuestion
has body: I am new in the Cloud and I have an python script that I call from a bash script with parameters. this app run on Linux and required some python modules as well. I would like to deploy this app on the AWS cloud and make it run on a given schedule. What is the best way to deploy this app (AWS Lambda or EC2). Thanks Nono
has answer: http://stackoverflow.com/a/52745223
has answer: http://stackoverflow.com/a/52747630
type: Question
answer count: 2
has title: Deploy Python/Bash application on Aws
tagged with: amazon-ec2
tagged with: amazon-web-services
tagged with: aws-lambda

http://stackoverflow.com/q/52678883
has answer: http://stackoverflow.com/a/52679211
tagged with: python
has title: Python scraping href adjust url
tagged with: screen-scraping
tagged with: keyword
type: Question
score: 0
answer count: 1
tagged with: url
has body: This code works for the URL http://www.schulliste.eu/schule/ but not for http://www.schulliste.eu/type/gymnasien/ Does anybody know why? I think it has something to do with the keyword "title" Also I like to have the plain email adresses (without brackets and quotes) among themselves, is that possible? import requests from bs4 import BeautifulSoup as soup def get_emails(_links: list, _r=[0, 10]): for i in range(*_r): new_d = soup(requests.get(_links[i]).text, 'html.parser').find_all('a', {'class':'my_modal_open'}) if new_d: yield new_d[-1]['title'] d = soup(requests.get('http://www.schulliste.eu/schule/').text, 'html.parser') results = [i['href'] for i in d.find_all('a')][52:-9] print(list(get_emails(results)))
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/q/52742438
score: 0
has comment: http://stackoverflow.com/comment/92409727
has comment: http://stackoverflow.com/comment/92412537
type: UnansweredQuestion
tagged with: python
has title: Python thread that opens subprocess not joining until I press Enter
tagged with: subprocess
answer count: 0
tagged with: multithreading
type: Question
has body: My program is supposed to run a subprocess in the background and wait for the user to press Enter. When the user presses Enter, an empty file is created at a predetermined path. The mere existence of this empty file signals the subprocess to terminate gracefully. (I have verfied that this termination based on the file's existence works correctly.) In my controller function, I spawn a thread (threading.Thread) that runs the subprocess using subprocess.Popen. Then, in controller, I await user input (Enter), and then create the special file to terminate the subprocess, and finally join on the spawned thread. Things seem to be working fine with 1 problem: after I press Enter and the termination sequence runs, I have to press Enter 1 more time to get past the thread join. That is, in order to reach the pdb.set_trace() statement below, I have to press Enter twice. What could be forcing me to press Enter twice here? Clue: When I remove the raw_input statement, the program terminates directly (which is the expected behaviour when not waiting for user input to terminate). def controllerSubprocess(command): subprocess.call(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def controller(parms): # Defined "command" here. ret_stdout = [] controller_subproc_thread = threading.Thread(target=controllerSubprocess, args=(command,)) controller_subproc_thread.daemon = False controller_subproc_thread.start() raw_input('Now running. Press ENTER to finish...') print '\nTerminating...' # Create an empty file that causes the process # opened by subprocess to end after roughly 5 seconds. controller_subproc_thread.join() pdb.set_trace()

http://stackoverflow.com/q/52733442
tagged with: tkinter
has answer: http://stackoverflow.com/a/52734759
has title: Tkinter - cannot move canvas on mainwindow
duplicate of: http://stackoverflow.com/q/34032111
type: Question
has body: I'm learning tkinter and I have created a simple converter. I have created a canvas and put all my widges on it. My main window is 800x640 and the canvas is 400x320. After I was done I wanted to play with the grid command and find a position for my canvas that I like. However when I do canvas.grid(row=rownr, column=columnnr) the canvas just goes to row=0, column=0 on the mainwindow no matter what values for row and col I give in the grid method. If I add another widget for example a label on the mainwindow at (0,0) then I try moving the canvas to (0,1) then the canvas goes to that position. However if the canvas is the only widget on my main window it won't move at all with grid method. Please help me understand why this happens. Here is the entire code: from tkinter import * from tkinter.ttk import * from tkinter import messagebox from tkinter import Menu def convert_meters(): # get value from entry and convert it to all result_in_meters = int(label1_1.get())# integer value result_in_km.set(float(result_in_meters/1000)) result_in_dem.set(float(result_in_meters*10)) result_in_miles.set(float(result_in_meters*0.000621371)) result_in_yards.set(float(result_in_meters*1.09361)) def get_value_and_convert(): if(combo1.get()=="meters"): convert_meters() elif(combo1.get()=="centimeters"): convert_centimeters() elif(combo1.get()=="millimeters"): convert_millimeters() elif(combo1.get()=="inches"): convert_inches() else: result_in_km.set("0") result_in_dem.set("0") result_in_miles.set("0") result_in_yards.set("0") window = Tk() window.title("Converter") result = IntVar() result_in_km = StringVar() result_in_dem = StringVar() result_in_miles = StringVar() result_in_yards = StringVar() canvas1 = Canvas(window, width=400, height=320, bd=1, highlightthickness=1, relief='ridge') canvas1.grid(row=2, column=2) #### Things to convert ##### label1 = Label(canvas1, text="Convert ", width=8) label1_1 = Entry(canvas1, width=2) # between label1 and combobox combo1 = Combobox(canvas1, width…
score: 0
linked to: http://stackoverflow.com/q/34032111
answer count: 1
accepted answer: http://stackoverflow.com/a/52734759
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/92260627
comment on: http://stackoverflow.com/q/52664005
type: Comment
has text: I want to know alternate method to insert sd1 value into MySQL database. Length of sd1 dictionary may goes upto 15.
score: 0
type: QuestionComment

http://stackoverflow.com/a/52706805
type: Answer
has body: The first thing you should make sure is the VPC Security Group that the Elasticache Redis is attached, allows Custom TCP traffic from your address to port number 6379 (default for Redis). For me the connection timed out issue arised due to the inaccessibility to the VPC where the Redis cluster resides.
score: 0
answers question: http://stackoverflow.com/q/52705563

http://stackoverflow.com/comment/92413375
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52743441
type: AnswerComment
has text: One final thing (I promise :P): `TimeDistributed` takes a layer as its argument, not a tensor, so what is being wrapped should be `small_model`, as opposed to `small_model()`. The latter gives an error, at least. In the same vein, should `outputs` not be `large_model(small_model_out)`, as `TimeDistributed` returns a tensor?

http://stackoverflow.com/q/52718750
tagged with: python
has comment: http://stackoverflow.com/comment/92362890
duplicate of: http://stackoverflow.com/q/22391433
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92363149
linked to: http://stackoverflow.com/q/22391433
has body: I have a pandas dataframe with many different elements, and I want to group similar ones and add another column representing the frequency of them. For example: +-------+------+ | Atr1 | Atr2 | +-------+------+ | 1 | A | +-------+------+ | 2 | B | +-------+------+ | 1 | A | +-------+------+ | 3 | C | +-------+------+ I want to get: +-------+-------+-------+ | Atr1 | Atr2 | COUNT | +-------+-------+-------+ | 1 | A | 2 | +-------+-------+-------+ | 2 | B | 1 | +-------+-------+-------+ | 3 | C | 1 | +-------+-------+-------+ How can I do it?
tagged with: group-by
tagged with: dataframe
type: Question
score: 0
tagged with: pandas
has title: How can I group by and count similar elements in a pandas dataframe?
has comment: http://stackoverflow.com/comment/92363172
tagged with: frequency

http://stackoverflow.com/q/52716888
score: -1
has comment: http://stackoverflow.com/comment/92359526
has title: Compute prime factors in python
has answer: http://stackoverflow.com/a/52717296
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92359770
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15347174
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92359469
type: Question
has comment: http://stackoverflow.com/comment/92359272
has body: I currently have a list containing numbers: lst = [3,4,6] and I'm trying to compute the prime factors of the numbers in the list where i obtain the output of 3^1 2^2 2^1 x 3^1 Here's what i tried: def prime_factors(lst): for j in range(len(lst)): i = 2 factors = [] while i*i &lt;= j: if j%i: i+=1 else: j//= i factors.append(i) if j &gt; 1: factors.append(j) return factors but I'm getting [2] as the output. Would appreciate some help on this.
tagged with: python

http://stackoverflow.com/comment/92141850
has text: So you do want to remove all subset from a list of list. Right? You might want to give more than just one example. If you are unable to articulate what you want via English try using pseudo code like, `f([[1]]) -> [[1]], f([[1][1,2]]) -> [[1,2]], f([[1][1,2],[3]]) -> [[1,2],[3]], f([[1][1,2,3],[3]]) -> [[1,2,3]]` and so on until it is very clear what you want.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52603251
score: 0

http://stackoverflow.com/a/52703450
score: 0
has comment: http://stackoverflow.com/comment/92334066
answers question: http://stackoverflow.com/q/52702986
type: Answer
has comment: http://stackoverflow.com/comment/92333943
has body: You're performing a transformation to X_fresh that you are not performing to X_train. Your pipeline expects the input data from X_fresh to be the same shape as X_train. By doing this selector transformation before the pipeline you're changing the shape of X_fresh so that it no longer matches X_train. Since selector is already a part of the pipeline this code is unnecessary: X_fresh=X_fresh[:,selector.get_support(indices=True) When you call y_pred=estimator.predict(X_fresh) the selector step will run as a part of the pipeline so there is not need to call that step independently. This is one of the benefits of using a pipeline to begin with. When you do call the estimator make sure X_fresh matches the shape of X_train since that's what the trained pipeline would be expecting. A pipeline works by chaining steps of a model together. In your pipeline you have a feature selection step, selector, and a regression step, regressor. When you call the fit() method on your pipeline the input data, X_train is first transformed by selector to have the 250 best features and then the transformed data is being fed into the regressor step to train the regression model. When you call predict() on your pipeline the new data you feed in will perform those same steps, so there is no need to perform any step from the pipeline independently. Prior to fitting your pipeline you should get X_train.shape to determine how many columns are in X_train. After you fit estimator you have to make sure X_fresh has the same columns as X_train. Then when you call predict on your estimator the pipeline will automatically perform the feature selection and produce predictions.
has comment: http://stackoverflow.com/comment/92334803

http://stackoverflow.com/q/52600215
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52600311
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52603930
tagged with: deep-learning
tagged with: python
tagged with: object-detection
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: How do I know the total number of steps while training using Tensorflow Object Detection API?
has body: I've been running a training job for the last 3 hours on GPU powered cloud machine with the following command: python legacy/train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config and after running that, the log says this for example: INFO:tensorflow:global step 14455: loss = 0.5896 (0.775 sec/step) I1001 19:27:43.575182 140054916601600 tf_logging.py:116] global step 14455: loss = 0.5896 (0.775 sec/step) How do I know how many steps are there to be done or how many steps are there in total?
score: 2
has comment: http://stackoverflow.com/comment/124906089

http://stackoverflow.com/q/52636215
favorite count: 0
has comment: http://stackoverflow.com/comment/92205688
type: Question
tagged with: prompt
has answer: http://stackoverflow.com/a/52636318
has body: I'm working on a program that prompts a user for a number within a range of integers they've entered. If the number they enter is out of range, they're prompted to give another, and if they enter a letter instead they're prompted to change their answer as well. Here is what I've got: def code_one(d, f): s = input('Enter a number between' + str(d) + 'and' + str(f) + ': ') s = int(s) if int(d) &lt;= s &lt;= int(f): return s else: while s &lt; int(d) or s &gt; int(f): s = input(str(s) + 'is out of range. Please try again. ') s = int(s) if s &lt; int(d) or s &gt; int(f): continue else: return s while s.isdigit == False: s = input(str(s) + 'is not a number. Please try again.' ) if s.isdigit == False: continue else: return s It works fine up until the line reading "while s.isdigit == False:" and then, if I input a letter instead of a number, I get the error "invalid literal for int() with base 10: 'x'", (the x being whatever letter I happen to enter). What can I do to fix this?
has comment: http://stackoverflow.com/comment/92205674
has title: Invalid literal for int() with base 10: 'x' error in Python?
has comment: http://stackoverflow.com/comment/92205720
has comment: http://stackoverflow.com/comment/92205661
linked to: http://stackoverflow.com/q/20095244
tagged with: while-loop
downvote count: 3
answer count: 1
duplicate of: http://stackoverflow.com/q/20095244
type: UnansweredQuestion
score: -3
tagged with: python
upvote count: 0

command-line-arguments
tags question: http://stackoverflow.com/q/52746418
type: Tag
tags question: http://stackoverflow.com/q/52636309
tags question: http://stackoverflow.com/q/52671179
tag name: command-line-arguments

http://stackoverflow.com/q/52676223
has comment: http://stackoverflow.com/comment/92290095
tagged with: windows
tagged with: python
linked to: http://stackoverflow.com/q/4498099
has comment: http://stackoverflow.com/comment/92295930
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 1
tagged with: selenium
downvote count: 1
type: Question
tagged with: automation
has title: Automate printing of a page from PDF
has body: Let me walk you through the steps I need to automate: 1) Go to URL, fill out form, and click submit 2) This downloads a PDF 3) I want to only print second page of PDF So far, I've been using python with selenium to automate step 1 and 2. Now I am stuck at printing the second page of downloaded PDF. I would love it to be OS universal (I know I would have to write different logic between Windows and Mac), but if that is not possible, Windows is fine. So far I have looked at Silent printing of a PDF in Python But I was wondering if there any other solutions. Thank you
favorite count: 0
linked to: http://stackoverflow.com/q/27195594

http://stackoverflow.com/q/52627519
has title: Batch Prediction in Tensorflow session run
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: I am pretty new to Tensorflow and I would like to know when I load a frozen graph for prediction, is it possible to do a batch prediction like in keras. My code looks like the following in Tensorflow : path='some_path.pb' with dgraph.as_default(): od_graph_def=tf.GraphDef() with tf.gfile.GFile(path,'rb') as fid: serialized_graph=fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def,name='') sess = tf.Session(graph=dgraph) feat_5=detection_graph.get_tensor_by_name('Relu6:0') input=np.random.randn(100,300,300,3) sess.run([feat_5],feed_dict={image_tensor: input}) **want to add batches of data here instead of input directly
has comment: http://stackoverflow.com/comment/92190464
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/92212684
type: Question
downvote count: 0

http://stackoverflow.com/a/52738746
accepted answer of: http://stackoverflow.com/q/52738570
has comment: http://stackoverflow.com/comment/92403078
answers question: http://stackoverflow.com/q/52738570
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92402888
score: 0
type: Answer
has body: Initiliaze loss as a variable. When you define something as a placeholder, you have to feed it's value when running the graph dependent on it.

http://stackoverflow.com/comment/92245393
type: Comment
has text: This incorrectly sorts the IP-address lexicographically rather than numerically, so `192.168.70.123` would be ahead of `192.168.70.20`, for example.
score: 0
comment on: http://stackoverflow.com/a/52657142
type: AnswerComment

http://stackoverflow.com/q/52673987
has body: I am working with the MaskRCNN repo https://github.com/matterport/Mask_RCNN/blob/master/mrcnn/model.py Here in line 2064 in model.py before returning the built model back I want to extract the config using model.get_config() I get the following error. Since the entire network is built before Traceback (most recent call last): File "./samples/coco/coco.py", line 460, in &lt;module&gt; model_dir=args.logs) File "/mask_rcnn_root/Mask_RCNN/mrcnn/model.py", line 2063, in build print(self.keras_model.get_config()) File "/usr/local/lib/python3.5/dist-packages/keras/engine/network.py", line 926, in get_config return copy.deepcopy(config) File "/usr/lib/python3.5/copy.py", line 155, in deepcopy y = copier(x, memo) File "/usr/lib/python3.5/copy.py", line 243, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python3.5/copy.py", line 155, in deepcopy y = copier(x, memo) File "/usr/lib/python3.5/copy.py", line 218, in _deepcopy_list y.append(deepcopy(a, memo)) File "/usr/lib/python3.5/copy.py", line 155, in deepcopy y = copier(x, memo) File "/usr/lib/python3.5/copy.py", line 243, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python3.5/copy.py", line 155, in deepcopy y = copier(x, memo) File "/usr/lib/python3.5/copy.py", line 243, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python3.5/copy.py", line 155, in deepcopy y = copier(x, memo) File "/usr/lib/python3.5/copy.py", line 223, in _deepcopy_tuple y = [deepcopy(a, memo) for a in x] File "/usr/lib/python3.5/copy.py", line 223, in &lt;listcomp&gt; y = [deepcopy(a, memo) for a in x] File "/usr/lib/python3.5/copy.py", line 155, in deepcopy y = copier(x, memo) File "/usr/lib/python3.5/copy.py", line 223, in _deepcopy_tuple y = [deepcopy(a, memo) for a in x] File "/usr/lib/python3.5/copy.py", line 223, in &lt;listcomp&gt; y = [deepcopy(a, memo) for a in x] File "/usr/lib/python3.5/copy.py", line 182, in deepcopy y = _reconstruct(x, rv, …
downvote count: 0
favorite count: 0
has title: Keras model.get_config() raises error in deepcopy (MaskRCNN)
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1
tagged with: tensorflow
type: Question
tagged with: neural-network
tagged with: keras

http://stackoverflow.com/comment/92211626
comment on: http://stackoverflow.com/q/52639563
type: Comment
type: QuestionComment
has text: You want to replace dummy 1 with dummy 2?
score: 0

django
tags question: http://stackoverflow.com/q/52737613
tags question: http://stackoverflow.com/q/52620712
tags question: http://stackoverflow.com/q/52663370
tags question: http://stackoverflow.com/q/52632601
tags question: http://stackoverflow.com/q/52737568
tags question: http://stackoverflow.com/q/52673009
tags question: http://stackoverflow.com/q/52724487
tags question: http://stackoverflow.com/q/52727746
tags question: http://stackoverflow.com/q/52740918
tags question: http://stackoverflow.com/q/52724255
tags question: http://stackoverflow.com/q/52731018
tags question: http://stackoverflow.com/q/52699407
tags question: http://stackoverflow.com/q/52609136
tags question: http://stackoverflow.com/q/52682772
tags question: http://stackoverflow.com/q/52687706
tags question: http://stackoverflow.com/q/52685896
tags question: http://stackoverflow.com/q/52590260
tags question: http://stackoverflow.com/q/52662393
tags question: http://stackoverflow.com/q/52665479
tags question: http://stackoverflow.com/q/52645858
tags question: http://stackoverflow.com/q/52733905
tags question: http://stackoverflow.com/q/52656156
tags question: http://stackoverflow.com/q/52732691
tags question: http://stackoverflow.com/q/52629800
tags question: http://stackoverflow.com/q/52747055
tags question: http://stackoverflow.com/q/52703725
tags question: http://stackoverflow.com/q/52626184
tags question: http://stackoverflow.com/q/52620784
tags question: http://stackoverflow.com/q/52676415
tags question: http://stackoverflow.com/q/52735322
tags question: http://stackoverflow.com/q/52628944
tags question: http://stackoverflow.com/q/52732744
tags question: http://stackoverflow.com/q/52640992
tags question: http://stackoverflow.com/q/52614854
tags question: http://stackoverflow.com/q/52677365
tags question: http://stackoverflow.com/q/52599057
tags question: http://stackoverflow.com/q/52594121
tags question: http://stackoverflow.com/q/52641360
tags question: http://stackoverflow.com/q/52633697
type: Tag
tags question: http://stackoverflow.com/q/52682401
tags question: http://stackoverflow.com/q/52592298
tags question: http://stackoverflow.com/q/52651205
tags question: http://stackoverflow.com/q/52698292
tags question: http://stackoverflow.com/q/52668420
tags question: http://stackoverflow.com/q/52609069
tags question: http://stackoverflow.com/q/52647132
tags question: http://stackoverflow.com/q/52711577
tags question: http://stackoverflow.com/q/52633383
tags question: http://stackoverflow.com/q/52708193
tags question: http://stackoverflow.com/q/52650006
tags question: http://stackoverflow.com/q/52720185
tags question: http://stackoverflow.com/q/52627904
tags question: http://stackoverflow.com/q/52687605
tags question: http://stackoverflow.com/q/52653782
tags question: http://stackoverflow.com/q/52724382
tags question: http://stackoverflow.com/q/52710854
tags question: http://stackoverflow.com/q/52591354
tags question: http://stackoverflow.com/q/52616549
tags question: http://stackoverflow.com/q/52728144
tags question: http://stackoverflow.com/q/52709367
tags question: http://stackoverflow.com/q/52618805
tags question: http://stackoverflow.com/q/52627833
tags question: http://stackoverflow.com/q/52729288
tags question: http://stackoverflow.com/q/52610231
tags question: http://stackoverflow.com/q/52623974
tags question: http://stackoverflow.com/q/52695868
tags question: http://stackoverflow.com/q/52604074
tags question: http://stackoverflow.com/q/52605132
tags question: http://stackoverflow.com/q/52736737
tags question: http://stackoverflow.com/q/52698322
tags question: http://stackoverflow.com/q/52592658
tags question: http://stackoverflow.com/q/52611505
tags question: http://stackoverflow.com/q/52673980
tags question: http://stackoverflow.com/q/52746119
tags question: http://stackoverflow.com/q/52728790
tags question: http://stackoverflow.com/q/52696693
tags question: http://stackoverflow.com/q/52606820
tags question: http://stackoverflow.com/q/52705444
tags question: http://stackoverflow.com/q/52701655

http://stackoverflow.com/a/52666464
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52666429
score: 1
has body: try: with open('file.log') as file: read_data = file.read() except Exception as e: print(e) You have to cast the Exception to a variable. This and more is in the Python documentation.
downvote count: 0
answers question: http://stackoverflow.com/q/52666429
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/52653374
type: Question
has comment: http://stackoverflow.com/comment/92903605
has comment: http://stackoverflow.com/comment/92928011
has comment: http://stackoverflow.com/comment/92241456
has comment: http://stackoverflow.com/comment/92243095
has comment: http://stackoverflow.com/comment/92851447
tagged with: twisted
has comment: http://stackoverflow.com/comment/92863660
linked to: http://stackoverflow.com/q/3071237
has body: There is a Twisted server which gives responses to clients' requests. The "LineOnlyReceiver" is used for the protocol design. The process should go as following: A client sends a request to the server (such as "TEMP?" asking the temperature), then the number of request on the server should increase by 1. After the server sends back the response, the number should decrease by 1. However, during the request ("TEMP?") being processed by the server, there could be other clients sending requests to the server, the number of requests on the server should vary with time. So how to keep track of the number of requests on the server on-the-fly? Currently, the "lineReceived" method is used to receive requests from clients and send back responses (other codes omitted): Class SimProtocol(LineOnlyReceiver): def lineReceived(self, request): self.factory.taskNumber[request.strip()] += 1 print 'Task number: ', self.factory.taskNumber[request.strip()] time.sleep(10) resp = self.factory.getResponse(request.strip()) self.transport.write(resp) self.factory.taskNumber[request.strip()] -= 1 print 'Task number: ', self.factory.taskNumber[request.strip()] The 10 seconds delay is added in the middle on purpose to simulate the processing time of the requests. During the 10 seconds, there are several other requests being sent to the server, but the server didn't respond to other requests until it finishes the current one. In other words, the "print" statements always show the task number is 1, 0, 1, 0..., no matter how many clients are sending requests. So what kind of design approach (probably a totally different one, like getting the reactor queue size could do?) should be used to accomplish this functionality (keep track of the number of requests on the server on-the-fly)?
linked to: http://stackoverflow.com/q/80617
linked to: http://stackoverflow.com/q/6117587
linked to: http://stackoverflow.com/q/2466000
answer count: 0
has comment: http://stackoverflow.com/comment/92930872
has title: Twisted Server: How to keep track of the number of requests on the server?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92925091
has comment: http://stackoverflow.com/comment/92931123
has comment: http://stackoverflow.com/comment/92932286
score: 0
has comment: http://stackoverflow.com/comment/92894886
has comment: http://stackoverflow.com/comment/92240076
has comment: http://stackoverflow.com/comment/92903965

http://stackoverflow.com/comment/92178652
score: 0
has text: [here](https://stackoverflow.com/questions/36139/how-to-sort-a-list-of-strings)
comment on: http://stackoverflow.com/q/52622323
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52609724
answer count: 2
downvote count: 1
accepted answer: http://stackoverflow.com/a/52610029
has body: I have the following scenario, where a text file has something like the following output: DecodingIndex[ 1] PresentationIndex[ 2] DecodingIndex[ 2] PresentationIndex[ 3] DecodingIndex[ 3] PresentationIndex[ 1] etc... Since it shows the numbers within DecodingIndex sequential, I want it to be sorted instead by PresentationIndex. Like the following: DecodingIndex[ 3] PresentationIndex[ 1] DecodingIndex[ 1] PresentationIndex[ 2] DecodingIndex[ 2] PresentationIndex[ 3] Is there an easy way to do this in Python? These numbers go all the way to to tens of thousands. The distance between the square brackets always has a gap for numbers less than 10, and then hugs the numbers e.g DecodingIndex[32100] Hope that made sense and thanks for your help! ======= Here's what I have tried: 1)I iterate through each line in the file and store into a lines[] list 2)Iterate through each item in the lines[] list, while using the following regex pattern re.compile(r'PresentationIndex\[(.*?)\]') 3)I then get the matches out of the result using group() and store these values in a new list 4)I then sort the list numerically by first turning the items into an int, then sorting, then turning it back into an string like this 5)Now I iterate through that list and insert the words PresentationIndex and square brackets in 6)Using the now sorted list of PresentationIndex, I iterate through each of these. For each iteration, I iterate through the whole output text file to search for the associated line and append this to a final list. This way I get my output in the order I want. I started out with a file of about 32,000 lines. Doing this sort took about 3 hours...
possible better answer: http://stackoverflow.com/a/52610527
has answer: http://stackoverflow.com/a/52610527
tagged with: brackets
score: 2
type: AnsweredQuestion
has title: How to sort numerically by what's between square brackets
tagged with: sorting
favorite count: 0
has comment: http://stackoverflow.com/comment/92154103
has comment: http://stackoverflow.com/comment/92154108
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/92154059
has comment: http://stackoverflow.com/comment/92153788
has comment: http://stackoverflow.com/comment/92153966
upvote count: 3
has answer: http://stackoverflow.com/a/52610029

http://stackoverflow.com/q/52732448
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52732496
type: Question
answer count: 1
has body: I am trying to parse CSS file to change style fo html. Look at the example CSS text as follow : p.FM_table_cell_body308 { margin-left:0.000pt; margin-right:0.000pt; text-align:left; text-indent:0.000pt; } p.FM_table_cell_body309 { margin-left:0.000pt; margin-right:0.000pt; text-align:left; text-indent:0.000pt; } p.FM_table_cell_body { margin-left:0.000pt; margin-right:0.000pt; text-align:left; text-indent:0.000pt; } I want to change the word 'left' of 'text-align:left;' to 'center' in every under 'p.FM_table_cell_body*** {' (*** is number). So, this is what i am looking foward as follow : p.FM_table_cell_body308 { margin-left:0.000pt; margin-right:0.000pt; text-align:center; text-indent:0.000pt; } p.FM_table_cell_body309 { margin-left:0.000pt; margin-right:0.000pt; text-align:center; text-indent:0.000pt; } p.FM_table_cell_body { # this has no number so should pass margin-left:0.000pt; margin-right:0.000pt; text-align:left; # no change text-indent:0.000pt; } And it's what i am coding so far as below : from bs4 import BeautifulSoup import glob2 import re with open ("C:\\TEST\\HTML\\Output_sample1\\Responsive HTML5\\Output.css","r",encoding="utf-8") as file_css : with open ("C:\\TEST\\HTML\\Output_sample1\\Responsive HTML5\\Output_test.css","wt",encoding="utf-8") as file_css_text_align : lines_css = file_css.readlines() for i_css, line_css in enumerate(lines_css[:-1]): try : FM_number_css = re.findall('FM_table_cell_body[1-9][0-9]?[0-9]?[0-9]?', line_css) text_align_content = lines_css[i_css + 3] if FM_number_css and text_align_content == 'text-align:left;': text_align_content = text_align_content.split(':') text_align_content.remove('left;\n') text_align_content.insert(1, 'center;\n') new_text_align_content = ':'.join(text_align_content) file_css_text_align.write(str(new_text_align_content)) else : file_css_text_align.write(str(line_css)) except : pass but this code i am trying to make doesn't work right. this code changes not this(text-align:left;) but (p.FM_table_ce…
accepted answer: http://stackoverflow.com/a/52732496
score: 0
tagged with: python
tagged with: regex
has title: CSS parsing using python using regex or anything else?

http://stackoverflow.com/q/52662009
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/52662251
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/55099986
type: Question
has body: I have an XML file which has the following format - &lt;root&gt; &lt;tag&gt; This is the first Value. &lt;/tag&gt; &lt;tag&gt; This is the second Value. &lt;/tag&gt; &lt;/root&gt; When I convert this XML string to JSON in Python using the following code jsonString=json.dumps(XML_String) The tag becomes an array and the JSON file I get is like this - {"root":["tag":"This is the first Value", "tag":"This is the second Value"]} What I actually want is the &lt;root&gt; tag should be an object instead of an array. Like this - {"root":{"tag":"This is the first Value", "tag":"This is the second Value"}} How to achieve such kind of format?
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/52662251
tagged with: mongodb
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/55099986
has title: How to prevent same name XML tags being converted to Array when converting the XML String to JSON using Python?
tagged with: python
tagged with: parsing

http://stackoverflow.com/q/52672529
has answer: http://stackoverflow.com/a/52673416
accepted answer: http://stackoverflow.com/a/52673416
has comment: http://stackoverflow.com/comment/92276652
has comment: http://stackoverflow.com/comment/92275324
downvote count: 1
linked to: http://stackoverflow.com/q/41453850
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92275132
has comment: http://stackoverflow.com/comment/92275282
score: -1
type: Question
has body: Here is a game from the book "Python Crash Course (author: Eric Matthes)" I do exactly what the book told. But I found these problems, and why? File "D:\pythoncode\l_one\venv\lib\site-packages\pygame\sprite.py", line 1586, in spritecollideany spritecollide = sprite.rect.colliderect AttributeError: 'pygame.Surface' object has no attribute 'rect' Here are my codes: https://github.com/yushu-liu/Learn_Python/tree/master/Alien_Invasion And part of my codes as follows(aline_invasion.py): import sys from settings import Settings from ship import Ship from pygame.sprite import Group import game_functions as gf from alien import Alien from game_stats import GameStats import pygame 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") # Set the background Color bg_color = (230,230,230) # Make a ship, a group of bullets, and a group of aliens. ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() # Create the fleet of aliens gf.create_fleet(ai_settings,screen,ship,aliens) # Create an instance to store game statistics. stats = GameStats(ai_settings) # Start the main loop for the game while True: # Watch for keyboard and mouse events gf.check_events(ai_settings,screen,ship,bullets) if stats.game_active: ship.update() # Make the most recently drawn screen visible gf.update_bullets(ai_settings,screen,ship,aliens,bullets) gf.update_aliens(ai_settings,stats,ship,screen,aliens,bullets) gf.update_screen(ai_settings,screen,ship,aliens,bullets) run_game() And another part of my codes as follows(game_function.py): import sys import pygame from bullet import Bullet from alien import Alien from time import sleep def check_keydown_events(event,ai_settings,screen,ship,bullets): '''Respond to keypresses''' if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.m…
upvote count: 0
has comment: http://stackoverflow.com/comment/92274931
answer count: 1
favorite count: 0
has title: AttributeError 'pygame.Surface' object has no attribute 'rect'
tagged with: python
tagged with: pygame

http://stackoverflow.com/a/52735936
upvote count: 4
downvote count: 0
has body: I think this might do it: import hashlib, os basedir = os.path.abspath(os.path.dirname(__file__)) hasher = hashlib.md5() directory = "/".join((basedir,"venv")) bs=4096 def flatten(d): for path, dirs, filenames in os.walk(d): for filename in filenames: yield os.path.join(path, filename) if os.path.exists(directory): dircontent = list(flatten(directory)) for item in dircontent: with open(item, "rb") as _f: buf = _f.read(bs) while len(buf) &gt; 0: hasher.update(buf) buf = _f.read(bs) else: exit(1) print(hasher.hexdigest()) The flatten function is fairly straightforward, it just walks the venv and creates one huge list with all the filepaths from top to bottom of the file tree, beginning at whatever path you provide as d-parameter. I took that from here I then open the file in ro,b mode and read small chunks into a buffer (as to not clog the systems memory in case of unexpected large files) and update the md5-hashobject with the buffers content. This is being done for every file in venv. Not sure if this is a viable solution for you, but it was great fun doing this, so thanks for your question :)
type: Answer
score: 4
answers question: http://stackoverflow.com/q/52734619

http://stackoverflow.com/comment/92386015
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52730375
has text: Thanks, so I changed the specifier to: html = driver.execute_script("return document.documentElement.outerHTML") soup = BeautifulSoup(html, 'html.parser') soup.findAll("span", {"class": "sectionals-time"}) but the result is still Out[19]: []

http://stackoverflow.com/q/52735509
tagged with: amazon-web-services
tagged with: aws-lambda
has comment: http://stackoverflow.com/comment/92403954
has comment: http://stackoverflow.com/comment/92402815
type: UnansweredQuestion
tagged with: python
has body: Am new to aws development and was trying to do password less features using aws cognito's Custom Auth Flow, lambda triggers and the aws python SDK. My problem is after the call to InitiateAuth, I always get the error below: An error occurred (InvalidLambdaResponseException) when calling the InitiateAuth operation: Unrecognizable lambda output Full traceback is: Traceback (most recent call last): File "test_custom_auth.py", line 52, in &lt;module&gt; ClientId=client_id File "/Users/jules/Repositories/snaaap/onemac-api/env/lib/python3.6/site-packages/botocore/client.py", line 320, in _api_call return self._make_api_call(operation_name, kwargs) File "/Users/jules/Repositories/snaaap/onemac-api/env/lib/python3.6/site-packages/botocore/client.py", line 623, in _make_api_call raise error_class(parsed_response, operation_name) botocore.errorfactory.InvalidLambdaResponseException: An error occurred (InvalidLambdaResponseException) when calling the InitiateAuth operation: Unrecognizable lambda output I can see thru cloudwatch logs that the defineAuthChallenge Trigger and createAuthChallenge Trigger calls are successful and was even able to print out logs to verify this. I did the lambda functions first with Javascript, then with Python, just to try another method. I tried to return the following in python (I am editing using the lambda editor console) return event result = { "isBase64Encoded": False, "statusCode": 200, "headers": {}, "body": json.dumps(event) } return result I tried to return the following in javascript (I am editing using the lambda editor console) context.succeed(event) callback(null, event) context.done(event) context.done(JSON.stringify(event)) And permutations of those mentioned above, but I still kept on getting the error :( Appreciate anyone that can help! EDIT Performed another request: Below are the logs from defineAuthChallenge: START RequestId: 14441740-cc65-11e8-a632-9508cbba464c Version: $LATEST END RequestId: 14441740-cc65-11e8-a632-9508cbba464…
has comment: http://stackoverflow.com/comment/92397662
tagged with: amazon-cognito
type: Question
has comment: http://stackoverflow.com/comment/92403204
has title: An error occurred (InvalidLambdaResponseException) when calling the InitiateAuth operation: Unrecognizable lambda output
has answer: http://stackoverflow.com/a/52739861
score: 0
answer count: 1
tagged with: javascript

http://stackoverflow.com/a/52682407
has comment: http://stackoverflow.com/comment/92293684
accepted answer of: http://stackoverflow.com/q/52682345
type: Answer
has comment: http://stackoverflow.com/comment/92293744
score: 1
has comment: http://stackoverflow.com/comment/92293601
has comment: http://stackoverflow.com/comment/92293785
upvote count: 1
has comment: http://stackoverflow.com/comment/92293765
has comment: http://stackoverflow.com/comment/92294073
has body: you can use pythons re library for regex and re.IGNORECASE for your second problem, like this: import re ### rest of your code regx = re.compile("^foo", re.IGNORECASE) myCursor = db.collection.find({"chip" : "4377","branch" : regx}).sort({"_id":-1}) print myCursor About your updated question: Thats another issue and its about using sort() with pymongo, you can see the answer here In short you should use .sort() like this: .sort([("_id", -1)])
has comment: http://stackoverflow.com/comment/92293643
has comment: http://stackoverflow.com/comment/92293964
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52682345

http://stackoverflow.com/q/52736390
score: 3
has answer: http://stackoverflow.com/a/52745090
favorite count: 0
tagged with: azure-resource-manager
tagged with: python
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/52745090
type: Question
has title: Paging async iterator protocol is not available (Azure SDK for Python)
has body: What I'm trying to achieve I'm trying to automate subscription and resource group creation on Azure using the Python SDK. To do that, I need a Service Principal Account (Client Id; Client Secret; Tenant Id) with Permissions to at least retrieve Enrollment Accounts and create the subscriptions and resource groups. How I'm trying to achieve it I tried listing the enrollment accounts without success (yes, I'm importing azure.mgmt.billing, azure.mgmt and azure.common, among others) First I instantiate the client: billing_client = azure.mgmt.billing.BillingManagementClient(credentials, subscription_id) Then I tried printing the results in two different ways: # A print(list(billing_client.enrollment_accounts.list())) # B for enrollment_account in billing_client.enrollment_accounts.list(): print(enrollment_account) What problem am I facing? The problem I'm experiencing is that I get the following error: Paging async iterator protocol is not available for EnrollmentAccountPaged This also happens with other list() methods, like when I retrieve resource groups using something like rm_client = ResourceManagementClient(credentials, subscription_id) resource_groups = rm_client.resource_groups.list() Then, I get the error: Paging async iterator protocol is not available for ResourceGroupPaged How would I consider my problem solved? I'd love to know why I'm getting this error, and how to fix it. The example code from Azure doesn't use the methods or objects in a different way. How's the environment? Python version: Python 3.7 Packages: Package Version Latest Version PyJWT 1.6.4 1.6.4 adal 1.1.0 1.1.0 asn1crypto 0.24.0 0.24.0 azure-common 1.1.16 1.1.16 azure-mgmt 4.0.0 4.0.0 azure-mgmt-advisor 1.0.1 1.0.1 azure-mgmt-applicationinsights 0.1.1 0.1.1 azure-mgmt-authorization 0.50.0 0.50.0 azure-mgmt-batch 5.0.1 5.0.1 azure-mgmt-batchai 2.0.0 2.0.0 azure-mgmt-billing 0.2.0 0.2.0 azure-mgmt-cdn 3.0.0 3.0.0 azure-mgmt-cognitiveservices 3.0.0 3.0.0 azure-mgmt-commerce 1.0.1 1.0.1 azure-mg…
downvote count: 0
answer count: 1
tagged with: azure

http://stackoverflow.com/comment/92406997
score: 1
type: Comment
comment on: http://stackoverflow.com/a/52740741
has text: @Chrisvdberge presumably the module was cached so your code was still looking at the wrong library. I'm not convinced that starting a new environment is _required_ for it to work, but I can't test on my end with Pycharm to find a cleaner approach
type: AnswerComment

http://stackoverflow.com/q/52739576
duplicate of: http://stackoverflow.com/q/32815451
duplicate of: http://stackoverflow.com/q/10434599
has title: Flask - get user input and pass it to backend
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/52740253
type: AnsweredQuestion
upvote count: 3
downvote count: 1
type: Question
has body: I want to get user input and validate if it is correct or not in the backend... There is something missing but I am not able to figure it out: run.py code: @app.route('/game', methods = ["GET","POST"]) def game(): global answer_number global user_correct global user_wrong with open ("data/riddles.json", "r") as jason_data: data = json.load(jason_data) if request.method == "POST": user_answer.append(request.form["answer"]) if user_answer [-1] == data[answer_number]["answer"]: answer_number += 1 user_correct += 1 else: user_wrong += 1 print (answer_number, user_correct, user_wrong) return render_template("game_page.html", user_list = user_list, riddles_data = data, user_answer=user_answer, answer_number=answer_number) game_page.html code: Write down your answer
linked to: http://stackoverflow.com/q/504947
tagged with: flask
duplicate of: http://stackoverflow.com/q/504947
has answer: http://stackoverflow.com/a/52740253
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/110933

http://stackoverflow.com/q/52681646
answer count: 1
favorite count: 0
tagged with: slack-api
has comment: http://stackoverflow.com/comment/92291533
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92291640
has title: Python TypeError: 'NoneType' object is not iterable but every variables defined
tagged with: python
has comment: http://stackoverflow.com/comment/92291551
has comment: http://stackoverflow.com/comment/92291785
downvote count: 0
accepted answer: http://stackoverflow.com/a/52681948
score: 1
has comment: http://stackoverflow.com/comment/92291670
has comment: http://stackoverflow.com/comment/92292185
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52681948
has body: I am trying to build a bot that connects to slack, and keep receiving a TypeError: Traceback (most recent call last): File "happybotV4.2.py", line 217, in &lt;module&gt; av_mood, user_count, total_mood = datamood(user_answer, user_id, user_count, total_mood, av_mood) TypeError: 'NoneType' object is not iterable Here is the code: if slackinput_list and len(slackinput_list) &gt; 0: user_answer, user_id, channel, event_type = parse_slack_useranswer(slackinput_list) #print(user_answer,user_id)#test if user_answer and user_id and user_id != 'U7GRT34H3' and event_type=="message": if user_answer=="1" or user_answer=="5": print(user_answer, user_id, user_count, total_mood, av_mood) #test #if user_id not in user_list: av_mood, user_count, total_mood = datamood(user_answer, user_id, user_count, total_mood, av_mood) And datamood's code: def datamood(mood, user, count, total_mood, average_mood): print(user_list) if user not in user_list: count = count+1 mood_user.append(mood) user_list.append(user) print(user_list, user) if len(mood_user)&gt;0: for i in mood_user : if i=="1": n=1 elif i=="5": n=5 total_mood = total_mood + n print(total_mood)#test average_mood = total_mood/count print (average_mood, count) #test return average_mood, count, total_mood else: return average_mood, count, total_mood In fact datamood works one time, but when I try to call it a second time I get the error. I checked that every variable (that is user_answer, user_id, user_count, total_mood, av_mood) are not None and are in the correct format. Any ideas?
has comment: http://stackoverflow.com/comment/92291761
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92291904
upvote count: 1
has comment: http://stackoverflow.com/comment/92291679

http://stackoverflow.com/comment/92168013
comment on: http://stackoverflow.com/q/52616695
score: 0
type: Comment
type: QuestionComment
has text: Does it work if you try a different image?

http://stackoverflow.com/q/52675678
has body: I am currently learning python and while trying to find a way to compile data from IP registrations, I stumbled into nested dictionaries/lists. I have found a way to pull the data I wanted but this seems excessive but all of my attempts to consolidate the iteration has failed. Any documentation on this subject or some pointers would be greatly appreciated. from ipwhois import IPWhois obj = IPWhois('8.8.8.8') results = obj.lookup_rdap(depth=1) for key, val in results.items(): if isinstance(val, dict): if key == 'objects': objects = (val) for key, val in objects.items(): if isinstance(val, dict) and key.startswith("ABUSE"): abuse =(val) for key, val in abuse.items(): if isinstance(val, dict): contact = (val) for key,val in contact.items(): if isinstance(val, list): if key == 'email': email = (val) value=(email[0]) print (value['value'])
tagged with: iteration
favorite count: 0
type: UnansweredQuestion
has title: Python interation and recursion
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/52675966
type: Question
score: -2
downvote count: 2
answer count: 1
tagged with: nested

http://stackoverflow.com/comment/92395725
comment on: http://stackoverflow.com/q/52735322
has text: you use a template for a JSON stream :O? What is the serializer then doing?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92168251
comment on: http://stackoverflow.com/q/52617018
type: Comment
score: 1
type: QuestionComment
has text: You wrote: "I need to set a zero where the year...is less than the value associate to the column `year_out`", but in your expected output you have set 0 for all the years *greater* than `year_out`. Which do you want?

http://stackoverflow.com/q/52613002
tagged with: python
score: 0
has title: How to build bar graph or line graph for weekly data in pandas
tagged with: graph
has comment: http://stackoverflow.com/comment/92160493
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92160507
tagged with: pandas-groupby
tagged with: pandas
has body: I want to build the week on the x-axis and the count on the Y-axis for both line and bar graph. MY data in data frame. Date----------- count 06-01-2017 18.51 1 06-01-2017 19.11 10 20-01-2017 19.55 20 21-01-2017 20.10 30 22-01-2017 20.10 40 23-01-2017 20.10 50 23-01-2017 20.10 60 29-01-2017 21.33 70 Please advice df = data.groupby([ pd.Grouper(key='date', freq='W-MON')])['value'].sum().reset_index().sort_values('date') x= df['date'] y = df['value'] fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x, y, color='skyblue') ax1.set_xticklabels(x,rotation=90) plt.show() this is giving me graph for month wise i need for week wise
answer count: 0
type: Question

global
type: Tag
tag name: global
tags question: http://stackoverflow.com/q/52709289
tags question: http://stackoverflow.com/q/52651270
tags question: http://stackoverflow.com/q/52666536

http://stackoverflow.com/a/52736144
has body: As you can see the correct list is the last printed list. it is because you put your print function inside your loop and will print out the current list in all iteration, so, remove the print from for body and put it out of the loop. for line in stdout.split('\n')[1:10]: lines.append(line) print(lines)
upvote count: 1
answers question: http://stackoverflow.com/q/52736034
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52736034
type: Answer
score: 1

c#
tags question: http://stackoverflow.com/q/52624483
tags question: http://stackoverflow.com/q/52593393
tag name: c#
tags question: http://stackoverflow.com/q/52705347
tags question: http://stackoverflow.com/q/52654470
tags question: http://stackoverflow.com/q/52672972
tags question: http://stackoverflow.com/q/52626753
tags question: http://stackoverflow.com/q/52692806
tags question: http://stackoverflow.com/q/52672375
type: Tag
tags question: http://stackoverflow.com/q/52736438
tags question: http://stackoverflow.com/q/52647908
tags question: http://stackoverflow.com/q/52612651
tags question: http://stackoverflow.com/q/52678613

http://stackoverflow.com/q/52653144
has body: Content of my csv file is:: [user@localhost ~]$ cat tempcsv.csv info,info,auth,req,req name,desc,username,key1,key2 a,alphabet,admin,1,team Here, the csv contains two headers. On using pandas to read the csv, &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; pd.read_csv('tempcsv.csv', sep=',', header=[0,1], encoding = "utf-8-sig", skipinitialspace=True, tupleize_cols=True) (info, name) (info, desc) (auth, username) (req, key1) (req, key2) 0 a alphabet admin 1 team &gt;&gt;&gt; df = pd.read_csv('tempcsv.csv', sep=',', header=[0,1], encoding = "utf-8-sig", skipinitialspace=True, tupleize_cols=True) &gt;&gt;&gt; df.to_dict() {(u'req', u'key1'): {0: 1}, (u'req', u'key2'): {0: u'team'}, (u'info', u'name'): {0: u'a'}, (u'auth', u'username'): {0: u'admin'}, (u'info', u'desc'): {0: u'alphabet'}} Now on trying to convert the dataframe to dict, I get a list dicts that have key as tuple. &gt;&gt;&gt; df.to_dict('records') [{(u'req', u'key1'): 1, (u'req', u'key2'): u'team', (u'info', u'name'): u'a', (u'auth', u'username'): u'admin', (u'info', u'desc'): u'alphabet'}] When I try to convert them to a proper dictionary, &gt;&gt;&gt; result = [] &gt;&gt;&gt; row_data = {} &gt;&gt;&gt; for row in df.to_dict('records'): ... for key,value in row.iteritems(): ... row_data.setdefault(key[0], {})[key[1]] = value ... &gt;&gt;&gt; row_data {u'info': {u'name': u'a', u'desc': u'alphabet'}, u'req': {u'key2': u'team', u'key1': 1}, u'auth': {u'username': u'admin'}} And that is my expected output -- {u'info': {u'name': u'a', u'desc': u'alphabet'}, u'req': {u'key2': u'team', u'key1': 1}, u'auth': {u'username': u'admin'}} So my question is, is there any way to convert the dataframe to dict using python? Or, is there a way to do the same using csv package? Pandas version: &gt;&gt;&gt; import pandas as pd pd&gt;&gt;&gt; pd.__version__ '0.14.1'
accepted answer: http://stackoverflow.com/a/77002494
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77002494
possible better answer: http://stackoverflow.com/a/52653932
has title: Convert multiheader csv to nested dictionary in python
type: Question
score: 0
has answer: http://stackoverflow.com/a/52653932
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/52704990
tagged with: python
has comment: http://stackoverflow.com/comment/92336631
tagged with: nlp
answer count: 0
tagged with: text-classification
type: Question
has comment: http://stackoverflow.com/comment/92336774
score: 0
has title: Text classification + NLP + Python : Warning: The least populated class in y has only 23 members, which is too few
has body: I am working on a text classification problem for which I am using 30 fold cross validation. Before starting experiment I made sure that each class had at least 30 members. Then I did necessary text processing and split my dataset into test and train sets. x_train, x_test, y_train, y_test = cross_validation.train_test_split(data['event_name_description'], data['category_id'], test_size=0.2, random_state=42) Test set consists of 20% of total data. Now when I run my model for training, I get this warning: /home/hp/anaconda3/envs/tensorflow/lib/python3.5/site-packages/sklearn/cross_validation.py:553: Warning: The least populated class in y has only 23 members, which is too few. The minimum number of labels for any class cannot be less than n_folds=30. Apparently, it seems after splitting my data into test set and train set, I have at least one class in my train set which has as few as 23 members. Am I correct?
type: UnansweredQuestion
tagged with: machine-learning

http://stackoverflow.com/comment/92362903
type: QuestionComment
type: Comment
has text: two things: (1) the error is interesting - could you please include the code the code that is making the requests in parallel? (2) i don't think that your traversal is doing what you describe - please include a Gremlin script that creates some sample data like the example shown here: https://stackoverflow.com/questions/51388315/gremlin-choose-one-item-at-random
comment on: http://stackoverflow.com/q/52698115
score: 0

http://stackoverflow.com/a/52597914
has comment: http://stackoverflow.com/comment/92130574
has comment: http://stackoverflow.com/comment/92130534
type: Answer
accepted answer of: http://stackoverflow.com/q/52597864
score: 1
has comment: http://stackoverflow.com/comment/92130471
has comment: http://stackoverflow.com/comment/92130632
upvote count: 1
has comment: http://stackoverflow.com/comment/92131252
has body: So long as the list isn't empty then yes you can use a list to be evaluated as a True bool in and if/elif/else statement. Empty lists will be False, lists with at least 1 item will be True You can always just try your own code out to see for yourself!
has comment: http://stackoverflow.com/comment/92130499
has comment: http://stackoverflow.com/comment/92130515
answers question: http://stackoverflow.com/q/52597864
has comment: http://stackoverflow.com/comment/92134310
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92131875

http://stackoverflow.com/q/52628369
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/3964681
score: 0
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52628855
tagged with: python
tagged with: opencv3.0
has body: I need to read a folder with a lot of .bmp files, and put all of the images on a lits of images. I do not know how to handle the adress. I was doing some thing like this: adress = "c:/Users/My Name/Desktop/assignment/*.bmp" imageArray = [cv2.imread(file) for file in glob.glob(adress)] numImg = len(imageArray) Inside the assignment folder, there is the Images folder with all the images I need. How to make this work?
type: UnansweredQuestion
has title: Python OpenCV- Problems reading files on Windows
tagged with: image-processing

http://stackoverflow.com/q/52611032
accepted answer: http://stackoverflow.com/a/52621376
type: AnsweredQuestion
tagged with: tkinter
downvote count: 0
score: 1
has title: Disable click events from queuing on a widget while another function runs
type: Question
has comment: http://stackoverflow.com/comment/92156479
has body: I have a function (A) that is bound to a click event on a Canvas. At some point, function A calls another function (B). The canvas contents may change in function B, so I want it to ignore canvas click events while it's running. I've tried setting a bool variable that is checked when function A is called to False before the function B is called and then resetting it to True when the function B is done, but the event still queues with bad mouse coordinates for the new contents. I've tried re-binding canvas click events to a function (C) that just returns "break" then calling the function B then re-binding canvas click events back to function A. Still queues with bad mouse coordinates for the new contents. I've tried setting the canvas state to "disabled" calling function B then setting the state to "normal". I've tried returning "break" from function A, function B, and from both. I get the same result it still queues with bad mouse coordinates for the new contents. Any suggestions? the code I'm using for testing options in its current state: import time from tkinter import * class test_form(object): def __init__(self, master): self.master = master self._CreateGUI() def _CreateGUI(self): geom = "200x175+0+0" self.master.geometry(geom) self.xx=Canvas(bg='#ff0000',width=100,height=75) self.xx.bind('&lt;ButtonRelease&gt;',self.test_button) self.xx.pack() def waste_time(self): print('time wasted') time.sleep(10) return "break" def test_button(self,event=None): self.waste_time() return "break" def start_gui(): root = Tk() form_load = test_form(root) root.mainloop() if __name__ == "__main__": start_gui()
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52621376

http://stackoverflow.com/q/52712726
tagged with: postgresql
answer count: 1
favorite count: 0
has body: I have a list of ids like: tracker_ids = [69] I need to get all the APInformation objects based on the tracker_id. data looks like this: { 'tracker_id' : 69, 'cpu_core_avg': 89.890', 'is_threshold': true,'datetime':1539053379040 } { 'tracker_id' : 70, 'cpu_core_avg': 65.0', 'is_threshold': false, 'datetime':1539053379040 } { 'tracker_id' : 69, 'cpu_core_avg': 34.9', 'is_threshold': false,'datetime':1539053379040 } I tried the following but it raises an error. session.query(APInformation).\ filter(APInformation.data['tracker_id'].in_(tracker_ids), APInformation.data['datetime'].astext.cast(BigInteger) &gt; 1539053379040).\ all() the error it throws: ProgrammingError: (psycopg2.ProgrammingError) operator does not exist: jsonb = integer LINE 3: ...oring_apinfomation".data -&gt; 'tracker_id') IN (69) ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
upvote count: 2
has title: SQLAlchemy jsonb column - How to perform filter based on list of ids on a key
has comment: http://stackoverflow.com/comment/92351936
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: sqlalchemy
type: Question
downvote count: 0
tagged with: jsonb
has comment: http://stackoverflow.com/comment/92354583
has answer: http://stackoverflow.com/a/52714756
accepted answer: http://stackoverflow.com/a/52714756

http://stackoverflow.com/a/52633715
has comment: http://stackoverflow.com/comment/92201516
has comment: http://stackoverflow.com/comment/92201768
has comment: http://stackoverflow.com/comment/92200759
score: 3
answers question: http://stackoverflow.com/q/52633366
upvote count: 3
has comment: http://stackoverflow.com/comment/92200895
has comment: http://stackoverflow.com/comment/92202119
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92202216
accepted answer of: http://stackoverflow.com/q/52633366
type: Answer
has body: You might be interested in invoke_without_command. It's a parameter you pass to your group that tells it to only run the callback if there is no subcommand. So your group would be @commands.group(invoke_without_command=True) @commands.has_permissions(administrator=True) async def autorole(self, ctx): exists = dbinteraction.dbexec("SELECT role from autorole WHERE server_id = {}".format(ctx.guild.id)) if (exists == None): em = discord.Embed(title="Autorole is disabled for this guild.", color=discord.Color(0xff0000)) else: em = discord.Embed(title="Autorole is enabled for this guild.", color = discord.Color(0x32ff00)) rol = discord.utils.get(ctx.guild.roles, id=exists) em.add_field(name="Current role:", value=rol.mention) await ctx.send(embed=em) Edit: From my comment below: Try changing the names of the subcommands to _enabled and _disabled and pass name="enabled" and name="disabled" to the command decorators. This is a guess, but sometimes names that the Bot class uses internally don't work properly when used as command names.

http://stackoverflow.com/q/52607992
downvote count: 0
favorite count: 0
has title: How to get a balance panel from an unbalanced one?
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has body: I have an unbalanced panel data, in which data of countries covers different time range. For example, the value of country A is from 1996 to 2001, value of country B is from 2000 to 2006, the value of country C is from 1996 to 2006. I would like to select the data of the countries whose data is from 1996 to 2006, which is to drop data from country A and country B. So if the time range of data of a country is a subset of 1996~2006, then this country should be dropped, while those whose time range equals or is larger than 1996~2006 should be kept, and the final result should be a balanced panel. I`d like to use python 3.6 (especially pandas) to solve this. The original data structure is as follows:
has comment: http://stackoverflow.com/comment/92155441
tagged with: dataframe
tagged with: pandas

http://stackoverflow.com/comment/92201997
has text: @today:Hmm..Do you mean I must use this? `ensemble_model.predict([X_val, X_val])`.So, for each model, give the array?I didn't know that.But, it works!You just have to alter X_val in order to have 3 channels!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52634226
score: 0

http://stackoverflow.com/q/52729483
has answer: http://stackoverflow.com/a/52729870
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: I'm reading a file from the frontend and converting it to JSON consists of uuid and a list of JSON objects: class File(Resource): def post(self): if 'file' not in request.files: return {"message": "No File in the request!"}, 400 file = request.files['file'] if file.filename == '': return {'message': "No File selected!"}, 400 if file: filename = secure_filename(file.filename) #file_contents = file.read() print(file) converted_json = File.csv2json(file) new_request = { 'uuid': str(uuid.uuid4()), 'devices': converted_json } print(new_request) return new_request, 201 @classmethod def csv_to_json(cls, data): df = pd.read_csv(data, header=None) df.columns = ['name', 'username', 'password', 'domain'] print(df) df = df.to_json(orient='records') print(df) return df Output is double encoded: { "uuid": "1a09ad79-dc78-4759-9aa0-f1dda9c08dc4", "details": "[{\"name\":\"joe\",\"username\":\"admin\",\"password\":\"admin\",\"domain\":\"abc.xyz.com\"}]" } How to get JSON Object output like (with newline at the end of each ','): { "uuid": "1a09ad79-dc78-4759-9aa0-f1dda9c08dc4", "details": [ {"name": "joe", "username": "admin", "password": "admin", "domain"" "abc.xyz.com"} ] }
tagged with: flask-restful
type: Question
has title: Flask Restful: Converting CSV file to JSON Object
tagged with: flask
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/92391762
type: Comment
has text: Yes, you should use the tensorflow keras API, not keras itself. I will give an answer with another example below.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52730645

http://stackoverflow.com/a/52709960
has body: After some documentation reading I have found out no clear solution. Here is a pull-request I have proposed the development team to create a "get_native_connection()" method: https://github.com/PyMySQL/mysqlclient-python/pull/269
answers question: http://stackoverflow.com/q/52687294
score: 0
type: Answer

http://stackoverflow.com/comment/92319939
type: Comment
type: QuestionComment
has text: What have you tried so far?
comment on: http://stackoverflow.com/q/52696757
score: 0

http://stackoverflow.com/comment/92305082
type: Comment
has text: It already runs fine - you should just decide what you want to output: the name of the current user (a.k.a. `i`) or the name of the last user seen (a.k.a. `user.screen_name`).
type: QuestionComment
comment on: http://stackoverflow.com/q/52688864
score: 0

http://stackoverflow.com/a/52618902
has body: You have already parsed a string into a datetime object. This is done by using datetime.datetime.strptime(). To format the object back into a string you can use the same syntax but using method datetime.datetime.strftime(), e.g.: date.strftime('%Y/%m/%d %H:%M') See also documentation. If you want exactly your input string (without leading 0), you can put a hyphen between percentage operator and directive character where necessary, e.g.: date.strftime('%Y/%-m/%-d %-H:%M') This is well explained in: Python strftime - date without leading 0 but it is platform dependent.
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52618757
upvote count: 2

http://stackoverflow.com/q/52674134
answer count: 1
accepted answer: http://stackoverflow.com/a/52674229
has comment: http://stackoverflow.com/comment/92277900
favorite count: 0
tagged with: python
tagged with: filereader
tagged with: text-files
type: AnsweredQuestion
tagged with: return-value
has body: I need to create a progtam that opens a file then reads the values inside the file and then prints out the name with the largest value. The file contains the following info: Juan,27 Joe,16 Mike,29 Roy,10 Now the code I have is as follows: UserFile = input('enter file name') FileOpen = open(User File,'r') for lines in User File: data = line.split(&quot;,&quot;) name = data[0] hrs = data[1] hrs = int(hrs) LHRS = 0 if hrs &gt; LHRS: LHRS = hrs if LHRS == LHRS: print('Person with largest hours is',name) The following prints out: Person with the largest hours is Juan Person with the largest hours is Mike How can I make it so it only prints out the true largest?
type: Question
has answer: http://stackoverflow.com/a/52674229
has title: Finding largest value in a file and printing out value w name
score: 4
upvote count: 4
downvote count: 0

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

http://stackoverflow.com/comment/124426172
type: QuestionComment
comment on: http://stackoverflow.com/q/52593803
score: 6
type: Comment
has text: TypedDict, check [PEP 589](https://www.python.org/dev/peps/pep-0589/)

http://stackoverflow.com/q/52675374
linked to: http://stackoverflow.com/q/51814897
has comment: http://stackoverflow.com/comment/92280586
tagged with: python
answer count: 0
score: 0
type: UnansweredQuestion
has title: How to parellelize a nested for loop in function with multiple arguments
has comment: http://stackoverflow.com/comment/92280251
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/92287404
has comment: http://stackoverflow.com/comment/92280233
has comment: http://stackoverflow.com/comment/92280181
type: Question
has comment: http://stackoverflow.com/comment/92280316
has body: I'm trying to solve the minimum vertex cover problem using the Brute-Force Approach, basically trying every combination of edges of a graph to find the minimum. I have a nested for loop that I want to run parallel Say I have the following code so far: def brute_force_MVC(vertices, edges): bin_input=["000","001","010","011","100","101","110","111"] for case in bin_input: for i, vertex in enumerate(vertices): if case[i]: #do stuff for edge in edges: #do more stuff is there a way to parallelize this? instead of running each case one after the other, could i run them parallel? Would that speed things up?

http://stackoverflow.com/comment/103238730
type: Comment
comment on: http://stackoverflow.com/a/54031084
score: 7
type: AnswerComment
has text: We have now release an Saxon/C extension for Python3: http://www.saxonica.com/saxon-c/index.xml

http://stackoverflow.com/comment/92376807
type: AnswerComment
score: 0
has text: Hi Idlehands , brilliant, thank you so much!!! I wish i could give you more than one upvote because of how well you addressed all of my questions and gave an answer that i (and others i hope) can use for building out own dropdown menus. I didnt know that the lambda would give you that ability. I knew a for loop was required but was not sure how to implement it, but combining it with dictionaries is a perfectly logical and beautiful way of defining it so that all the elements fit together in a DRY way. Thank you!
type: Comment
comment on: http://stackoverflow.com/a/52725646

http://stackoverflow.com/q/52734790
has comment: http://stackoverflow.com/comment/92394575
has comment: http://stackoverflow.com/comment/92394638
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52734915
has comment: http://stackoverflow.com/comment/92394562
has body: ctx['location_ids'] = vals['location_ids'] I have a large function so I will not post it here, but the problem is when vals['location_ids'] have values as integer everything works smooth, but sometimes there are no values in vals['location_ids'] so it is False, and when it is False I get error. ctx['location_ids'] = vals['location_ids'] TypeError: 'bool' object has no attribute '__getitem__' how can I avoid it, maybe add hasattr?
has comment: http://stackoverflow.com/comment/92394508
type: AnsweredQuestion
has title: check when trying to assign Boolean
linked to: http://stackoverflow.com/q/21024913
has comment: http://stackoverflow.com/comment/92394536
has comment: http://stackoverflow.com/comment/92394391
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52734915

http://stackoverflow.com/a/52697077
answers question: http://stackoverflow.com/q/52666760
score: 0
type: Answer
has body: Have you ever looked at BLAS/LAPACK sort of things. This libraries are built for linear algebraic operations in compilers. Try these operations through BLAS/LAPACK. To set it for Python have a look at the following: You can check here Why BLAS matters ? Netlib - BLAS page Netlib - LAPACAK page OpenBLAS

http://stackoverflow.com/a/52792933
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92539873
has body: Your problem is the following : the convert_bin_dec() method calls the write() method of your object when you do this : self.half_pension_days_value = 5 and the write() method calls again the convert_bin_dec() method, so you have recursive calls. To fix this kind of issue, you have to use the @api.depends decorator. Try with this : @api.multi @api.depends('half_pension') def convert_bin_dec(self): for record in self: if record.half_pension: print "Je suis dans la fonction convert" record.half_pension_days_value = 5 Do not forget to remove the self.convert_bin_dec() in the write()and create() methods.
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52606704
answers question: http://stackoverflow.com/q/52606704
type: AcceptedAnswer

http://stackoverflow.com/comment/92253387
has text: @ jezrael I made them from one dataframe with this command: dfs = dict(tuple(timeseries.groupby('appId')))
comment on: http://stackoverflow.com/a/52661186
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52699527
tagged with: pyqt
downvote count: 0
answer count: 1
tagged with: insert
favorite count: 0
tagged with: python
has title: How to insert text at the top of a QTextEdit widget?
tagged with: append
tagged with: qtextedit
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52702009
type: Question
score: 3
has comment: http://stackoverflow.com/comment/92326237
has body: I have a simple QTextEdit form which I am using as a sort of log. Events are written down into the form, so the user can review history events. I am using textEdit.append() to add new lines to the form. However, textEdit.append(), appends the text to the end of the buffer, so the newest events are shown on the bottom. Is there a reasonable way to append to the beginning, so that the newest events are shown on the top?
accepted answer: http://stackoverflow.com/a/52702009

http://stackoverflow.com/comment/92281133
comment on: http://stackoverflow.com/q/52675869
score: 0
type: Comment
type: QuestionComment
has text: @hjpotter92 And I need help with any regular expression that returns the words that starts exactly with "[*" and ends with "]" or "[\" "]" but it may contain any number of words inside "[* ]" or "[\ ]" this pattern

http://stackoverflow.com/a/52714846
score: 1
has body: Apparently you need to click on the zoom button again. Mentioned here: http://matplotlib.1069221.n5.nabble.com/pick-event-after-zooming-panning-stops-working-td43812.html
upvote count: 1
answers question: http://stackoverflow.com/q/52697206
type: Answer
downvote count: 0

http://stackoverflow.com/q/52726889
tagged with: blit
has title: Pygame doesn't blit images onto canvas
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52727872
type: Question
has body: I've made an icon for a gui in a little project I'm working on, and pygame doesn't display it. What am I doing wrong? import pygame black = (0,0,0) toolscanvas = pygame.Surface((700,120)) pygame.init() gameDisplay = pygame.display.set_mode((0,0),pygame.FULLSCREEN) gameDisplay.fill(black) gameDisplay.convert() clock = pygame.time.Clock() class GuiHouse: def __init__(self): self.x = 0 self.y = 20 self.canvas = pygame.Surface((300,300)) self.canvas.set_alpha(128) self.iconed = pygame.image.load("house_icon.png").convert_alpha() self.iconed = pygame.transform.scale(self.iconed, (60, 60)) def display(self): global toolscanvas toolscanvas.fill((0,0,0)) self.canvas.blit(self.iconed, (0, 0)) toolscanvas.blit(self.canvas, (self.x, self.y)) gameDisplay.blit(toolscanvas,(0,0)) guihouse = GuiHouse() while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() guihouse.display() pygame.display.update() clock.tick(120) Real code is a lot longer, let me know if it doesn't work. Here's what the icon should look like
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52727872
favorite count: 0
upvote count: 2
tagged with: python
tagged with: pygame

http://stackoverflow.com/a/52714306
type: Answer
upvote count: 1
score: 1
has body: Your best bet would be to override serializer's to_representation. And return the structure which you want. Something like this: class AttributeSerializer(serializers.ModelSerializer): name = serializers.CharField() code = serializers.CharField() value = serializers.IntegerField() group = serializers.SerializerMethodField() class Meta: model = Attribute fields = ('name', 'code', 'value', 'group') def get_group(self, obj): serializer = GroupSerializer( Group(name=obj.name, code=obj.code), ) return serializer.data def to_representation(self, instance): output = super().to_representation(instance) value = output.pop('value') return {"attribute" : output, 'value' : value}
answers question: http://stackoverflow.com/q/52713631
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52713631

http://stackoverflow.com/q/52683383
type: Question
has answer: http://stackoverflow.com/a/52684632
tagged with: sympy
score: 0
has comment: http://stackoverflow.com/comment/92294864
has title: Converting sympy point object to tuple of coordinates
answer count: 1
has comment: http://stackoverflow.com/comment/92295009
favorite count: 0
has comment: http://stackoverflow.com/comment/92294954
has body: I'm working on a project in which I'm using sympy to (among other things) find the midpoint between two points in a 2D image. Since midpoint gives me a sympy point object, how can I convert this to a simple tuple of the coordinates? EDIT: here's what I have: vertex = Segment(hipL, hipR).midpoint vertex = tuple(vertex) Here's the error I'm getting: TypeError: 'method' object is not iterable EDIT 2: changed to this: vertex = Point(hipL).midpoint(hipR) vertex = tuple(vertex) Seems to be working.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92295002
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/92294939
upvote count: 1

http://stackoverflow.com/a/52599934
answers question: http://stackoverflow.com/q/52599918
has comment: http://stackoverflow.com/comment/92134554
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92134446
has body: For special characters (or in your case, accents) you need to encode with utf-8. Do this with: open("save.txt", 'w+', encoding='utf-8').write("C:\Müzikler")
type: Answer
has comment: http://stackoverflow.com/comment/92134483
accepted answer of: http://stackoverflow.com/q/52599918
downvote count: 0
score: 1

http://stackoverflow.com/q/52658117
favorite count: 0
tagged with: python
tagged with: excel
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Is there a way to sum all the values in a row in excel with the same key value using Pandas Python?
has body: I need to compare two Excel and sum all the actual values that have the same key value. example sheet. sheet 1 | sheet 2 index id count | index id name 1 a 12 | 1 a qg1 2 b 15 | 2 c ff2 3 c 21 | 3 f dv1 4 b 5 | 4 b bm5 . . . . In above case, I refer to sheet2 and sum the actual value(count) of the values with the same ID in sheet1.(id a | 100, id b |20 ...) The code below takes too long because each ID is indexed. import pandas as pd import csv pcode_quantity = pd.read_csv('/1.csv',delimiter=',') product_info = pd.read_csv('/2.csv' , delimiter=',') product_list = product_info.id.tolist() purchase_id = pcode_quantity.id.tolist() purchase_count = pcode_quantity['count'].tolist() product_sum = 0 i =0 i2 = 0 product_lenth =len(product_list) purchase_lenth = len(purchase_id) dict_pcode = {} while product_lenth &gt; i: while purchase_lenth &gt; i2: if product_list[i] == purchase_id[i2]: product_sum = product_sum + purchase_count[i2] i2=i2+1 dict_pcode[product_list[i]]=product_sum product_sum = 0 i2= 0 i= i+1 sum_pcode = pd.DataFrame(list(dict_pcode.items())) sum_pcode.to_csv('/output.csv') Is there any code that can speed up the above operations?
type: Question
has answer: http://stackoverflow.com/a/52660012
downvote count: 0
accepted answer: http://stackoverflow.com/a/52660012
linked to: http://stackoverflow.com/q/42947303
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/92133481
type: Comment
comment on: http://stackoverflow.com/q/52591066
score: 0
has text: can you show how you're getting truncated tweets? with `tweet_mode='extended'`, checking through some of the tweets in `alltweets` all seem to have `'truncated': False`, and a tweet.`full_text` appears to have the full tweet content, not truncated. even the content of `outtweets[0][2]` matches the full text of `alltweets[0].full_text` more information or examples of the results you are getting would help.
type: QuestionComment

http://stackoverflow.com/a/52693580
type: Answer
has body: I'm not sure that dask dataframe is the best choice for your application. You might want to look at the delayed, futures, or bag APIs. I would probably use concurrent.futures from dask.distributed import Client, as_completed futures = client.map(process, requests) for future in as_completed(futures): try: response = future.result() # do stuff with result except Exeption: # do stuff http://docs.dask.org/en/latest/futures.html
has comment: http://stackoverflow.com/comment/100494478
score: 0
answers question: http://stackoverflow.com/q/52598880
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/100515341
accepted answer of: http://stackoverflow.com/q/52598880

http://stackoverflow.com/comment/92251488
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52659981
has text: no i mean `djongo`, install it. https://code.djangoproject.com/wiki/NoSqlSupport If it fixes your problem let me know, I will add answer.

http://stackoverflow.com/q/52620995
tagged with: function
downvote count: 0
has comment: http://stackoverflow.com/comment/92175859
has body: I have a method object with assigned value from user's input inside a class. The problem is i can't use the method object maxcount_inventory = int(input("How many Inventories: ")) outside the class. The error says "method' object cannot be interpreted as an integer" class CLASS_INVENTORY: maxcount_inventory = int(input("How many Inventories: ")) inventory_name = [] def __init__(Function_Inventory): for count_inventory in range(Function_Inventory.maxcount_inventory): add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1))) Function_Inventory.inventory_name.append(add_inventory) def Return_Inventory(Function_Inventory): return Function_Inventory.inventory_name def Return_Maxcount(Function_Inventory): return maxcount_inventory maxcount_inventory = CLASS_INVENTORY().Return_Maxcount Another extra question if I may, how can i access items in the list per index outside the class? I have the code below, but I think it's not working. Haven't found out yet due to my error above. for count_inventory in range(maxcount_inventory): class_inv = CLASS_INVENTORY().Return_Inventory[count_inventory] print(class_inv) skip() Here is my full code: https://pastebin.com/crnayXYy
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92175886
possible better answer: http://stackoverflow.com/a/52621183
has comment: http://stackoverflow.com/comment/92175908
tagged with: python
has comment: http://stackoverflow.com/comment/92176043
tagged with: list
has comment: http://stackoverflow.com/comment/92175831
has comment: http://stackoverflow.com/comment/92176092
has answer: http://stackoverflow.com/a/52621183
type: AnsweredQuestion
score: 1
has title: How to use a method object (which is in the class) outside the class?
has comment: http://stackoverflow.com/comment/92176006
has comment: http://stackoverflow.com/comment/92175936
has answer: http://stackoverflow.com/a/52621185
tagged with: class
type: Question
accepted answer: http://stackoverflow.com/a/52621185
answer count: 2
has comment: http://stackoverflow.com/comment/92175926
upvote count: 1

http://stackoverflow.com/comment/92284720
has text: yes exactly. What the anaconda prompt is, is a normal cmd where aanconda has beend added to the PATH so the commands can be used directly
type: AnswerComment
comment on: http://stackoverflow.com/a/52664684
type: Comment
score: 1

http://stackoverflow.com/a/52740927
has body: Lists are inefficient for lookups. You should use a dict of sets instead to index every word with each letter in the word, so that you can simply use set intersection to find the words that contain all of the given letters: from functools import reduce d = {} with open('C:\\english-dict2.txt') as f: for l in f: w = l.strip() for c in set(w): d.setdefault(c, set()).add(w) letters = input("Please enter your letters: ") print(reduce(lambda a, b: a &amp; d[b], letters[1:], d[letters[0]])) For example, given a dictionary of the following words: apple book cat dog elephant The index dictionary d would become: {'p': {'elephant', 'apple'}, 'a': {'cat', 'elephant', 'apple'}, 'l': {'elephant', 'apple'}, 'e': {'elephant', 'apple'}, 'k': {'book'}, 'b': {'book'}, 'o': {'book', 'dog'}, 'c': {'cat'}, 't': {'cat', 'elephant'}, 'd': {'dog'}, 'g': {'dog'}, 'h': {'elephant'}, 'n': {'elephant'}} Here's a sample input/output of the above code, where both the words apple and elephant are found to contain both of the letters a and e: Please enter your letters: ae {'apple', 'elephant'} From here you can easily filter the resulting set based on a given minimum number of letters if you want.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52740498
answers question: http://stackoverflow.com/q/52740498
has comment: http://stackoverflow.com/comment/92445786
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/92380007
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52726134
has text: Exactly! There are multiple ways to achieve this but the one I showed you is a popular method used a lot nowadays ;)
type: AnswerComment

http://stackoverflow.com/comment/92311093
has text: Okay, that's it, done editing. Notice the spectra at the bottom, they look pretty good to me.
comment on: http://stackoverflow.com/q/52690632
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52644046
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/92220514
type: Question
type: AnsweredQuestion
has body: I have a list of tuples: x = [('abc', (7, 1, 8, 41), None), ('efg', (12, 2, 13, 42), None)] element = (13, 2, 14, 78) I need to fetch the tuple that has the tuple which is nearest to the 'element'. i.e I need to get the answer as ('efg', (12, 2, 13, 42), None) for element = (13,2,14,78) How can I do this in python?
answer count: 2
has answer: http://stackoverflow.com/a/52644406
has title: How to get the tuple which contains nearest tuple to a given tuple
possible better answer: http://stackoverflow.com/a/52645960
has answer: http://stackoverflow.com/a/52645960
tagged with: python
accepted answer: http://stackoverflow.com/a/52644406

http://stackoverflow.com/q/52681762
upvote count: 3
has answer: http://stackoverflow.com/a/52681925
answer count: 3
has title: How to check whether all elements of array are in between two values
tagged with: arrays
favorite count: 0
has body: I have 2 arrays with different values and an if statement that returns True or False depending on the values in the arrays. Code: avgs = rotation / speed if (avgs.all() &lt;= 55.2 and avgs.all() &gt;= 55): #if all avgs between 55 and 55.2 return false return False elif (avgs.any() &gt;55.2 or avgs.any() &lt; 55): #if any avgs above 55.2 or below 55 return true return True The arrays: [55. 55. 55. 55. 55.] and [95. 55. 55. 55. 55.] The output I get is True for both, when the first array should return False since all the values are between 55 and 55.2. Any ideas why this is? I'm thinking it has something to do with the statement comparing both arrays and returning same value for both.
possible better answer: http://stackoverflow.com/a/52682005
has answer: http://stackoverflow.com/a/52682005
tagged with: python
linked to: http://stackoverflow.com/q/10542240
type: AnsweredQuestion
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52682100
duplicate of: http://stackoverflow.com/q/10542240
accepted answer: http://stackoverflow.com/a/52682100
type: Question
tagged with: numpy

http://stackoverflow.com/comment/92288482
comment on: http://stackoverflow.com/a/52676178
score: 0
type: AnswerComment
type: Comment
has text: Ahh I see now. Thanks!

http://stackoverflow.com/comment/92193116
has text: I intentionally put in some outliers... Am I breaking something because my sample isn't really normally distributed?
score: 0
comment on: http://stackoverflow.com/q/52629524
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/123147463
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52636309
score: 0
has text: Does this answer your question? [Can't get argparse to read quoted string with dashes in it?](https://stackoverflow.com/questions/16174992/cant-get-argparse-to-read-quoted-string-with-dashes-in-it)

http://stackoverflow.com/comment/92442486
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52745782
has text: please see **Update and Update 2**.

http://stackoverflow.com/q/52743613
type: Question
has answer: http://stackoverflow.com/a/52807228
has body: I'm using tf.data to iterate batch from large text corpus. I want to apply a function to only subset of data(or to subset of batch), not one by one element. Specifically, my data iterator yields query, reply with batch. They are all positive pairs, so I just want to shuffle only subset of next batch(in this case, only "reply" batch") to generate random negatives. For example, inputs: query1 reply1 query2 reply2 query3 reply3 ... outputs: positive pairs: query1 reply1 (same as inputs) negative pairs: query1 replyN (replies are random shuffled) Of course it is possible to just shuffle text using python, but I want to make it efficient using tf.data because data size is too big.
upvote count: 1
answer count: 1
downvote count: 0
tagged with: tensorflow-datasets
favorite count: 0
has title: Tensorflow data : apply function TO batch
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52807228
tagged with: tensorflow

http://stackoverflow.com/comment/92237295
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52652503
type: Comment
has text: no, you should call your python script from the command line, output the values in your dict to stdout and pipe them into the bash script

http://stackoverflow.com/comment/92297763
type: Comment
score: 1
has text: Please try to provide a reproducible example, starting with a data generating process. Also...why are you converting it?
comment on: http://stackoverflow.com/q/52684816
type: QuestionComment

http://stackoverflow.com/q/52746119
tagged with: graphene-python
has title: Using DjangoFilterConnectionField with custom Connection in graphene_django
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52746690
score: 3
tagged with: python
upvote count: 3
tagged with: graphql
tagged with: django
type: Question
type: AnsweredQuestion
has body: I'm trying to use something similar to this: class User(DjangoObjectType): class Meta: model = auth_models.User filter_fields = ('email', ) interfaces = (Node, ) connection = UserConnection class UserConnection(Connection): extra = graphene.String() class Meta: node = User class Query(graphene.ObjectType): users_connection = DjangoFilterConnectionField( User, where=UserWhereInput() ) From my understanding, User node needs to be passed UserConnection on it's meta, and UserConnection needs to be passed User on it's meta. However, it creates a cross reference. Any help?
has answer: http://stackoverflow.com/a/52746690

http://stackoverflow.com/q/52745171
has body: How to rewrite the following example in order to properly use @property? class Config: def __init__(self, config_folder="", config_file="config.json"): self.set_config(config_folder, config_file) def get_config(self): with open(self.config) as f: return json.load(f) def set_config(self, config_folder, config_file): self.BASE_DIR = pathlib.Path(__file__).parent self.config = self.BASE_DIR / config_folder / config_file
type: Question
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52745265
has answer: http://stackoverflow.com/a/52745245
has answer: http://stackoverflow.com/a/52745265
has title: How to use @property properly
tagged with: python
tagged with: properties
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52745245

http://stackoverflow.com/a/62688095
answers question: http://stackoverflow.com/q/52702911
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52702911
has body: pexpect Example for fdisk that has interaction: def expectpart(): TMPLOG = "/tmp/pexpect.log" cmd = f''' sudo fdisk /dev/sdb ;\ echo "alldone" ; ''' with open(TMPLOG, "w") as log: ch = pexpect.spawn(f"/bin/bash -c \"{cmd}\"", encoding='utf-8', logfile=log) ch.expect("Command") ch.send("c\r") ch.expect("DOS Compat") ch.send("n\r") ch.expect("Partition type") ch.send("p\r") ch.expect("Partition number") ch.send("1\r") ch.expect("First sector") ch.send("\r") ch.expect("Last sector") ch.send("\r") ch.expect("Created a new partition") ch.send("w\r") ch.expect("alldone") i = ch.expect([pexpect.EOF], timeout=5) ch.close()
score: 1

http://stackoverflow.com/q/52686490
tagged with: python
has comment: http://stackoverflow.com/comment/92302568
answer count: 0
tagged with: xlsxwriter
tagged with: floating-point
has title: Importing excel file into a dataframe, causing change in values
type: Question
has comment: http://stackoverflow.com/comment/92302955
has body: I am reading an excel file into pandas data frame. The problem I am facing is when I import the file, a value of 0.021893287 becomes 3.7218587899996434e-05 in the data frame. And a value of 0.055100 becomes 0.05510000000000001 in the data frame. Also, I have to do the data calculations in the data frame and then write the data frame into an excel. After the calculation, I have to truncate the values upto 8 decimal points. For now, I am converting all the numeric columns to string format and then slicing the string. However, I am still facing issues when I see the results, as some of the results are still getting converted to Exponential format. Example 1 : Result 1 : Example 2 : Result 2 : Note: Fund name and CUSIP in Excel sheet picture had been edited earlier. Please ignore it.
has comment: http://stackoverflow.com/comment/92302938
score: 0
tagged with: pandas
tagged with: truncate
type: UnansweredQuestion

http://stackoverflow.com/comment/92373928
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52724255
type: QuestionComment
has text: you probably have >= 2 different python versions installed

http://stackoverflow.com/comment/92331841
score: 0
type: Comment
type: QuestionComment
has text: https://www.pythoncentral.io/pyside-pyqt-tutorial-the-qlistwidget/
comment on: http://stackoverflow.com/q/52702116

http://stackoverflow.com/comment/92112932
comment on: http://stackoverflow.com/q/52589054
score: 0
type: Comment
type: QuestionComment
has text: It happened with me that when working from terminal, the plot appeared but went behind the terminal. I minimized my terminal and all other windows and found the plot on the screen. Minimize the terminal and other open windows/browsers/etc. and see if it's there

http://stackoverflow.com/q/52699990
linked to: http://stackoverflow.com/q/1052148
has comment: http://stackoverflow.com/comment/92327075
type: UnansweredQuestion
tagged with: postgresql
linked to: http://stackoverflow.com/q/2113448
type: Question
has comment: http://stackoverflow.com/comment/92326526
has body: I have following simple table, ID DateTime Category -- -------- ---------- 1 2018-05-12 5:05 1 2 2018-05-12 5:10 1 3 2018-05-12 6:25 2 4 2018-05-13 7:40 1 5 2018-05-14 8:50 4 I want to count the number of entries per day for each category, so result should be like, Day Category Count --------- -------- ------- 2018-05-12 1 2 2018-05-12 2 1 2018-05-13 1 1 2018-05-14 4 1 How can i do this in sqlalchmey? Edit: Database I'm using is PostgreSQL Edit: Columns and their specific types are as following, ID - Integer, Category - Integer, DateTime - DateTime
has answer: http://stackoverflow.com/a/62036469
has comment: http://stackoverflow.com/comment/92326492
score: 0
answer count: 3
tagged with: python
linked to: http://stackoverflow.com/q/36024712
has comment: http://stackoverflow.com/comment/92326806
tagged with: sqlalchemy
has title: How to get row count per day in sqlalchemy?
has answer: http://stackoverflow.com/a/62040785
has answer: http://stackoverflow.com/a/52700673

http://stackoverflow.com/comment/92128172
type: Comment
comment on: http://stackoverflow.com/a/52595239
has text: If you're willing to live dangerously: `df['cable_block'].astype(int, errors='ignore').astype(str, , errors='ignore') + '/' + df['pair'].astype(int, , errors='ignore').astype(str, , errors='ignore')`
score: 0
type: AnswerComment

python-2.7
tags question: http://stackoverflow.com/q/52620224
tags question: http://stackoverflow.com/q/52672317
tags question: http://stackoverflow.com/q/52601383
tags question: http://stackoverflow.com/q/52714467
tags question: http://stackoverflow.com/q/52599673
tags question: http://stackoverflow.com/q/52650690
tags question: http://stackoverflow.com/q/52651506
tags question: http://stackoverflow.com/q/52722554
tags question: http://stackoverflow.com/q/52592774
tags question: http://stackoverflow.com/q/52620378
tags question: http://stackoverflow.com/q/52746654
tags question: http://stackoverflow.com/q/52609750
tags question: http://stackoverflow.com/q/52597327
tags question: http://stackoverflow.com/q/52636330
tags question: http://stackoverflow.com/q/52642240
tags question: http://stackoverflow.com/q/52668335
tags question: http://stackoverflow.com/q/52697524
tags question: http://stackoverflow.com/q/52740729
tags question: http://stackoverflow.com/q/52739323
tags question: http://stackoverflow.com/q/52693738
tags question: http://stackoverflow.com/q/52741688
tags question: http://stackoverflow.com/q/52705066
tags question: http://stackoverflow.com/q/52600897
tags question: http://stackoverflow.com/q/52636685
tags question: http://stackoverflow.com/q/52731407
tags question: http://stackoverflow.com/q/52633151
tags question: http://stackoverflow.com/q/52706997
tags question: http://stackoverflow.com/q/52640677
tags question: http://stackoverflow.com/q/52723103
tags question: http://stackoverflow.com/q/52606733
tags question: http://stackoverflow.com/q/52744393
tags question: http://stackoverflow.com/q/52671111
tags question: http://stackoverflow.com/q/52683888
tags question: http://stackoverflow.com/q/52719515
tags question: http://stackoverflow.com/q/52727032
tags question: http://stackoverflow.com/q/52708311
tags question: http://stackoverflow.com/q/52608995
tags question: http://stackoverflow.com/q/52737595
tags question: http://stackoverflow.com/q/52699494
tags question: http://stackoverflow.com/q/52741369
tags question: http://stackoverflow.com/q/52598998
tags question: http://stackoverflow.com/q/52603939
tags question: http://stackoverflow.com/q/52607540
tags question: http://stackoverflow.com/q/52656300
tags question: http://stackoverflow.com/q/52697433
tags question: http://stackoverflow.com/q/52683832
tags question: http://stackoverflow.com/q/52698283
tags question: http://stackoverflow.com/q/52736897
tags question: http://stackoverflow.com/q/52702526
tags question: http://stackoverflow.com/q/52645182
tags question: http://stackoverflow.com/q/52689144
tags question: http://stackoverflow.com/q/52684987
tags question: http://stackoverflow.com/q/52717176
tags question: http://stackoverflow.com/q/52716806
tags question: http://stackoverflow.com/q/52724530
tags question: http://stackoverflow.com/q/52641341
tags question: http://stackoverflow.com/q/52706232
tags question: http://stackoverflow.com/q/52705957
tags question: http://stackoverflow.com/q/52740831
tags question: http://stackoverflow.com/q/52714982
tags question: http://stackoverflow.com/q/52687616
tags question: http://stackoverflow.com/q/52594207
tags question: http://stackoverflow.com/q/52696176
tags question: http://stackoverflow.com/q/52651918
tags question: http://stackoverflow.com/q/52645858
tags question: http://stackoverflow.com/q/52625796
tags question: http://stackoverflow.com/q/52629106
tags question: http://stackoverflow.com/q/52714444
tags question: http://stackoverflow.com/q/52601725
tags question: http://stackoverflow.com/q/52719207
tags question: http://stackoverflow.com/q/52647485
tags question: http://stackoverflow.com/q/52741845
tags question: http://stackoverflow.com/q/52716189
tags question: http://stackoverflow.com/q/52611875
tags question: http://stackoverflow.com/q/52641587
tags question: http://stackoverflow.com/q/52633503
tags question: http://stackoverflow.com/q/52649213
type: Tag
tags question: http://stackoverflow.com/q/52720961
tags question: http://stackoverflow.com/q/52743695

http://stackoverflow.com/comment/92411605
has text: @CapnJack Yeah, the network drive is mapped on my computer and I have access to it.
comment on: http://stackoverflow.com/q/52743426
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92164879
type: Comment
type: QuestionComment
has text: Do you want me to post this solution?
comment on: http://stackoverflow.com/q/52599978
score: 0

http://stackoverflow.com/comment/92383489
type: QuestionComment
has text: I'm thinking of just closing this as a duplicate of [Type hints: solve circular dependency](//stackoverflow.com/q/33837918), because this is just another type hint circular dependency problem.
score: 0
comment on: http://stackoverflow.com/q/52676647
type: Comment

http://stackoverflow.com/q/52592663
answer count: 2
tagged with: pyqt
downvote count: 0
has title: Unicode Characters in QT Designer for Python?
favorite count: 0
tagged with: qt-designer
possible better answer: http://stackoverflow.com/a/76851622
accepted answer: http://stackoverflow.com/a/52592923
has body: I am writing a gui for an executable. My first one was written using Python and TKinter. It worked. Now I am working on version 2, and I want to do it in QT4. I found the Qt Designer which is really helpful for creating the layout etc. I created a QLabel, and in there I want it to display a greek Gamma Symbol. But how? I did not find any way to do this. There is a button I can press and there appears to be an option to write "source code". But what does it accept? I tried different methods: u"\u03B3" &amp;gamma; and a couple more. If I write the &amp;, the text changes its color to red, in the source code editor. But it will still just display the text I typed in. Is this at all possible, or I just write some placeholder and then change it to Gamma in the python code itself? Thx.
score: 2
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52592923
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76851622
type: Question

http://stackoverflow.com/a/52593493
upvote count: 9
has comment: http://stackoverflow.com/comment/92122135
type: Answer
has comment: http://stackoverflow.com/comment/92121945
downvote count: 0
has comment: http://stackoverflow.com/comment/92121790
answers question: http://stackoverflow.com/q/52593420
score: 9
has body: You can use os.path.abspath() to convert it: print(os.path.abspath("P:\python\t\temp.txt")) >>> P:/python/t/temp.txt See the documentation of os.path here.

http://stackoverflow.com/comment/92239843
type: AnswerComment
has text: @Mateo I don't see how the description I give is different than that. The import is not "skipped" it *succeeds* because the module object is created immediately and immediately inserted into `sys.modules`. When I say `import one` returns immediately I mean that it returns the value it finds in `sys.modules` without re-executing `one.py` (and ending up in an infinite loop)
type: Comment
comment on: http://stackoverflow.com/a/52654050
score: 0

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

http://stackoverflow.com/q/52626780
type: AnsweredQuestion
upvote count: 0
has title: Python best way to unflat json?
tagged with: http://stackoverflow.com/tag/json
has body: I have a function that makes JSON flat: def flat_json(z, sep): val = {} for i in z.keys(): if isinstance(z[i], dict): get = flat_json(z[i], sep) for j in get.keys(): val[i + sep + j] = get[j] else: val[i] = z[i] return val flat_json({"a": "b", "c": {"d": "g"}}, '__') # returns {'a': 'b', 'c__d': 'g'} But I have not yet figured out how to convert the flat JSON back
downvote count: 3
type: Question
linked to: http://stackoverflow.com/q/23011146
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52626861
accepted answer: http://stackoverflow.com/a/52626861
has comment: http://stackoverflow.com/comment/92187163
score: -3
tagged with: python

http://stackoverflow.com/q/52738709
has answer: http://stackoverflow.com/a/52739724
tagged with: jupyter
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/41351041
tagged with: python
upvote count: 7
score: 7
type: Question
has comment: http://stackoverflow.com/comment/121228937
linked to: http://stackoverflow.com/q/41351041
answer count: 2
downvote count: 0
has title: How to store %%time values in a variable in Jupyter?
has answer: http://stackoverflow.com/a/52738866
has body: I would like to know the CPU time of a cell working in Jupyter. I put %%time at the top of the cell. It prints out Wall time. But I couldn't store this time value in a variable? Could you please help me on that? Thanks.
has comment: http://stackoverflow.com/comment/92402044
favorite count: 0

http://stackoverflow.com/comment/92211043
score: 0
type: Comment
type: QuestionComment
has text: in search endpoint? i already use `['venues']`
comment on: http://stackoverflow.com/q/52631035

http://stackoverflow.com/a/52596105
has comment: http://stackoverflow.com/comment/92132985
upvote count: 5
has comment: http://stackoverflow.com/comment/92149671
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92127105
downvote count: 0
has body: f(lambda x: x+1, g) ultimately returns another function. That function is then called with 4 as its argument to produce the final result of 5. Let h = lambda x: x + 1, because this becomes a mess to trace otherwise. First, we apply f to h and g. f(h, g)(4) == (lambda x,y: y(y(x))(h, g)(4) == g(g(h))(4) Next, we'll evaluate the inner call to g: g(g(h))(4) == g((lambda x: lambda y: x(y))(h))(4) == g(lambda y: h(y))(4) == g(h)(4) The last step is an example of eta reduction, to use a term from lambda calculus: a function that applies a second function to an argument is equivalent to the second function itself. Finally, we evaluate g(h) again the same way, which finally gets us to an expression that doesn't involve passing a function as an argument, and lets us get a final answer. g(h)(4) == (lambda y: h(y))(4) == h(4) == (lambda x: x + 1)(4) == 4 + 1 == 5
has comment: http://stackoverflow.com/comment/92127218
has comment: http://stackoverflow.com/comment/92127301
accepted answer of: http://stackoverflow.com/q/52595975
type: Answer
has comment: http://stackoverflow.com/comment/92126919
has comment: http://stackoverflow.com/comment/92127603
answers question: http://stackoverflow.com/q/52595975
score: 5

http://stackoverflow.com/a/52725929
answers question: http://stackoverflow.com/q/52725743
has body: Two changes in above code. 1. First mult variable should be =1 2. if mult == 1 this condition will not change your value, after first multiplication condition will never satisfied if first value is not 1 Modification in above &gt;&gt;&gt; def answer(l): ... mult = 1 .. for i in l: ... if i != 0: ... mult *= i ... return mult ... &gt;&gt;&gt; print (answer([3,4,5]))
score: 0
type: Answer

http://stackoverflow.com/comment/92158364
type: AnswerComment
comment on: http://stackoverflow.com/a/52611472
type: Comment
has text: And what exactly are their difference? Also you seem to know very well and i want to ask you if you can help me with this question too: https://stackoverflow.com/questions/52593499/form-a-url-link-with-utf-8-encoding
score: 0

http://stackoverflow.com/a/52705349
accepted answer of: http://stackoverflow.com/q/52704840
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52704840
type: Answer
has comment: http://stackoverflow.com/comment/92341234
score: 5
has body: You can concatenate the dataframes, and then groupby the column names to apply an operation on the similarly named columns: In this case you can get away with taking the sum and then typecasting back to bool to get the or operation. import pandas as pd df = pd.concat([left, right], 1) df.groupby(df.columns, 1).sum().astype(bool) Output: 0.0 0.5 0.7 12.5 True True True 14.0 True True False 15.5 False True False If you need to see how to do this in a less case-specific manner, then again just group by the columns and apply something to the grouped object over axis=1 df = pd.concat([left, right], 1) df.groupby(df.columns, 1).apply(lambda x: x.any(1)) # 0.0 0.5 0.7 #12.5 True True True #14.0 True True False #15.5 False True False Further, you can define a custom combining function. Here's one which adds twice the left Frame to 4 times the right Frame. If there is only one column, it returns 2x the left frame. Sample Data left: 0.0 0.5 12.5 1 11 14.0 2 17 15.5 3 17 right: 0.7 0.5 12.5 4 2 14.0 4 -1 15.5 5 5 Code def my_func(x): try: res = x.iloc[:, 0]*2 + x.iloc[:, 1]*4 except IndexError: res = x.iloc[:, 0]*2 return res df = pd.concat([left, right], 1) df.groupby(df.columns, 1).apply(lambda x: my_func(x)) Output: 0.0 0.5 0.7 12.5 2 30 8 14.0 4 30 8 15.5 6 54 10 Finally, if you wanted to do this in a consecutive manner, then you should make use of reduce. Here I'll combine 5 DataFrames with the above function. (I'll just repeat the right Frame 4x for the example) from functools import reduce def my_comb(df_l, df_r, func): """ Concatenate df_l and df_r along axis=1. Apply the specified function. """ df = pd.concat([df_l, df_r], 1) return df.groupby(df.columns, 1).apply(lambda x: func(x)) reduce(lambda dfl, dfr: my_comb(dfl, dfr, func=my_func), [left, right, right, right, right]) # 0.0 0.5 0.7 #12.5 16 296 176 #14.0 32 212 176 #15.5 48 572 220
has comment: http://stackoverflow.com/comment/92337982
upvote count: 5
has comment: http://stackoverflow.com/comment/92360903

http://stackoverflow.com/q/52588867
upvote count: 1
has comment: http://stackoverflow.com/comment/92112703
has body: I'm trying to produce a million results of 3 bias coin flips - random.randint allows me to specify the number of flips but random.choice seems to only let me specify the size. What's I'm trying to get is: million results of 3 flips each with 60% chance of heads on a coin.
type: Question
has comment: http://stackoverflow.com/comment/92112746
has title: np.random.choice - can't specify number of coin flips
score: -1
tagged with: numpy
has answer: http://stackoverflow.com/a/52589055
tagged with: random
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92112651
tagged with: python
accepted answer: http://stackoverflow.com/a/52589055
type: AnsweredQuestion
downvote count: 2

http://stackoverflow.com/comment/92112828
has text: Thats nice, would you post the answer or it's not worth it?
comment on: http://stackoverflow.com/q/52588968
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52652945
has answer: http://stackoverflow.com/a/52653013
favorite count: 0
has answer: http://stackoverflow.com/a/52652990
score: 0
has comment: http://stackoverflow.com/comment/92237519
tagged with: python
tagged with: regex
answer count: 4
accepted answer: http://stackoverflow.com/a/52653013
upvote count: 1
has title: Get a string after a special character Python RegEx
has body: How can i get a string after a special character? For example I want to get the string after / in my_string = "Python/RegEx" Output to be : RegEx I tried : h = [] a = [ 'Python1/RegEx1' , 'Python2/RegEx2', 'Python3/RegEx3'] for i in a: h.append(re.findall(r'/(\w+)', i)) print(h) But the output is : [['RegEx1'], ['RegEx2'], ['RegEx3']] I need : ['RegEx1', 'RegEx2', 'RegEx3'] Thanks in advance RegEx beginner
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52653028
has comment: http://stackoverflow.com/comment/92237643
linked to: http://stackoverflow.com/q/252703
has comment: http://stackoverflow.com/comment/92237887
possible better answer: http://stackoverflow.com/a/52652980
has comment: http://stackoverflow.com/comment/92237549
has answer: http://stackoverflow.com/a/52652980
duplicate of: http://stackoverflow.com/q/252703

http://stackoverflow.com/q/52661069
has title: How add "." before each letter in string
answer count: 3
upvote count: 0
accepted answer: http://stackoverflow.com/a/52661260
favorite count: 0
has comment: http://stackoverflow.com/comment/92252298
has answer: http://stackoverflow.com/a/52661472
has body: as title says i simply need to add a . before each letter in my string while having vowels removed and making it lowercase i got it working just cant add the .s there here is my code s = str(input()) vowels = ('a','e','o','u','i','A','E','O','U','I') for letter in s: if letter in vowels: s = s.replace(letter,'').replace() print(s)
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/92252377
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52661150
downvote count: 1
linked to: http://stackoverflow.com/q/21554740
has answer: http://stackoverflow.com/a/52661150
type: Question
has comment: http://stackoverflow.com/comment/92254318
has comment: http://stackoverflow.com/comment/92254269
has answer: http://stackoverflow.com/a/52661260

http://stackoverflow.com/a/52715179
has body: To illustrate how you could refactor your code to use fixtures instead: import pytest @pytest.fixture(name='database_with_tables', scope='module') def _database_with_tables(): try: create_table(tb1) create_table(tb2) yield None # usually we would pass around a database connection / session finally: drop_table(tb1) drop_table(tb2) @pytest.mark.usefixtures("database_with_tables") class TestClass: def test_tc1(self): &lt;tc_content&gt; assert You still need to handle exceptions thrown during table creation. In most cases, you would also want to pass around the database connection to the test method as well, in which case pytest.mark.usefixtures would no longer be necessary. The advantage of fixtures is that it declares what you need for the test, not how. The scope parameter could also be set to session to live longer.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52702526
upvote count: 1
score: 1

http://stackoverflow.com/comment/92344502
has text: You need to convert your label to categorical. You can use the to_categorical method defined in [Keras Utils](https://keras.io/utils/) to do this. Here your num_classes would be 2.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52708821

http://stackoverflow.com/q/52710123
type: Question
has body: I'm trying to use the batch functionality for the Mailchimp API. My current set up is like this operations = [] for idx, row in users_df.iterows(): payload = { 'email': row['email'], 'last_updated': row['new_time'], 'custom_value': row['new_value'] } operation_item = { "method": "POST", # I changed this to PUT "path": '/lists/members/12345', "body": json.dumps(payload), } operations.append(operation_item) client = mc.MailChimp(MAILCHIMP_TOKEN, MAILCHIMP_USER) batch = client.batches.create(data={"operations": operations}) Whenever I use the POST method I get this error: old_user@gmail.com is already a list member. Use PUT to insert or update list members. But whenever I change my method to PUT, I get this other error: The requested method and resource are not compatible. See the Allow header for this resource's available methods. Is there a way to overcome this? I have already looked at this and this is a similar problem in Ruby.
linked to: http://stackoverflow.com/q/50021727
has answer: http://stackoverflow.com/a/55625935
linked to: http://stackoverflow.com/q/42828112
upvote count: 1
answer count: 1
favorite count: 0
has title: Python - Mailchimp Batch PUT requests
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: mailchimp
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/55625935

http://stackoverflow.com/q/52618381
has comment: http://stackoverflow.com/comment/92170948
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92171057
has comment: http://stackoverflow.com/comment/92171282
linked to: http://stackoverflow.com/q/590747
has comment: http://stackoverflow.com/comment/92170914
has comment: http://stackoverflow.com/comment/92170941
accepted answer: http://stackoverflow.com/a/52618422
has comment: http://stackoverflow.com/comment/92171073
has body: I want to find several tags in a webpage using regular expression, they have the same pattern: data-tag-slug="NAME", like this(only a small section): ...category="rating" data-tag-id="40482" data-tag-name="safe" data-tag-slug="safe"&gt;&lt;a cla... ...category="" data-tag-id="42350" data-tag-name="solo" data-tag-slug="solo"&gt;&lt;a cla... And I coded tagName = r'.*data-tag-slug="(\w+)".*', use re.findall(tagName, html), yet I can only get one result, which is the very last item that fits the pattern. I wonder how can I get all of them. P.S. By "the very last item", I mean that there're several tags that fit the pattern, but the code can only get the last one by the order of appearance in the html.
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/92171198
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92171288
has comment: http://stackoverflow.com/comment/92171151
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92170879
has comment: http://stackoverflow.com/comment/92171375
score: -1
has comment: http://stackoverflow.com/comment/92171332
has answer: http://stackoverflow.com/a/52618422
has comment: http://stackoverflow.com/comment/92170959
has title: Regular expression same pattern only applies to 1 result
linked to: http://stackoverflow.com/q/1732348
upvote count: 0

http://stackoverflow.com/a/52730375
answers question: http://stackoverflow.com/q/52730332
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92386015
has body: It looks to me like you have got the selector wrong, Should you be specifying: soup.findAll("span", {"class": "sectionals-time"}) hope that helps

http://stackoverflow.com/comment/92378111
has text: @CodingFR You have to recalculate the rect, because, since the images are now bigger, the coordinates have to change. Call `.get_rect()` on each scaled image. A future improvement would be to call multiple `.scale()` at the beginning of the program and store all the bigger player images in a list. That way you don't repeat the scaling all the time, because it can be costly. Then you can just iterate over the list and do the drawing.
type: AnswerComment
comment on: http://stackoverflow.com/a/52709706
type: Comment
score: 1

http://stackoverflow.com/a/52721966
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52719986
has body: Simply do not use the elif statement and use two if statements since nested ifs seems to execute only one in your case.Try below code: key1 = "00000110" key2 = "00000001" for line in f.readlines(): if line.startswith(key1): print(line.lstrip(key1 + " ")) if line.startswith(key2): print(line.lstrip(key2 + " "))

http://stackoverflow.com/comment/92272308
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52671144
has text: @mad_ Do you think 0/0 is a valid input seeing as we are not accepting a final answer with a leading 0 so there is never a case where 0/0 should be entered, correct?

http://stackoverflow.com/q/52595858
has comment: http://stackoverflow.com/comment/92126590
type: AnsweredQuestion
has title: Horner's rule and direct method in python
has comment: http://stackoverflow.com/comment/92153806
has comment: http://stackoverflow.com/comment/92126524
type: Question
has body: I am trying to solve the following question. I have made codes for implanting the direct method and Horner's rule, which I believe I have done this correctly. However past that I am having some problems figuring out the rest. Looking for some help with this, all help is greatly appreciated! Here is the code I have produced for Horner's rule, which I believe I have done correctly. def poly_horner(A, x): p = A[-1] i = len(A) - 2 while i &gt;= 0: p = p * x + A[i] i -= 1 return p And here is the code I have produced for the direct method: def poly_naive(A, x): p = 0 for i, a in enumerate(A): p += (x ** i) * a return p How can I put this code together and finish the rest?
accepted answer: http://stackoverflow.com/a/52596088
has comment: http://stackoverflow.com/comment/92143263
tagged with: numerical-methods
answer count: 1
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/92153909
downvote count: 2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52596088

nameerror
tags question: http://stackoverflow.com/q/52690131
tags question: http://stackoverflow.com/q/52670792
tag name: nameerror
tags question: http://stackoverflow.com/q/52690904
type: Tag
tags question: http://stackoverflow.com/q/52683773
tags question: http://stackoverflow.com/q/52588975

http://stackoverflow.com/comment/92254867
has text: What is input panel?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52662321
type: Comment

http://stackoverflow.com/comment/92294809
type: QuestionComment
has text: Show the code you have implemented which gives you `["java 6", "python 4"]`
comment on: http://stackoverflow.com/q/52674257
score: 0
type: Comment

http://stackoverflow.com/a/52708124
has comment: http://stackoverflow.com/comment/92374949
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52703513
type: Answer
downvote count: 0
has body: Thanks to a Reddit user, I find out that you have to connect to the dialog's delete-event and make sure to return True to avoid the dialog being destroyed. First create the signal handler in Glade, then in your Python code: def on_dialog_delete_event(self, dialog, event): dialog.hide() return True
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92374350
answers question: http://stackoverflow.com/q/52703513

http://stackoverflow.com/q/52734928
has comment: http://stackoverflow.com/comment/92395844
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92395271
has title: TensorFlow's Print is not printing
has comment: http://stackoverflow.com/comment/92396557
tagged with: keras-rl
has answer: http://stackoverflow.com/a/61124234
has comment: http://stackoverflow.com/comment/92397133
score: 5
answer count: 3
has answer: http://stackoverflow.com/a/52735507
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/92395705
accepted answer: http://stackoverflow.com/a/52735507
tagged with: python
upvote count: 6
possible better answer: http://stackoverflow.com/a/60739248
has comment: http://stackoverflow.com/comment/92396589
has answer: http://stackoverflow.com/a/60739248
has body: I am trying to understand some code from a reinforcement learning algorithm. In order to do that I am trying to print the value of a tensor. I made a simple piece of code to show what I mean. import tensorflow as tf from keras import backend as K x = K.abs(-2.0) tf.Print(x,[x], 'x') The goal is to have the value '2' printed(the absolute value of -2). But I only get back the following: Using TensorFlow backend. Process finished with exit code 0 Nothing, how can I print the value '2' just like a print('...') statement would do?
downvote count: 1
type: Question

http://stackoverflow.com/q/52624391
upvote count: 0
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/52625611
type: Question
has title: How to replace 'b' with 0 or 1 in the binary representation of a string
answer count: 2
has comment: http://stackoverflow.com/comment/92182837
has body: import binascii a = [] a = input('enter the messge') def str2bin(message): binary = bin(int(binascii.hexlify(message.encode("ascii")), 16)) return binary[1:] print(str2bin(a)) Input string : hai Output : b11010000110000101101001 How to remove or replace the 'b' from the output and replace it with another binary digit ?
favorite count: 0
downvote count: 3
has answer: http://stackoverflow.com/a/52624453
tagged with: python
tagged with: binary

http://stackoverflow.com/a/52694804
has comment: http://stackoverflow.com/comment/92316259
has body: You don't actually have a list of dictionaries, but a list of lists of dictionaries, and you're trying to merge the dictionaries within the sub-lists, so you should initialize your defaultdict inside the loop that iterates through the main list: empty = [] for smaller_list in list_of_dictionaries2: correct2 = defaultdict(list) for d in smaller_list: for k,v in d.items(): correct2[k].append(v) empty.append(correct2) empty would become: [defaultdict(&lt;class 'list'&gt;, {0: [3523, 7245], 1: [3524, 7246, 20898], 2: [3540, 7247, 20899], 4: [3541, 20901], 5: [3542, 7249, 20902], 3: [7248, 20900], 6: [7250]}), defaultdict(&lt;class 'list'&gt;, {0: [3], 1: [4], 2: [5], 3: [6]})] Note that your expected output for the second merged defaultdict is incorrect since the value of each key should be a list after merge. Also the list of lists of dictionary should become a list of defaultdicts of lists after the merge, not a list of lists of defaultdicts of lists.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92316276
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52694696
upvote count: 2
has comment: http://stackoverflow.com/comment/92316208
has comment: http://stackoverflow.com/comment/92316290
has comment: http://stackoverflow.com/comment/92316274
accepted answer of: http://stackoverflow.com/q/52694696

http://stackoverflow.com/comment/92388368
comment on: http://stackoverflow.com/a/52730842
type: AnswerComment
score: 0
type: Comment
has text: @MT467 yes it will, thanks to the errors="coerce" arg.

http://stackoverflow.com/comment/106818361
type: Comment
type: QuestionComment
has text: I am facing a similar problem explained here - https://stackoverflow.com/questions/60381483/timeseries-resample-error-none-of-dateindex-in-column-pandas
comment on: http://stackoverflow.com/q/52688583
score: 0

http://stackoverflow.com/comment/92164616
comment on: http://stackoverflow.com/q/52615130
has text: Please do *not* parse XML/HTML with regexes: https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/q/52747035
has body: I'm trying to use a Slack webhook to notify a channel about a csv file for that day as well as post a link to it to attach. https://api.slack.com/docs/message-attachments doesn't use any examples of actual attachments and only includes links. I'm wondering if its even possible to send a csv file that my code is generating and attaching it from its path via os.path.basename(csvfile) I'm trying use the format thats demonstrated here: https://gist.github.com/devStepsize/b1b795309a217d24566dcc0ad136f784 but am not sure if this allows for actual file attachments. So, I'd appreciate any help/direction in this matter. Is it even possible to send file attachments via a Slack webhook and if so, how should one go about doing so?
tagged with: slack-api
has answer: http://stackoverflow.com/a/52747693
has title: Adding a csv attachment to slack webhook in python
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
accepted answer: http://stackoverflow.com/a/52747693
tagged with: python
tagged with: python-requests
type: AnsweredQuestion
tagged with: slack
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/35742775
has comment: http://stackoverflow.com/comment/92421377
answer count: 1
downvote count: 0
score: 4

http://stackoverflow.com/a/52590354
has comment: http://stackoverflow.com/comment/92116151
type: Answer
answers question: http://stackoverflow.com/q/52590331
has comment: http://stackoverflow.com/comment/92115722
score: 0
has body: Use pandas: import pandas as pd dataframe = pd.read_csv("your_data.csv") dataframe.head() # prints out first rows of your data Or from Excel: dataframe = pd.read_excel('your_excel_sheet.xlsx')

http://stackoverflow.com/comment/92321722
comment on: http://stackoverflow.com/a/52697652
type: Comment
has text: @HarryLe: how did you get one cursor to begin with? Or is `c` a connection object?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92221628
comment on: http://stackoverflow.com/q/52644714
score: 0
type: Comment
type: QuestionComment
has text: @AndreMotta maybe `0-9` as well?

http://stackoverflow.com/comment/92405599
has text: @SarthakNegi, yes I do have from wtforms.fields import DateField . I forgot to include that in my code earlier..
type: Comment
comment on: http://stackoverflow.com/q/52739544
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92361118
type: Comment
comment on: http://stackoverflow.com/q/52699212
has text: @Cleb : `from requests import Session` ... `client = Session()` ... `r = client.post(db_url, data=json.dumps(d), headers=headers)`. Then continue later to use this `client` object that will handle the cookies for you. Test it in a iPython REPL for more hints.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92313424
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52692120
has text: @AndrewMcDowell it must have something to do with the site since i `quit` the instance of the webdriver and then create another instance anew... man ive tested much longer scripts on amazon and it seems like theyve done almost everything in their power to try and prevent scraping/ddosing stuff. unfortunate

http://stackoverflow.com/comment/92263151
type: AnswerComment
score: 0
type: Comment
has text: Does this mean, the number of features in my data increase depending on different transformations that I apply on them?
comment on: http://stackoverflow.com/a/52666039

http://stackoverflow.com/a/52694470
has body: If you would like to capture all the factors, you could use the sub below. If you give it a number like 1024, it returns a list of ten 2's (all the factors) def main(): x = int(input('Enter a number to find the prime factors ')) primes = prime_factors(x) print(primes) def prime_factors(x): factors = [] y = 2 while (y &lt;= x): while x % y != 0: y += 1 x /= y factors.append(y) return factors main()
answers question: http://stackoverflow.com/q/52693860
type: Answer
score: 0

http://stackoverflow.com/a/52666264
accepted answer of: http://stackoverflow.com/q/52666182
score: 6
type: AcceptedAnswer
downvote count: 0
has body: It could be that it's not encoded in utf-8. Try decoding it into latin-1 instead: file_data = file.read().decode("latin-1")
answers question: http://stackoverflow.com/q/52666182
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/92262236

http://stackoverflow.com/comment/92409323
type: Comment
type: QuestionComment
has text: //my php code $output = shell_exec('python3 ActorArrayMatcher_FS.py'); print_r($output);
score: 0
comment on: http://stackoverflow.com/q/52741901

http://stackoverflow.com/comment/92173075
score: 0
has text: @WillHamilton, can you publish your dataframe code you are processing to reproduce to get the correct answer.
type: Comment
comment on: http://stackoverflow.com/a/52619416
type: AnswerComment

http://stackoverflow.com/a/52619555
has body: You need to do what it says on the data.world site. Click the Download link (at the top right), Share URL and use either: To share a secure download link: https://query.data.world/s/xxxxxxxlink_codexxxxxxxx To import: import pandas as pd df = pd.read_csv('https://query.data.world/s/xxxxxxxlink_codexxxxxxxx') Note: my links have been edited to not work, you may provide your own link.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52616803
accepted answer of: http://stackoverflow.com/q/52616803
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/52592826
has body: A good way to initialize a class is: class A: def __init__(self, arg1=None, arg2=None): self.arg1=arg1 self.arg2=arg2 Since you want to initialize variables using a file, you may want to use ConfigParser. ConfigParser allows you to read from a file and access key-value pairs easily. from configparser import ConfigParser config = ConfigParser() config.read('example.conf') class A: def __init__(self, config): self.arg1=config['arg1'] self.arg2=config['arg2'] My example class above takes in a config object in which you can get the values you stored from a file. P.S. I didn't test the code above. Take a look at the configparser docs for more info.
has comment: http://stackoverflow.com/comment/92216116
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52590809

http://stackoverflow.com/q/52644035
possible better answer: http://stackoverflow.com/a/56296451
tagged with: pandas
has answer: http://stackoverflow.com/a/56296451
score: 59
downvote count: 0
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/52644115
has title: How to show a pandas dataframe into a existing flask html table?
has answer: http://stackoverflow.com/a/65764878
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52644615
has body: This may sound a noob question, but I'm stuck with it as Python is not one of my best languages. I have a html page with a table inside it, and I would like to show a pandas dataframe in it. What is the best way to do it? Use pandasdataframe.to_html? py from flask import Flask; import pandas as pd; from pandas import DataFrame, read_csv; file = r'C:\Users\myuser\Desktop\Test.csv' df = pd.read_csv(file) df.to_html(header="true", table_id="table") html &lt;div class="table_entrances" style="overflow-x: auto;"&gt; &lt;table id="table"&gt; &lt;thead&gt;&lt;/thead&gt; &lt;tr&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt;
upvote count: 59
tagged with: pandas-datareader
type: Question
has answer: http://stackoverflow.com/a/72958906
has answer: http://stackoverflow.com/a/56228582
answer count: 6
accepted answer: http://stackoverflow.com/a/52644615
linked to: http://stackoverflow.com/q/12341496

http://stackoverflow.com/comment/92291768
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52681750
has text: My apologies about the typo! I have removed it as per requested. On a different note, how would you go about it using nested `while` loops? Thanks a bunch, Baptiste!
type: Comment

http://stackoverflow.com/q/52689035
has body: Consider the following text: ! interesting1 a not interesting b interesting2 c ! interesting1 a not interesting b interesting2 c ! interesting1 a not interesting b interesting2 c not interesting arbitrary text d ! As you may have guessed, I want to extract a and c from every section. The interesting2 c line is optional, but I only need a if there is also c (section-wise). Using !\n(interesting1 (?P&lt;a&gt;.*?)$.*?(?:interesting2 (?P&lt;c&gt;.*?))?$\n(?=!)) I get: a and c from the top 2 sections, but (understandably) a and c\nnot interesting arbitrary text d from the last section. See on regex101. I doubt this is the most efficient regex for this situation as this small text requires 438 steps, so I'm open to any other more efficient solutions that will get the correct results. If I change the regex to !\n(interesting1 (?P&lt;a&gt;.*?)$.*?(?:interesting2 (?P&lt;c&gt;\w+))?$\n(?=!)) (\w+ instead of .*? in capture group c) the only thing it matches in the third section is a (as expected since \w does not include \n). What I don't understand is how to use $ in order to specify an optional line of arbitrary text between interesting2 c and the closing !. Using different variations of optional non-capturing groups and $ don't give me the correct results. I even tried optional non-capturing groups in the lookahead part (to signify that we may have additional/optional stuff before the !).
possible better answer: http://stackoverflow.com/a/52689239
answer count: 2
has answer: http://stackoverflow.com/a/52689239
has comment: http://stackoverflow.com/comment/92305355
has answer: http://stackoverflow.com/a/52689504
favorite count: 0
has comment: http://stackoverflow.com/comment/92305249
has comment: http://stackoverflow.com/comment/92305187
tagged with: python
tagged with: regex
has title: Slight regex confusion - $ behavior when using multiline flag
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/52689504
has comment: http://stackoverflow.com/comment/92305677
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/92192857
has text: please, show how do you send the data and the auth info.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52620395

http://stackoverflow.com/comment/92412189
type: QuestionComment
comment on: http://stackoverflow.com/q/52743576
score: 1
type: Comment
has text: Have you tried building from source from [here](https://github.com/mhammond/pywin32)?

http://stackoverflow.com/comment/92179687
comment on: http://stackoverflow.com/q/52622069
score: 0
type: QuestionComment
type: Comment
has text: @MuhammadAsif Because while processing data line by line if any error raise... So next time i don't want to reprocess complete file from starting

http://stackoverflow.com/q/52638332
tagged with: python
has comment: http://stackoverflow.com/comment/92225284
has comment: http://stackoverflow.com/comment/92224589
has comment: http://stackoverflow.com/comment/92225106
tagged with: http
type: Question
has answer: http://stackoverflow.com/a/52638390
has body: I am trying to map GET/PUT/DELETE HTTP methods to a single Django REST API endpoint. I can override the default get_queryset method to essentially do a GET request for a specific model field in the DB but am unsure which class methods to override for PUT/DELETE. If I'm using postman to perform PUT/DELETE I get a method not allowed error. Models.py class Computer(models.Model): computer_id = models.IntegerField(unique=True) city = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) def __str__(self): return str(self.computer_id) Urls.py router.register(r'computer/(?P&lt;comp_id&gt;[0-9]+)', ComputerViewSet, base_name='computers') Views.py class ComputerViewSet(viewsets.ModelViewSet): serializer_class = ComputerSerializer def get_queryset (self, *args, **kwargs): comp_id = self.kwargs['comp_id'] queryset = Computer.objects.filter(computer_id=comp_id) return queryset Serializers.py class ComputerSerializer(serializers.ModelSerializer): class Meta: model = Computer fields = ('id', 'computer_id', 'city', 'description') So I tried overriding other methods unsuccessfully in the class in Views.py : def destroy(self, request, *args, **kwargs): computer = self.get_object() self.perform_destroy(computer) computer.delete() def update(self, request, *args, **kwargs): #... My goal is to have one endpoint with GET/PUT/DELETE capabilities. How can I go about starting this?
has title: Django REST API one endpoint for CRUD
score: 0
has comment: http://stackoverflow.com/comment/92209841
has comment: http://stackoverflow.com/comment/92209630
answer count: 1
tagged with: django-rest-framework
tagged with: rest
type: UnansweredQuestion

http://stackoverflow.com/q/52727326
type: AnsweredQuestion
has body: I have the following dataframe, all the blank regions are np.nan. coupler_id 25 26 28 29 timestamp 2015-12-05 03:02:29 12017.0 12008.0 2015-12-05 03:04:47 12017.0 12008.0 2015-12-05 03:09:14 12017.0 12008.0 2015-12-05 03:12:12 12017.0 12008.0 2015-12-05 03:23:06 12008.0 2015-12-05 03:24:45 12017.0 2015-12-05 06:31:20 12017.0 2015-12-05 09:36:29 12011.0 2015-12-05 23:59:35 12017.0 2015-12-06 23:59:38 12017.0 I want to forward fill the missing values (limit 1) without duplicating values in rows. So the above dataframe should look like this: coupler_id 25 26 28 29 timestamp 2015-12-05 03:02:29 12017.0 12008.0 2015-12-05 03:04:47 12017.0 12008.0 2015-12-05 03:09:14 12017.0 12008.0 2015-12-05 03:12:12 12017.0 12008.0 2015-12-05 03:23:06 12017.0 12008.0 2015-12-05 03:24:45 12017.0 2015-12-05 06:31:20 12017.0 2015-12-05 09:36:29 12011.0 2015-12-05 23:59:35 12011.0 12017.0 2015-12-06 23:59:38 12017.0 Edit: What if there is data in column 25 and 26 and there was not a preceding nan on column 28 index 2015-12-05 03:24:45. coupler_id 25 26 28 29 timestamp 2015-12-05 03:02:29 12017.0 12008.0 2015-12-05 03:04:47 12017.0 12008.0 2015-12-05 03:09:14 12017.0 12008.0 2015-12-05 03:12:12 12017.0 12008.0 2015-12-05 03:23:06 12007.0 12018.0 12008.0 2015-12-05 03:24:45 12033.0 12050.0 12025.0 12017.0 2015-12-05 06:31:20 12033.0 12017.0 2015-12-05 09:36:29 12008.0 12011.0 2015-12-05 23:59:35 12017.0 2015-12-06 23:59:38 12017.0
has comment: http://stackoverflow.com/comment/92380637
has title: Forward fill pandas dataframe without duplicating values in rows
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52727735
type: Question
has comment: http://stackoverflow.com/comment/92379951
has comment: http://stackoverflow.com/comment/92380109
has answer: http://stackoverflow.com/a/52727735
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92380059
answer count: 1
tagged with: python

http://stackoverflow.com/q/52716889
tagged with: biopython
type: AnsweredQuestion
tagged with: fasta
has title: Repetitive writing in output using list of characters - python
possible better answer: http://stackoverflow.com/a/52716979
has answer: http://stackoverflow.com/a/52717025
type: Question
has body: In a file, I have some characters to be substituted. letters = ["B", "Z", "J", "U", "O"] for record in SeqIO.parse(inFile, "fasta"): for letter in letters: if letters in str(record.seq): print record.id record.seq = str(record.seq).replace(letter, "X") outFile.write("&gt;%s\n%s\n" % (record.description, record.seq)) else: outFile.write("&gt;%s\n%s\n" % (record.description, record.seq)) #pass The problem is that the output looks like this, writing the outputs as many characters I have in letters: &gt; &gt;ID:WP_004160595.1|Erwinia_amylovora_01SFR-BO|01SFR-BO|50S_ribosomal_protei..|630|NZ_CAPA01000010(58437):26053-26682:-1 &gt; MIGLVGKKVGMTRIFTEDGVSIPVTVIEIEANRVTQVKGLENDGYTAIQVTTGAKKANRVTKPAAGHFAKAGVEAGRGLWEFRTAEGAEFTVGQSINVDIFADVKKVDVTGTSKGKGFAGTVKRWNFRTQDATHGNSLSHRVPGSIGQNQTPGKVFKGKKMAGQLGNERVTVQSLDVVRVDAERNLLLVKGAVPGATGSDLIVKPAVKA &gt; &gt;ID:WP_004160595.1|Erwinia_amylovora_01SFR-BO|01SFR-BO|50S_ribosomal_protei..|630|NZ_CAPA01000010(58437):26053-26682:-1 &gt; MIGLVGKKVGMTRIFTEDGVSIPVTVIEIEANRVTQVKGLENDGYTAIQVTTGAKKANRVTKPAAGHFAKAGVEAGRGLWEFRTAEGAEFTVGQSINVDIFADVKKVDVTGTSKGKGFAGTVKRWNFRTQDATHGNSLSHRVPGSIGQNQTPGKVFKGKKMAGQLGNERVTVQSLDVVRVDAERNLLLVKGAVPGATGSDLIVKPAVKA &gt; &gt;ID:WP_004160595.1|Erwinia_amylovora_01SFR-BO|01SFR-BO|50S_ribosomal_protei..|630|NZ_CAPA01000010(58437):26053-26682:-1 &gt; MIGLVGKKVGMTRIFTEDGVSIPVTVIEIEANRVTQVKGLENDGYTAIQVTTGAKKANRVTKPAAGHFAKAGVEAGRGLWEFRTAEGAEFTVGQSINVDIFADVKKVDVTGTSKGKGFAGTVKRWNFRTQDATHGNSLSHRVPGSIGQNQTPGKVFKGKKMAGQLGNERVTVQSLDVVRVDAERNLLLVKGAVPGATGSDLIVKPAVKA &gt; &gt;ID:WP_004160595.1|Erwinia_amylovora_01SFR-BO|01SFR-BO|50S_ribosomal_protei..|630|NZ_CAPA01000010(58437):26053-26682:-1 &gt; MIGLVGKKVGMTRIFTEDGVSIPVTVIEIEANRVTQVKGLENDGYTAIQVTTGAKKANRVTKPAAGHFAKAGVEAGRGLWEFRTAEGAEFTVGQSINVDIFADVKKVDVTGTSKGKGFAGTVKRWNFRTQDATHGNSLSHRVPGSIGQNQTPGKVFKGKKMAGQLGNERVTVQSLDVVRVDAERNLLLVKGAVPGATGSDLIVKPAVKA &gt; &gt;ID:WP_004160595.1|Erwinia_amylovora_01SFR-BO|01SFR-BO|50S_ribosomal_protei..|630|NZ_CAPA01000010(58437):26053-26682:-1…
has comment: http://stackoverflow.com/comment/92359452
has comment: http://stackoverflow.com/comment/92359730
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52717025
has comment: http://stackoverflow.com/comment/92359591
tagged with: bioinformatics
tagged with: python
has answer: http://stackoverflow.com/a/52716979

http://stackoverflow.com/q/52737165
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92399710
tagged with: python
type: AnsweredQuestion
score: 0
type: Question
has answer: http://stackoverflow.com/a/52737841
has comment: http://stackoverflow.com/comment/92399769
has comment: http://stackoverflow.com/comment/92399454
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92399322
has body: Following Problem I got a DataFrame like so: df = pd.DataFrame(columns=pd.MultiIndex(levels=[["foo","baa"],["x","y","z"]], labels=[[0,0,0,1,1,1],[0,1,2,0,1,2]]), index=[0,1,2,3], data=np.random.rand(4,6)) foo baa x y z x y z 0 0.263780 0.942880 0.176744 0.914854 0.920735 0.573692 1 0.601317 0.584691 0.288536 0.832064 0.095142 0.186045 2 0.807323 0.075620 0.399703 0.936894 0.168441 0.468984 3 0.871293 0.324817 0.395784 0.133541 0.365586 0.615219 And I want to get say foo out of it into a new DataFrame completly empty constructed like this: r_df = pd.DataFrame(index=df.index) Empty DataFrame Columns: [] Index: [0, 1, 2, 3] it should look like this: foo x y z 0 0.263780 0.942880 0.176744 1 0.601317 0.584691 0.288536 2 0.807323 0.075620 0.399703 3 0.871293 0.324817 0.395784 How I tryed to do it was like this: for label in df.columns.levels[0]: data = df[label] for row in data.index: r_df.loc[row,(label,"x")] = data["x"] r_df.loc[row,(label,"y")] = data["y"] r_df.loc[row,(label,"z")] = data["z"] I thought this could work because multi index can be referenced by tubles but it didnt.
has comment: http://stackoverflow.com/comment/92399390
tagged with: pandas
answer count: 1
has title: appending multi index columns into empty dataframe
has comment: http://stackoverflow.com/comment/92399914
has comment: http://stackoverflow.com/comment/92399727
accepted answer: http://stackoverflow.com/a/52737841

http://stackoverflow.com/a/52630566
has body: The problem was 32-bit python versus 64-bit, and I think I know what broke it because when I reinstalled I had both 32-bit and 64-bit python installed. I uninstalled the 32-bit version os 2.7.15 and installed the 64-bit and it's working now. Thanks to Alex K for pointing out the redirection and sorry for the silly question!
answers question: http://stackoverflow.com/q/52629933
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/52684180
type: Answer
has body: Your loop, for student in studentgrades: will set, on each iteration, student to be one of the sublists. So for the first iteration, student will be the sublist [95, 92, 86]. So the next line, average = sum(studentgrades[student]) / len(studentgrades[student]) Will raise that error, as you're attempting to index (access) a list (studentgrades) by using another list (student). One way to fix this would be to iterate over the studentgrades list (as you're doing) then use that list in your average calculation: for student in studentgrades: average = sum(student) / len(student) antw.append(average) To put that visually, that code would result in a first iteration that'd look like: for student in studentgrades: average = sum([95, 92, 86]) / len([95, 92, 86]) antw.append(average) If you really wanted to index studentgrades every time, you might change your code to something like: for index in range(len(studentgrades)): average = sum(studentgrades[index]) / len(studentgrades[index]) antw.append(average) But the first option of iterating over the sublists (instead of the output of a range generator) seems much better :)
score: 0
answers question: http://stackoverflow.com/q/52684158

http://stackoverflow.com/q/52738308
has title: How to create a multiple line cell in pyplot table
has body: Is it possible to use a multiple line cell in pyplot (Matplotlib) table ? ... or merge cells in pyplot table. Here an example : import matplotlib.pyplot as plt plt.figure() table1 = [[1,2,3],[4,5,6]] plt_table1=plt.table(cellText=table1, rowLabels=['Line 1\n and stuff', 'line 2']) plt.axis('off') plt.show() Is it possible to use this idea ?
tagged with: python
has comment: http://stackoverflow.com/comment/92406884
answer count: 0
upvote count: 3
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37279807
score: 3
has comment: http://stackoverflow.com/comment/92404488
duplicate of: http://stackoverflow.com/q/37279807
tagged with: matplotlib
tagged with: matplotlib-table
type: Question
has comment: http://stackoverflow.com/comment/92407854
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/92314338
type: Comment
has text: Thanks but I couldn't connect either with the default link give me a 404 error. Do you have worked previously with this library ?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52693781

http://stackoverflow.com/q/52601258
tagged with: python
has body: I have a scatter plot that gets sorted into 4 Bins. These are separated by two arcs and a line in the middle (see figure below). There's a slight problem with the two arcs. If the X-Coordiante is greater than the ang2 it doesn't get attributed to the correct Bin. (Please see figure below) import math import matplotlib.pyplot as plt import matplotlib as mpl X = [24,15,71,72,6,13,77,52,52,62,46,43,31,35,41] Y = [94,61,76,83,69,86,78,57,45,94,82,74,56,70,94] fig, ax = plt.subplots() ax.set_xlim(-100,100) ax.set_ylim(-40,140) ax.grid(False) plt.scatter(X,Y) #middle line BIN_23_X = 0 #two arcs ang1 = -60, 60 ang2 = 60, 60 angle = math.degrees(math.acos(2/9.15)) E_xy = 0,60 Halfway = mpl.lines.Line2D((BIN_23_X,BIN_23_X), (0,125), color = 'white', lw = 1.5, alpha = 0.8, zorder = 1) arc1 = mpl.patches.Arc(ang1, 70, 110, angle = 0, theta2 = angle, theta1 = 360-angle, color = 'white', lw = 2) arc2 = mpl.patches.Arc(ang2, 70, 110, angle = 0, theta2 = 180+angle, theta1 = 180-angle, color = 'white', lw = 2) Oval = mpl.patches.Ellipse(E_xy, 160, 130, lw = 3, edgecolor = 'black', color = 'white', alpha = 0.2) ax.add_line(Halfway) ax.add_patch(arc1) ax.add_patch(arc2) ax.add_patch(Oval) #Sorting the coordinates into bins def get_nearest_arc_vert(x, y, arc_vertices): err = (arc_vertices[:,0] - x)**2 + (arc_vertices[:,1] - y)**2 nearest = (arc_vertices[err == min(err)])[0] return nearest arc1v = ax.transData.inverted().transform(arc1.get_verts()) arc2v = ax.transData.inverted().transform(arc2.get_verts()) def classify_pointset(vx, vy): bins = {(k+1):[] for k in range(4)} for (x,y) in zip(vx, vy): nx1, ny1 = get_nearest_arc_vert(x, y, arc1v) nx2, ny2 = get_nearest_arc_vert(x, y, arc2v) if x &lt; nx1: bins[1].append((x,y)) elif x &gt; nx2: bins[4].append((x,y)) else: if x &lt; BIN_23_X: bins[2].append((x,y)) else: bins[3].append((x,y)) return bins #Bins Output bins_red = classify_pointset(X,Y) all_points = [None] * 5 for bin_key in [1,2,3,4]: all_points[bin_key] = bins_red[bin_key] Out…
favorite count: 0
possible better answer: http://stackoverflow.com/a/52642487
upvote count: 1
tagged with: plot
type: Question
type: AnsweredQuestion
score: 1
tagged with: matplotlib
has title: Allocate scatter plot into specific bins
linked to: http://stackoverflow.com/q/49098942
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52603422
answer count: 2
has answer: http://stackoverflow.com/a/52642487
downvote count: 0
has answer: http://stackoverflow.com/a/52603422
tagged with: pandas

http://stackoverflow.com/a/52678799
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52678589
type: Answer
has body: The easiest way to do this is to make use of the dictionary .get() method to increment values if they have been seen before, or start with a default count of 0. my_count = {} for lst in L: for item in lst: my_count[item] = my_count.get(item, 0) + 1 However, since you're already iterating in this way to create the list, you can do it all together: import random my_count = {} L = [] for x in range(0, 100): L.append([]) for y in range(0, 6): num = random.randint(0, 45) + 1 L[x].append(num) my_count[num] = my_count.get(num, 0) + 1
has comment: http://stackoverflow.com/comment/92286449
has comment: http://stackoverflow.com/comment/92286475
accepted answer of: http://stackoverflow.com/q/52678589
score: 0
has comment: http://stackoverflow.com/comment/92286406
has comment: http://stackoverflow.com/comment/92286485
has comment: http://stackoverflow.com/comment/92286481

http://stackoverflow.com/comment/92218189
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52642712
has text: do you want to find maximum times a number appeared in a row ? ` A =[12,12,15,12,12,12]` and `B = [12]` ans is 3 or ...ans should be 2 because 12 appears two times consecutively.

http://stackoverflow.com/q/52636686
answer count: 3
has title: How to use PyInstaller from script, not terminal?
has answer: http://stackoverflow.com/a/52676985
possible better answer: http://stackoverflow.com/a/65079242
favorite count: 0
has comment: http://stackoverflow.com/comment/92206611
tagged with: pyinstaller
linked to: http://stackoverflow.com/q/89228
has comment: http://stackoverflow.com/comment/92206550
accepted answer: http://stackoverflow.com/a/52636912
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92206758
score: 12
type: Question
has body: Short version: How do I use PyInstaller from within a Python script, instead of from the terminal? What would I need to write inside a Python script to get the equivalent of writing this in the terminal: &gt;python -m PyInstaller --noconsole --name WorkLogger ../WorkLogger/main.py Long version: I'm using a library that requires using PyInstaller to distribute an executable. But I have to run PyInstaller once, then change the spec files, then run the spec file through PyInstaller. So in the terminal I would've done this: &gt;python -m PyInstaller --noconsole --name WorkLogger ../WorkLogger/main.py After this is done running, I manually change the spec file. Then I run: &gt;python -m PyInstaller WorkLogger.spec I've written a script that does the manual labor for me, by running &gt;change_spec.py But I ultimately want to do all of this in one Python script. I want to be able to type something like this: &gt;distribute_python_project.py ./Worklogger This means my Python script would need to look something like this: #Psuedocode: #python -m PyInstaller --noconsole --name WorkLogger ../WorkLogger/main.py #Code from change_spec.py #python -m PyInstaller WorkLogger.spec But I can't figure out how I use PyInstaller from a python script, instead of from the terminal. Is this possible? (The library I use is Kivy, for those interested).
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/92206827
has answer: http://stackoverflow.com/a/52636912
has answer: http://stackoverflow.com/a/65079242

http://stackoverflow.com/a/52593279
has body: import matplotlib.pyplot as plt from PIL import Image fig,ax = plt.subplots(2,5) filenames=['\path\to\img\img_{}.jpg'.format(i) for i in range(10)] #or glob or any other way to describe filenames for i in range(10): with open(filenames[i],'rb') as f: image=Image.open(f) ax[i%2][i//2].imshow(image) fig.show()
accepted answer of: http://stackoverflow.com/q/52592829
score: 10
answers question: http://stackoverflow.com/q/52592829
type: AcceptedAnswer
downvote count: 0
upvote count: 10
type: Answer

http://stackoverflow.com/comment/92267583
comment on: http://stackoverflow.com/q/52666965
score: 0
type: Comment
has text: @kindall An indexed image generally has only 1 channel, i.e. the indices. If the error says it got too many values to unpack and it was expecting 3, the most likely guess Is that there are 4 channels, i.e. RGBA.
type: QuestionComment

http://stackoverflow.com/q/52701175
downvote count: 0
linked to: http://stackoverflow.com/q/45696656
has comment: http://stackoverflow.com/comment/92396366
tagged with: pyinstaller
answer count: 1
tagged with: exe
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52739524
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: I have generated an .exe-file for a little PowerPoint Tool, that I've written using python 3.6, the PyQt5 framework and pyinstaller. The program runs without any errors on my own laptop and functions as expected. Unfortunately, I can't get the .exe to run on a different computer. I've tried with 2 other computers now and get different errors on each of them. PC 1: Entry Point not found The procedure entry point ucrtbase.terminate could not be located in the dynamic link library api-ms-win-crt-runtime-l1-1-0.dll. PC 2: This application failed to start because it could not load the Qt platform plugin 'Windows'. The thing, that bugs me is, that I had this last error (from PC2) during development on my dev computer, but fixed this problem for my own PC. What I was trying to do is create an .exe-file that just runs on any PC. It's a simple PowerPoint Helper, which is supposed to be a quick tool to create new slides from a folder of images. That is why it's pretty important, that it can be seamlessly used. Ideally just opening the .exe and go, without the need to worry about individual missing pieces on every single computer, where it will be utilized. BIG QUESTION: Is there anything I can do, to guarantee my .exe to include all the dependencies that are needed to run? Things I've tried (aka I DID try to solve it myself.. for days): read trough here: https://github.com/pyqt/python-qt5/issues/2 changed my .specas mentioned here: https://github.com/carlosperate/pyinstaller-test/blob/master/package/pyqt5_test.spec read through all of this: https://stackoverflow.com/search?page=2&amp;tab=Relevance&amp;q=entry%20point%20not%20found and this: https://stackoverflow.com/search?q=qt+platform+windows and this: pyinstaller exe without any dependencies? But nothing helps.... Most of the posts address problems when compiling the executable file, but this works just fine for me.
tagged with: pyqt5
type: Question
has title: .exe generated with pyinstaller crashes on other PCs - how to create .exe with TRULY no dependencies?

http://stackoverflow.com/comment/92201760
type: Comment
has text: Genera ID. Then you filter the different to nan, make a join
score: 0
comment on: http://stackoverflow.com/a/52634154
type: AnswerComment

http://stackoverflow.com/q/52594911
answer count: 1
accepted answer: http://stackoverflow.com/a/52596931
score: 0
has title: Python parent class modifiable by child class or dynamic attribute?
tagged with: python
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52596931
has body: So I am not even sure if what I want to do is possible but I thought I would ask and find out. I want to build a chef "databag" via python. This is pretty much just a python dictionary. There are other things that need to happen with this databag that are encapsulated in the Databag class. Now for the meat of the question... I want to add key/values to this dictionary but need to build it in a way that is easily extensible. NOTE: the autodict is a class that makes it so you can build a dictionary using dot notation. Here is what I am trying to do: databag = Databag( LogGroup=Sub("xva-${environment}-${uniqueid}-mygroup"), RunList=[ "mysetup::default", "consul::client" ] ) databag.Consul() &lt;-- Trying to add consul key/values to databag print(databag.to_dict()) print(databag.to_string_list()) So you can see how I add the "consul" key values to the already existing databag object. Here are the class definitions. I know this is wrong which is why I am here to see if this is even possible. Databag Class class Databag(object): def __init__(self,uniqueid=Ref("uniqueid"),environment=Ref("environment"),LogGroup=None,RunList=[]): self.databag = autodict() self.databag.uniqueid = uniqueid self.databag.environment = environment self.databag.log.group = LogGroup self.runlist=RunList def to_string_list(self): return self.convert_databag_to_string(self.databag) def to_dict(self): return self.databag def get_runlist(self): return self.convert_to_runlist_string(self.runlist) Consul Class class Consul(Databag): def __init__(self, LogGroup=None): if LogGroup == None: Databag.consul.log.group = Databag.log.group else: Databag.consul.log.group = LogGroup As you can see the Consul class is supposed to access the databag dictionary of the Databag class and add the "consul" variables, almost like an attribute. However, I don't want to add a new function to the databag class every time otherwise that class will end up being very, very large.

http://stackoverflow.com/comment/92347993
type: Comment
type: QuestionComment
has text: edit your post and format your code rather than stuffing it into an unreadable comment please...
comment on: http://stackoverflow.com/q/52695951
score: 0

http://stackoverflow.com/q/52674896
has answer: http://stackoverflow.com/a/52674953
downvote count: 1
has comment: http://stackoverflow.com/comment/92279504
type: Question
has answer: http://stackoverflow.com/a/52674910
has answer: http://stackoverflow.com/a/52674929
has comment: http://stackoverflow.com/comment/92279403
answer count: 3
has comment: http://stackoverflow.com/comment/92279429
has comment: http://stackoverflow.com/comment/92279512
has body: i've been learning Python for only a few weeks, so please bear with me. Let's say I have 3 variables: AX557349 = "gcggatttactcaggggagagcccagataaatggagtctgtgcgtccacagaattcgcacca" AX557350 = "tccgtgaaacaaagcggatgtaccggatttttattccggctatggggcaattccccgtcgcggagcca" Tester = "atcgatccblah" nucs = [] nucs.extend(AX557349, AX557350, Tester) I want to only return list element(s) that contain characters other than "a", "t", "c", or "g". In this case, Tester. How would I go about doing that?
has comment: http://stackoverflow.com/comment/92279493
has comment: http://stackoverflow.com/comment/92279536
favorite count: 0
tagged with: bioinformatics
accepted answer: http://stackoverflow.com/a/52674910
has comment: http://stackoverflow.com/comment/92279287
tagged with: python
score: 2
type: AnsweredQuestion
has title: How to check if string contains unwanted characters
upvote count: 3
possible better answer: http://stackoverflow.com/a/52674953

http://stackoverflow.com/comment/92383737
score: 0
has text: @rahlf23 I figured perhaps store it in a new temporary table, so that apple can be shown again but at a different date.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52728680

http://stackoverflow.com/q/52598719
type: AnsweredQuestion
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52599500
tagged with: directory-tree
score: 0
has answer: http://stackoverflow.com/a/52599154
has body: I need to traverse all my folders to find the file path of a folder with files with a specific extension (for sake of example, we will say .txt). I do not know if the folder will be at the top of the tree or at the bottom. For example, we are starting in: OneDrive/Documents/project/SourceCode The folder containing all the .txt files could be in OneDrive/Documents/project/SourceCode/TxtFiles or it could be in OneDrive/Documents/project/TxtFiles or it could also be up more past the project file. How would I find the filepath? I tried using os.walk, but I do not have a strong enough understanding of how it works. In the end, I am globbing all of the .txt files into a giant list.
tagged with: glob
possible better answer: http://stackoverflow.com/a/52599154
has title: Use os.walk to find a folder with specific file extensions under directory tree
accepted answer: http://stackoverflow.com/a/52599500
tagged with: python
tagged with: os.walk
tagged with: filepath

http://stackoverflow.com/q/52651270
answer count: 2
tagged with: function
possible better answer: http://stackoverflow.com/a/52651636
has answer: http://stackoverflow.com/a/52651636
has body: Originally I had "global" statements inside of the deposit and withdraw functions. I was told by my professor that I cannot use global statements for this assignment. There is a variable at the top that was created by Codio and I cannot move that. I have to access that variable in my functions, which I did. Now I need to get my functions to return in such a way that the "account_balance" variable updates after each withdrawal and deposit. Currently the code functions mostly okay, but after each operation on the money, I type "b" for the balance function and the previous operations are wiped away and I'm back at the default balance. What am I doing wrong here? Code is below: import sys #account balance account_balance = float(500.25) #&lt;--------functions go here--------------------&gt; #printbalance function def balance(): print('Your current balance:\n%.2f' % account_balance) #deposit function def deposit(temp): deposit_amount = float(input('How much would you like to deposit today?\n')) temp = temp + deposit_amount print('Deposit was $%.2f, current balance is $%.2f' % (deposit_amount, temp)) return temp #withdraw function def withdraw(temp2): withdrawal_amount = float(input('How much would you like to withdraw today?\n')) if withdrawal_amount &gt; temp2: print('$%.2f is greater than your account balance of $%.2f ' % (withdrawal_amount, temp2)) else: temp2 -= withdrawal_amount account_balance = temp2 print('Withdrawal amount was $%.2f, current balance is $%.2f' % (withdrawal_amount, temp2)) return temp2 #User Input goes here, use if/else conditional statement to call function based on user input userchoice = '' while userchoice!= 'Q': userchoice = input('What would you like to do?\n(B)alance?, (W)ithdraw?, (D)eposit?, (Q)uit?\n') userchoice = userchoice.upper() if (userchoice == 'B'): balance () elif userchoice == 'W': withdraw (account_balance) elif userchoice == 'D': deposit (account_balance) elif userchoice == 'Q': print('Thank you for banking with us.') break
has answer: http://stackoverflow.com/a/52651473
tagged with: python
tagged with: global
has comment: http://stackoverflow.com/comment/92234578
type: AnsweredQuestion
has title: Fixing "global" issue with program?
type: Question
accepted answer: http://stackoverflow.com/a/52651473
score: 0

http://stackoverflow.com/comment/119493539
comment on: http://stackoverflow.com/a/52660279
score: 0
type: AnswerComment
has text: for those unaware (as me) of the star operator: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists and https://stackoverflow.com/questions/2921847/what-does-the-star-and-doublestar-operator-mean-in-a-function-call
type: Comment

http://stackoverflow.com/a/52595447
upvote count: 14
has comment: http://stackoverflow.com/comment/97509587
downvote count: 1
has comment: http://stackoverflow.com/comment/92128905
has body: A fuller traceback would be nice. My guess is that seaborn.distplot is using scipy.stats to calculate something. The error occurs in def _compute_qth_percentile(sorted, per, interpolation_method, axis): .... indexer = [slice(None)] * sorted.ndim ... indexer[axis] = slice(i, i + 2) ... return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval So in this last line, the list indexer is used to slice sorted. In [81]: x = np.arange(12).reshape(3,4) In [83]: indexer = [slice(None), slice(None,2)] In [84]: x[indexer] /usr/local/bin/ipython3:1: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. #!/usr/bin/python3 Out[84]: array([[0, 1], [4, 5], [8, 9]]) In [85]: x[tuple(indexer)] Out[85]: array([[0, 1], [4, 5], [8, 9]]) Using a list of slices works, but the plan is to depreciate in the future. Indexes that involve several dimensions are supposed to be tuples. The use of lists in the context is an older style that is being phased out. So the scipy developers need to fix this. This isn't something end users should have to deal with. But for now, don't worry about the futurewarning. It doesn't affect the calculations or plotting. There is a way of suppressing future warnings, but I don't know it off hand. FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use `arr[tuple(seq)]` instead of `arr[seq]`
has comment: http://stackoverflow.com/comment/106306055
answers question: http://stackoverflow.com/q/52594235
accepted answer of: http://stackoverflow.com/q/52594235
has comment: http://stackoverflow.com/comment/126372698
type: AcceptedAnswer
score: 13
type: Answer

http://stackoverflow.com/a/52644764
score: 9
downvote count: 0
type: Answer
has body: A simple way to establish the alignment of a column is through the delegates: import sys from PyQt5 import QtCore, QtWidgets class AlignDelegate(QtWidgets.QStyledItemDelegate): def initStyleOption(self, option, index): super(AlignDelegate, self).initStyleOption(option, index) option.displayAlignment = QtCore.Qt.AlignCenter class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.tableWidget = QtWidgets.QTableWidget(15, 6) self.setCentralWidget(self.tableWidget) for i in range(self.tableWidget.rowCount()): for j in range(self.tableWidget.columnCount()): it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j)) self.tableWidget.setItem(i, j, it) delegate = AlignDelegate(self.tableWidget) self.tableWidget.setItemDelegateForColumn(2, delegate) # for all columns: # self.tableWidget.setItemDelegate(delegate) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.resize(640, 480) w.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/122257338
has comment: http://stackoverflow.com/comment/122257356
answers question: http://stackoverflow.com/q/52644371
upvote count: 9
has comment: http://stackoverflow.com/comment/122259487

http://stackoverflow.com/q/52690131
has title: NameError: name 'config' is not defined
has comment: http://stackoverflow.com/comment/92308156
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52690370
score: 1
possible better answer: http://stackoverflow.com/a/52690200
upvote count: 1
has answer: http://stackoverflow.com/a/52690200
type: Question
has comment: http://stackoverflow.com/comment/92308887
has answer: http://stackoverflow.com/a/52690222
has comment: http://stackoverflow.com/comment/92307244
has comment: http://stackoverflow.com/comment/92308819
has comment: http://stackoverflow.com/comment/92308224
has comment: http://stackoverflow.com/comment/92307220
has comment: http://stackoverflow.com/comment/92307267
has comment: http://stackoverflow.com/comment/92308879
has body: This error seems to have been asked earlier but I noticed the responses were to create a class and instantiate an object. Here I just define a function to read a yaml file and spit out the values. import yaml def read_yaml(file): with open(file, "r") as stream: try: config = yaml.load(stream) print(config) except yaml.YAMLError as exc: print(exc) print("\n") return config read_yaml(config.yaml) print(config) This returns an error: " NameError: name 'config' is not defined ". I can print the data from yaml file but not the config returned by the function.
has comment: http://stackoverflow.com/comment/92307195
tagged with: nameerror
answer count: 3
tagged with: function
has answer: http://stackoverflow.com/a/52690370
downvote count: 0
tagged with: callback
favorite count: 0

http://stackoverflow.com/q/52596327
favorite count: 0
type: Question
tagged with: locust
upvote count: 2
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52597888
has body: Locust is a great and simple load testing tool. By default it only tracks response times and content length from which it can deduce RPS, etc. Is there any way to track custom statistics in locust as well? In my case a site Im testing returns couple of stats via headers. For example a count of SQL queries within a request. It would be very helpful to track some of these statistics in conjunction to tracking standard response times. I do not see any way to do that in locust however. Is there a simple way for doing that? Only customization I could see is setting url names in a request in docs. Manually storing some of the stats is not that straight forward either as locust is distributed so would like to avoid doing anything custom. edit There is an example how custom stats can be passed around however that does not show up in the UI and requires custom export. Any way to add additional data in locust which will get logged both in UI and data export? Maybe something like: class MyTaskSet(TaskSet): @task def my_task(self): response = self.client.get("/foo") self.record(foo=response.headers.get('x-foo'))
score: 2
downvote count: 0
type: UnansweredQuestion
has title: Any way to track custom statistics in locust

rounding
tags question: http://stackoverflow.com/q/52697875
tags question: http://stackoverflow.com/q/52623621
tags question: http://stackoverflow.com/q/52708660
tags question: http://stackoverflow.com/q/52740989
tag name: rounding
type: Tag

http://stackoverflow.com/comment/92305519
comment on: http://stackoverflow.com/a/52627105
type: Comment
has text: @RohanPooniwala Done!
type: AnswerComment
score: 0

multidimensional-array
tags question: http://stackoverflow.com/q/52681191
tags question: http://stackoverflow.com/q/52725154
tags question: http://stackoverflow.com/q/52597757
tags question: http://stackoverflow.com/q/52740339
tags question: http://stackoverflow.com/q/52635539
type: Tag
tags question: http://stackoverflow.com/q/52731257
tag name: multidimensional-array

http://stackoverflow.com/a/52709374
answers question: http://stackoverflow.com/q/52697732
score: -1
downvote count: 1
type: Answer
has body: You could filter based on slice l = list(filter(lambda x: x[:2] not in firstList, secondList)) # 'i-am3', 'banana', 'test ok'
upvote count: 0

http://stackoverflow.com/a/52694341
has comment: http://stackoverflow.com/comment/114581855
answers question: http://stackoverflow.com/q/52693565
upvote count: 2
has body: To find the answer you can use the other code they provide for manually doing what geocoder does: import requests url = 'https://maps.googleapis.com/maps/api/geocode/json' params = {'sensor': 'false', 'address': 'Mountain View, CA'} r = requests.get(url, params=params) results = r.json() Looking in this object we can see that it contains an error_message key, as well as the status OVER_QUERY_LIMIT. The error message reads as follows: print(results['error_message']) You have exceeded your rate-limit for this API. We recommend registering for a key at the Google Developers Console: https://console.developers.google.com/apis/credentials?project=_ This is due to the fact that Google stopped supporting keyless API access back on June 11, 2018. To use Google as the provider for geocoding you'll need to get an API key and enable billing. You may want to look at some free alternatives for geocoding out there if you don't want to pay for their API access. EDIT: Looks like the geocoder documentation also has a list of alternatives that you can try using.
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/a/54031127
answers question: http://stackoverflow.com/q/52677658
downvote count: 0
type: Answer
upvote count: 3
has body: Your problem is this: The command import pandas as pd in your case didn't import the genuine pandas module, but some other one - and in that other one the read_csv() function is not defined. Highly likely you have in your project directory (or in your current directory) a file with the name "pandas.py". And - highly likely - you called the pd.read_csv() function in it. Rename this file, and you will be happy again. (Highly likely.)
has comment: http://stackoverflow.com/comment/116983318
score: 3

http://stackoverflow.com/q/52691945
has comment: http://stackoverflow.com/comment/92311266
has comment: http://stackoverflow.com/comment/92311672
has comment: http://stackoverflow.com/comment/92310886
has body: I have 2 data frames I am trying to join on multiple conditions [col1 , col2]. col2 is a date in this format 02/17/2018. Both data frames have the dates column in '%m/%d/%Y' format. I have I have tried to make sure they are the same format and have attempted to strip any white spaces. Both data comes from 2 CSV files. df_next_date = pd.merge(df_calls, df_nums, how= 'left', left_on= ['ticker','date'], right_on=['ticker','day_after']) date ticker meas meas2 meas3 10/27/2018 amazon 5 NaN NaN 02/02/2017 amazon 3 NaN NaN 05/20/2018 apple 2 NaN NaN I attempted to use strip to get rid of any white spaces with no luck. df_nums['day_after'] = df_nums['day_after'].str.strip() Here is a sample of the 2 date frames. df_calls date ticker meas 10/27/2018 amazon 5 02/02/2017 amazon 3 05/20/2018 apple 2 df_nums date ticker meas2 meas3 10/27/2018 amazon 2 6 02/02/2017 amazon 5 4 05/20/2018 apple 7 5 The odd thing is I have another date column in df_nums that successfully joined to the date column of df_calls with no issue so I believe it must be with in the df_nums['day_after'] column.I have looked tried the answers for similar issues her
has title: Merge on Dates column returning NaN
upvote count: 1
has comment: http://stackoverflow.com/comment/92310894
answer count: 0
type: UnansweredQuestion
tagged with: date
has comment: http://stackoverflow.com/comment/92311101
has comment: http://stackoverflow.com/comment/92311688
tagged with: pandas
has comment: http://stackoverflow.com/comment/92311546
has comment: http://stackoverflow.com/comment/92311024
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92311590
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: merge

http://stackoverflow.com/a/52723550
has body: The example that you are comparing this to, is graphing the amplitude at each frequency bin, i.e, abs(fft()) The periodogram produces a power spectral density, that means it is the square of the amplitude at each frequency bin. The label "windowed psd" is from an early edit, and was corrected later.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92372663
type: Answer
answers question: http://stackoverflow.com/q/52723383
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52723383
has comment: http://stackoverflow.com/comment/92372485

http://stackoverflow.com/q/52736840
has title: Writing hex numbers to a file in Python
answer count: 2
has comment: http://stackoverflow.com/comment/93665847
has body: The below code is reading a file called ‘test.txt’ which has hex numbers. The below code is converting these hex number into decimal numbers. How can I write the decimal number to a file instead of printing it out? my code file= 'test.txt' with open(file) as fp: line = fp.readline() cnt = 1 while line: i = int(line, 16) print(str(i)) line = fp.readline() cnt += 1
favorite count: 0
linked to: http://stackoverflow.com/q/6159900
tagged with: python-3.x
type: UnansweredQuestion
score: -3
tagged with: python
duplicate of: http://stackoverflow.com/q/6159900
downvote count: 3
has answer: http://stackoverflow.com/a/52736874
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/52736898

dataframe
tags question: http://stackoverflow.com/q/52654214
tags question: http://stackoverflow.com/q/52678422
tags question: http://stackoverflow.com/q/52624059
tags question: http://stackoverflow.com/q/52635171
tags question: http://stackoverflow.com/q/52717994
tags question: http://stackoverflow.com/q/52684290
tags question: http://stackoverflow.com/q/52630289
tags question: http://stackoverflow.com/q/52727838
tags question: http://stackoverflow.com/q/52740893
tags question: http://stackoverflow.com/q/52724044
tags question: http://stackoverflow.com/q/52604133
tags question: http://stackoverflow.com/q/52626923
tags question: http://stackoverflow.com/q/52630311
tags question: http://stackoverflow.com/q/52642966
tags question: http://stackoverflow.com/q/52745365
tags question: http://stackoverflow.com/q/52693015
tags question: http://stackoverflow.com/q/52605852
tags question: http://stackoverflow.com/q/52735762
tags question: http://stackoverflow.com/q/52676653
tags question: http://stackoverflow.com/q/52646676
tags question: http://stackoverflow.com/q/52722315
tags question: http://stackoverflow.com/q/52701932
tags question: http://stackoverflow.com/q/52654011
tags question: http://stackoverflow.com/q/52638427
tags question: http://stackoverflow.com/q/52731780
tags question: http://stackoverflow.com/q/52746702
tags question: http://stackoverflow.com/q/52681731
tags question: http://stackoverflow.com/q/52682423
tags question: http://stackoverflow.com/q/52673814
tags question: http://stackoverflow.com/q/52594686
tags question: http://stackoverflow.com/q/52624286
tags question: http://stackoverflow.com/q/52694947
tags question: http://stackoverflow.com/q/52656862
tags question: http://stackoverflow.com/q/52667035
tags question: http://stackoverflow.com/q/52689905
tags question: http://stackoverflow.com/q/52596975
tags question: http://stackoverflow.com/q/52713466
tags question: http://stackoverflow.com/q/52731563
tags question: http://stackoverflow.com/q/52695826
tags question: http://stackoverflow.com/q/52723755
tags question: http://stackoverflow.com/q/52741236
tags question: http://stackoverflow.com/q/52601168
tags question: http://stackoverflow.com/q/52622708
tags question: http://stackoverflow.com/q/52740527
tags question: http://stackoverflow.com/q/52708365
tags question: http://stackoverflow.com/q/52741874
tags question: http://stackoverflow.com/q/52656521
tags question: http://stackoverflow.com/q/52606022
tags question: http://stackoverflow.com/q/52735259
tags question: http://stackoverflow.com/q/52637037
tags question: http://stackoverflow.com/q/52739486
tags question: http://stackoverflow.com/q/52703921
tags question: http://stackoverflow.com/q/52721889
tags question: http://stackoverflow.com/q/52693136
tags question: http://stackoverflow.com/q/52650041
tags question: http://stackoverflow.com/q/52647667
tags question: http://stackoverflow.com/q/52709059
tags question: http://stackoverflow.com/q/52745166
tags question: http://stackoverflow.com/q/52589348
tags question: http://stackoverflow.com/q/52728852
tags question: http://stackoverflow.com/q/52729569
tags question: http://stackoverflow.com/q/52607992
tags question: http://stackoverflow.com/q/52651039
tags question: http://stackoverflow.com/q/52636092
tags question: http://stackoverflow.com/q/52625091
tags question: http://stackoverflow.com/q/52616959
tags question: http://stackoverflow.com/q/52597031
tags question: http://stackoverflow.com/q/52612526
tags question: http://stackoverflow.com/q/52711386
tags question: http://stackoverflow.com/q/52639258
tags question: http://stackoverflow.com/q/52727326
tags question: http://stackoverflow.com/q/52686318
tags question: http://stackoverflow.com/q/52595611
tags question: http://stackoverflow.com/q/52615950
tags question: http://stackoverflow.com/q/52677165
tags question: http://stackoverflow.com/q/52663848
tags question: http://stackoverflow.com/q/52596332
tags question: http://stackoverflow.com/q/52621834
tags question: http://stackoverflow.com/q/52613682
tags question: http://stackoverflow.com/q/52673648

http://stackoverflow.com/q/52682394
answer count: 1
score: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/92292970
accepted answer: http://stackoverflow.com/a/52682719
has comment: http://stackoverflow.com/comment/92293056
type: AnsweredQuestion
has body: I have a report that identifies key drivers of an overall number/trend. I would like to automate the functionality to be able to list/identify the underlying records based on a percentage of that number. For example if the net change for sales of widgets in the south(region) is -5,000.00, but there are positives and negatives- I would like to identify at least ~90% (-4,500.00) of all underlying drivers that make up that -5,000.00 total from largest to smallest. data region OfficeLocation sales South 1 -500 South 2 300 South 3 -1000 South 4 -2000 South 5 300 South 6 -700 South 7 -400 South 8 800 North 11 300 North 22 -400 North 33 1000 North 44 800 North 55 900 North 66 -800 for South, the total sales is -3200. I would like to identify/list the drivers that make up at least 90% of this move(in descending order)- so 90% of -3200 would be 2880. And the directional moves/sales for South office 3 &amp; 4 = -3000 would be the output for this request: region OfficeLocation sales South 3 -1000 South 4 -2000 for North, the total sales is +1800. I would like to identify/list the drivers that make up at least 90% of this move(in descending order)- so at least 90% of 1800 would be 1620. And the directional moves/sales for South office 3 &amp; 4 = -3000 would be the output for this request: region OfficeLocation sales North 33 1000 North 44 800 Dataset above has both positive and negative trends for south/north. Any help you can provide would be greatly appreciated!
has answer: http://stackoverflow.com/a/52682719
has comment: http://stackoverflow.com/comment/92292940
has title: identify records that make up 90% of total
type: Question

http://stackoverflow.com/comment/92316188
type: Comment
type: QuestionComment
has text: the coordinate pairs are from geojson lines, so the outer brackets represent where one linestring ends and another begins
comment on: http://stackoverflow.com/q/52694786
score: 0

http://stackoverflow.com/comment/92360849
type: AnswerComment
score: 0
type: Comment
has text: hey @Debbie I have added a bit more detail for you.
comment on: http://stackoverflow.com/a/52717568

http://stackoverflow.com/a/52744199
accepted answer of: http://stackoverflow.com/q/52744034
score: 0
answers question: http://stackoverflow.com/q/52744034
type: Answer
has comment: http://stackoverflow.com/comment/92413979
has body: This will give you the wanted dates: import datetime end = datetime.date.today() - datetime.timedelta(1) start = end.replace(day=1) daysInMonth = (datetime.date(start.year, start.month + 1, 1) - datetime.timedelta(1)).day start #2018-10-01 end #2018-10-09 daysInMonth #31
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92413948

http://stackoverflow.com/comment/92199810
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52633119
has text: @user3483203 Is there a way I could fill them for example 60% data with 2 and remaining 40% data with 8 randomly? I'll update the question.

http://stackoverflow.com/q/52728432
has body: I am trying to join two data frames (df1 and df2) based on matching values from one column (called 'Names') that is found in each data frame. I have tried this using R's inner_join function as well as Python's pandas merge function, and have been able to get both to work successfully on smaller subsets of my data. I think my problem is with the size of my data frames. My data frames are as follows: df1 has the 'Names' column with 5 additional columns and has ~900 rows. df2 has the 'Names' column with ~2million additional columns and has ~900 rows. I have tried (in R): df3 &lt;- inner_join(x = df1, y = df2, by = 'Name') I have also tried (in Python where df1 and df2 are Pandas data frames): df3 = df1.merge(right = df2, how = 'inner', left_on = 1, right_on = 0) (where the 'Name' column is at index 1 of df1 and at index 0 of df2) When I apply the above to my full data frames, it runs for a very long time and eventually crashes. Additionally, I suspect that the problem may be with the 2 million columns of my df2, so I tried sub-setting it (row-wise) into smaller data frames. My plan was to join the small subsets of df2 with df1 and then row bind the new data frames together at the end. However, joining even the smaller partitioned df2s was unsuccessful. I would appreciate any suggestions anyone would be able to provide.
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/52730680
has comment: http://stackoverflow.com/comment/92384154
tagged with: python
has comment: http://stackoverflow.com/comment/92386287
tagged with: merge
score: 4
answer count: 2
has comment: http://stackoverflow.com/comment/92382248
tagged with: inner-join
has comment: http://stackoverflow.com/comment/92382626
has comment: http://stackoverflow.com/comment/92382107
has comment: http://stackoverflow.com/comment/92382176
has title: inner join with huge dataframes (~2 million columns)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52729702
has comment: http://stackoverflow.com/comment/92420702
has comment: http://stackoverflow.com/comment/92382735
upvote count: 4

http://stackoverflow.com/a/52591774
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52591695
downvote count: 0
score: 1
has body: Can you try doing this: a,b = x.split('/') This will work only if there are 2 elements after splitting.

http://stackoverflow.com/q/52623218
has title: Import Only Necessary CSV Columns In IDL
type: Question
tagged with: idl-programming-language
upvote count: 1
has answer: http://stackoverflow.com/a/52638210
tagged with: arrays
accepted answer: http://stackoverflow.com/a/52638210
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92231282
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/92209260
tagged with: python
type: AnsweredQuestion
has body: I am struggling to find a function in IDL that will replicate something I have done in Python with Pandas. I am new to IDL and there is next to nothing resource wise that I can find. In Python, I use the following: pd.read_csv('&lt;csv filepath&gt;', usecols=[n]) The usecols part will only pull in the columns of a CSV I would like in my data frame. Is there a way to do this in IDL? I hope this makes sense - my first post here! Thanks.
score: 1

http://stackoverflow.com/q/52654504
has body: I just started learning python and I have a problem that I canno't get a button to close my program. The code: from tkinter import * import ScoreboardController as SC class guiController(Frame): def open_scoreboard(self): scoreBoard = SC.ScoreboardController("scores.txt") for x in range(len(scoreBoard)): print("Name: {} \nScore: {}". format(scoreBoard[x].name, scoreBoard[x].score)) def start_game(self): pass def hide_main_window(self): self.score_button.pack_forget() self.start_button.pack_forget() def create_widgets(self): self.frame = Frame(master=None, width=800, height=600) self.frame.pack() self.start_button = Button(self.frame) self.start_button["text"] = "Játék indítása" self.start_button["bg"] = "#5E99FF" self.start_button["fg"] = "#ffffff" self.start_button["command"] = self.start_game self.start_button.pack() self.start_button.place(x=300, y=455, bordermode=OUTSIDE, height=50, width=200) self.score_button = Button(self.frame) self.score_button["text"] = "Eredmények" self.score_button["bg"] = "#5E99FF" self.score_button["fg"] = "#ffffff" self.score_button["command"] = self.open_scoreboard self.score_button.pack() self.score_button.place(x=300, y=400, bordermode=OUTSIDE, height=50, width=200) self.quit_button = Button(self.frame) self.quit_button["text"] = "Kilépés" self.quit_button["bg"] = "#5E99FF" self.quit_button["fg"] = "#FFFFFF" self.quit_button["command"] = self.destroy() self.quit_button.pack() self.quit_button.place(x=300, y=510, bordermode=OUTSIDE, height=50, width=200) def __init__(self, master=None): Frame.__init__(self, master) self.place() self.create_widgets() When I click the button it doesn't do anything (self.quit_button). The other buttons work. Thank you in advance
has title: Tkinter quit button
has comment: http://stackoverflow.com/comment/92240823
has comment: http://stackoverflow.com/comment/92240959
has comment: http://stackoverflow.com/comment/92240436
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92240854
tagged with: tkinter
has comment: http://stackoverflow.com/comment/92240554
has comment: http://stackoverflow.com/comment/92240596
type: Question
has comment: http://stackoverflow.com/comment/92240910
has comment: http://stackoverflow.com/comment/92240649
has answer: http://stackoverflow.com/a/52654817
has comment: http://stackoverflow.com/comment/92240718
accepted answer: http://stackoverflow.com/a/52654817
score: 0
answer count: 1

http://stackoverflow.com/q/52729540
has comment: http://stackoverflow.com/comment/92384403
score: 0
has title: Is it possible to "lock" dependencies for a Python CLI application on PyPI?
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/92384920
type: UnansweredQuestion
has body: Let's say I'm developing a Python CLI application, which I plan on distributing to others. The usual way this is done is through the Python Package Index and requires me to create a setup.py with packaging information. When I am declaring dependencies for my package, setup.py requires me to fill in the install_requires parameter of the setup function. This is fine but has its limitations, namely locking these dependencies. The problem I want to avoid in my code can be shown through an example: Suppose I declare a dependency such as requests==2.19.1, which itself declares certifi&gt;=2017.4.17 as its own dependency. Fast forward some time later, and certifi v2018.3.2 has been released with the whole API rewritten. As requests only declares a lower bound to this dependency, it may break with the brand new version of certifi, which could then possibly break my code. How do I lock dependencies for an application that I am publishing to PyPI in order to avoid the aforementioned problem?
upvote count: 1
tagged with: python
tagged with: dependency-management
has comment: http://stackoverflow.com/comment/92384424
has comment: http://stackoverflow.com/comment/92384682
has comment: http://stackoverflow.com/comment/92384644
has comment: http://stackoverflow.com/comment/92384233
downvote count: 1
tagged with: pypi
type: Question
has comment: http://stackoverflow.com/comment/92384313
has comment: http://stackoverflow.com/comment/92384275

http://stackoverflow.com/a/52735676
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/52735535
answers question: http://stackoverflow.com/q/52735535
has comment: http://stackoverflow.com/comment/92396286
upvote count: 1
has body: Thats it running. If you want to see more, you need to start it with the verbose flag -v $.\mosquitto.exe -v If you installed it in the default location, you can run it like this from the command prompt (just copy and paste): "C:\Program Files (x86)\mosquitto\mosquitto.exe" -v Also note that if you installed it with the Service option (checked by default), the next time you start your PC, it will already be running, so if you try to start it again by clicking on the icon, the command prompt will appear and then close.
has comment: http://stackoverflow.com/comment/92396231

http://stackoverflow.com/a/52617933
has comment: http://stackoverflow.com/comment/92169992
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52617808
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52617808
upvote count: 2
has body: Here def alter(ls): for i in range(len(ls)-1): if ls[i]%2 == ls[i+1]%2: return False return True

http://stackoverflow.com/comment/92219144
type: Comment
has text: @brunodesthuilliers yes, i know. but i dont agree. I would not call it anti pattern. Even in the article it says it has its use. And this question is actually good example for signals - as I understood - he just wants to log an event. I would argue signal is good solution for this.
comment on: http://stackoverflow.com/a/52643144
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92264930
type: QuestionComment
comment on: http://stackoverflow.com/q/52652313
has text: Yes, i have crawled more than 1 millions of url for a price comparison portal and experienced this as the best way to scrape data.
score: 0
type: Comment

http://stackoverflow.com/q/52697002
has answer: http://stackoverflow.com/a/52697188
downvote count: 0
tagged with: pandas-groupby
answer count: 1
has comment: http://stackoverflow.com/comment/92320514
accepted answer: http://stackoverflow.com/a/52697188
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has body: i have data df: month name duration 5 abc 09:03:00 5 abc 09:09:00 5 eef 10:03:00 5 eef 09:03:00 5 eef 09:03:00 5 ttk 10:03:00 5 abc 09:03:00 5 ttk 09:23:00 6 ttk 09:03:00 6 abc 11:03:00 I need to groupby this to get results like this: month name name_size name_nuique duration_mean 5 abc 3 1 09:05:00 eef 3 1 09:23:00 ttk 2 1 09:43:00 6 abc 1 1 09:03:00 ttx 1 1 11:03:00 Please let me know how to do this. I tried doing df.groupby(['month','name'], sort=False).agg({'name':['size','nunique'], 'duration':['mean']}) But i get error saying: No numeric types to aggregate
has title: group by average no of hours
has comment: http://stackoverflow.com/comment/92320370
upvote count: 1
type: Question

http://stackoverflow.com/q/52727856
has comment: http://stackoverflow.com/comment/92381307
has comment: http://stackoverflow.com/comment/92937327
has answer: http://stackoverflow.com/a/52728556
has comment: http://stackoverflow.com/comment/92381487
tagged with: pool
answer count: 2
has comment: http://stackoverflow.com/comment/92381415
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92381800
tagged with: python
linked to: http://stackoverflow.com/q/52272325
score: 3
has comment: http://stackoverflow.com/comment/92381524
has comment: http://stackoverflow.com/comment/92381234
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92916832
tagged with: multiprocessing
upvote count: 4
has answer: http://stackoverflow.com/a/52737081
has comment: http://stackoverflow.com/comment/92381296
has body: How to exit from a function called my multiprocessing.Pool Here is an example of the code I am using, when I put a condition to exit from function worker when I use this as a script in terminal it halts and does not exit. def worker(n): if n == 4: exit("wrong number") # tried to use sys.exit(1) did not work return n*2 def caller(mylist, n=1): n_cores = n if n &gt; 1 else multiprocessing.cpu_count() print(n_cores) pool = multiprocessing.Pool(processes=n_cores) result = pool.map(worker, mylist) pool.close() pool.join() return result l = [2, 3, 60, 4] myresult = caller(l, 4)
has title: Right way to exit from function called by multiprocessing.Pool?
has comment: http://stackoverflow.com/comment/92381336
has comment: http://stackoverflow.com/comment/92381359

http://stackoverflow.com/a/52632091
downvote count: 0
has body: In Python 3, zip returns a generator: once iterated, it is exhausted. You should convert it to a list first: weekzip = list(zip(weekdays, weekdaynum))
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52631795

http://stackoverflow.com/a/52634116
answers question: http://stackoverflow.com/q/52633915
score: -1
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/92201842
has body: your inner while loop is causing the issue: max = 5 #Input miles to be converted for counter in range(max): miles = float(input('Enter the number of miles to convert to kilometers: ')) milesToKms = miles*1.6 #miles to kilometers formula if miles &gt;= 0: print ('Miles converted: ', miles) print ('Kilometers: ', milesToKms) #display kilometers result break elif miles &lt;0: print ('Invalid value entered.') if counter == (max - 1): print ('Too many invalid entries submitted.') exit () Valid output: Enter the number of miles to convert to kilometers: 10 ('Miles converted: ', 10.0) ('Kilometers: ', 16.0) Invalid output: Enter the number of miles to convert to kilometers: -1 Invalid value entered. Enter the number of miles to convert to kilometers: -2 Invalid value entered. Enter the number of miles to convert to kilometers: -3 Invalid value entered. Enter the number of miles to convert to kilometers: -4 Invalid value entered. Enter the number of miles to convert to kilometers: -5 Invalid value entered. Too many invalid entries submitted.
upvote count: 0
has comment: http://stackoverflow.com/comment/92201602

http://stackoverflow.com/a/52699165
has comment: http://stackoverflow.com/comment/92325390
upvote count: 1
has comment: http://stackoverflow.com/comment/92324905
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92335342
has body: You can use BeautifulSoup: data = '''<?xml version="1.0" encoding="UTF-8"?> <client name="123" group="457" /> <lab symbol="xyz/ght" sources="SBS,TCS,DDT" /> <lab symbol="pqr/xyz" sources="RRT,QQR,XXC" /> <lab symbol="xyz/ght" sources="GHB,GRT,BNM" /> ''' soup = BeautifulSoup(data, 'lxml') result = [j['sources'] for i in soup.find_all('group', {'name': '457'}) for j in i.find_all('lab')] result #['SBS,TCS,DDT', 'RRT,QQR,XXC'] And this would do the same using xml: import xml.etree.ElementTree as ET data = '''<?xml version="1.0" encoding="UTF-8"?> <client name="123" group="457" /> <lab symbol="xyz/ght" sources="SBS,TCS,DDT" /> <lab symbol="pqr/xyz" sources="RRT,QQR,XXC" /> <lab symbol="xyz/ght" sources="GHB,GRT,BNM" /> ''' tree = ET.fromstring(data) result = [j.attrib['sources'] for i in tree.findall('group') if i.attrib['name'] == '457' for j in i.findall('lab')] result #['SBS,TCS,DDT', 'RRT,QQR,XXC']
accepted answer of: http://stackoverflow.com/q/52698840
answers question: http://stackoverflow.com/q/52698840

service
tags question: http://stackoverflow.com/q/52713401
tag name: service
tags question: http://stackoverflow.com/q/52698395
type: Tag

http://stackoverflow.com/q/52635866
favorite count: 0
has title: How to add a conda environment in jupyter
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
score: 2
has answer: http://stackoverflow.com/a/54056539
upvote count: 2
has answer: http://stackoverflow.com/a/52636245
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52636522
tagged with: conda
answer count: 3
has body: I'm try to enable a keras environmnt into jupyter. Using below commands I added the conda tf environment for Keras : C:&gt;conda create --name tf python=3.5 C:&gt;activate tf (tf) C:\Keras\Test&gt;pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.4.0-cp35-cp35m-win_amd64.whl Next I downloaded Keras-2.1.3-py2.py3-none-any.whl (from : https://repo.continuum.io/archive/) And successfully installed it. (tf) C:\Keras&gt;pip install --ignore-installed --upgrade C:\Keras\Keras-2.1.3-py2.py3-none-any.whl But then when i type (tf) c:\Keras\Jupyter Notebook . I would have thought to be able to 'switch' to the tf keras environment. When starting up the web browser But all I see in below jupyter page is the python 3 environment which doesn't know of keras. So shouldn't I see a "tf" environment here as well? from both environments i can start the jupyter notebook, but not sure if that should make a difference, both startups dont show tf, am i missing something here?. (in the picture i also show both conda consoles) When i try to launch a notebook that makes use of keras. Then this is the error i see like if it wasnt installed ?. (i'm sure it did though). . However a small test in python ran directly from the console proves keras is installed and working (but why not in jupyter??)
downvote count: 0
tagged with: keras

http://stackoverflow.com/comment/92411401
score: 1
has text: Have you tried changing the formatter on the fly ?
comment on: http://stackoverflow.com/q/52743317
type: Comment
type: QuestionComment

arrays
tags question: http://stackoverflow.com/q/52674292
tags question: http://stackoverflow.com/q/52693307
tags question: http://stackoverflow.com/q/52746193
tags question: http://stackoverflow.com/q/52745546
tags question: http://stackoverflow.com/q/52715059
tags question: http://stackoverflow.com/q/52668862
type: Tag
tags question: http://stackoverflow.com/q/52590745
tags question: http://stackoverflow.com/q/52721198
tags question: http://stackoverflow.com/q/52640065
tags question: http://stackoverflow.com/q/52678108
tags question: http://stackoverflow.com/q/52740724
tags question: http://stackoverflow.com/q/52703473
tags question: http://stackoverflow.com/q/52623218
tags question: http://stackoverflow.com/q/52617197
tags question: http://stackoverflow.com/q/52686528
tags question: http://stackoverflow.com/q/52726553
tags question: http://stackoverflow.com/q/52625998
tags question: http://stackoverflow.com/q/52615339
tags question: http://stackoverflow.com/q/52658793
tags question: http://stackoverflow.com/q/52636882
tags question: http://stackoverflow.com/q/52672229
tags question: http://stackoverflow.com/q/52744812
tags question: http://stackoverflow.com/q/52655497
tags question: http://stackoverflow.com/q/52728944
tags question: http://stackoverflow.com/q/52600082
tags question: http://stackoverflow.com/q/52684993
tags question: http://stackoverflow.com/q/52731304
tags question: http://stackoverflow.com/q/52647097
tags question: http://stackoverflow.com/q/52721752
tags question: http://stackoverflow.com/q/52746840
tags question: http://stackoverflow.com/q/52708584
tags question: http://stackoverflow.com/q/52664583
tags question: http://stackoverflow.com/q/52688113
tags question: http://stackoverflow.com/q/52636288
tags question: http://stackoverflow.com/q/52594503
tags question: http://stackoverflow.com/q/52623692
tags question: http://stackoverflow.com/q/52641975
tags question: http://stackoverflow.com/q/52674923
tags question: http://stackoverflow.com/q/52714845
tags question: http://stackoverflow.com/q/52628445
tags question: http://stackoverflow.com/q/52732162
tag name: arrays
tags question: http://stackoverflow.com/q/52729080
tags question: http://stackoverflow.com/q/52652572
tags question: http://stackoverflow.com/q/52673075
tags question: http://stackoverflow.com/q/52729910
tags question: http://stackoverflow.com/q/52673285
tags question: http://stackoverflow.com/q/52656993
tags question: http://stackoverflow.com/q/52682288
tags question: http://stackoverflow.com/q/52665271
tags question: http://stackoverflow.com/q/52657097
tags question: http://stackoverflow.com/q/52600897
tags question: http://stackoverflow.com/q/52626708
tags question: http://stackoverflow.com/q/52598012
tags question: http://stackoverflow.com/q/52668072
tags question: http://stackoverflow.com/q/52649802
tags question: http://stackoverflow.com/q/52630771
tags question: http://stackoverflow.com/q/52623980
tags question: http://stackoverflow.com/q/52737821
tags question: http://stackoverflow.com/q/52690963
tags question: http://stackoverflow.com/q/52669198
tags question: http://stackoverflow.com/q/52606057
tags question: http://stackoverflow.com/q/52741192
tags question: http://stackoverflow.com/q/52615815
tags question: http://stackoverflow.com/q/52687901
tags question: http://stackoverflow.com/q/52602775
tags question: http://stackoverflow.com/q/52698784
tags question: http://stackoverflow.com/q/52731257
tags question: http://stackoverflow.com/q/52663040
tags question: http://stackoverflow.com/q/52636158
tags question: http://stackoverflow.com/q/52702859
tags question: http://stackoverflow.com/q/52670278
tags question: http://stackoverflow.com/q/52681762
tags question: http://stackoverflow.com/q/52654882
tags question: http://stackoverflow.com/q/52654607
tags question: http://stackoverflow.com/q/52638053
tags question: http://stackoverflow.com/q/52728623
tags question: http://stackoverflow.com/q/52609181
tags question: http://stackoverflow.com/q/52736698

http://stackoverflow.com/comment/92161418
type: QuestionComment
comment on: http://stackoverflow.com/q/52613320
score: 0
has text: So why are Noah and Liam removed for id = 4?
type: Comment

http://stackoverflow.com/q/52687300
has answer: http://stackoverflow.com/a/52687344
downvote count: 0
has answer: http://stackoverflow.com/a/52687334
has title: Average values in all dicts with matching values for a given key in python
type: Question
has body: I have a list of dictionnaries that all have the same keys. in_list = [{'index':1, 'value':2.}, {'index':1, 'value':3.}, {'index':2, 'value':4.}] I'd like to create a new dictionnary with the average on 'value' for each 'index'. out_dict = {1:2.5, 2:4.} What would be the most pythonic way to do this ? The following code does what I want, but I feel like it is clumsy tmp = {x:[] for x in range(1,3)} for el in in_list: tmp[el['index']].append(el['value']) for key, val in tmp.iteritems(): out_dict[key] = sum(val)/len(val)
has answer: http://stackoverflow.com/a/52687346
score: 4
possible better answer: http://stackoverflow.com/a/52687344
favorite count: 0
tagged with: python
upvote count: 4
tagged with: dictionary
has answer: http://stackoverflow.com/a/52687572
accepted answer: http://stackoverflow.com/a/52687572
answer count: 4
type: AnsweredQuestion

opencv
tags question: http://stackoverflow.com/q/52700417
type: Tag
tags question: http://stackoverflow.com/q/52741742
tags question: http://stackoverflow.com/q/52719183
tags question: http://stackoverflow.com/q/52635798
tags question: http://stackoverflow.com/q/52651116
tags question: http://stackoverflow.com/q/52591762
tags question: http://stackoverflow.com/q/52644348
tags question: http://stackoverflow.com/q/52737584
tags question: http://stackoverflow.com/q/52664390
tags question: http://stackoverflow.com/q/52669705
tags question: http://stackoverflow.com/q/52734646
tags question: http://stackoverflow.com/q/52591714
tags question: http://stackoverflow.com/q/52684552
tags question: http://stackoverflow.com/q/52655841
tags question: http://stackoverflow.com/q/52717068
tags question: http://stackoverflow.com/q/52714189
tags question: http://stackoverflow.com/q/52714649
tags question: http://stackoverflow.com/q/52595273
tags question: http://stackoverflow.com/q/52745343
tags question: http://stackoverflow.com/q/52617318
tags question: http://stackoverflow.com/q/52601312
tags question: http://stackoverflow.com/q/52676020
tags question: http://stackoverflow.com/q/52594121
tags question: http://stackoverflow.com/q/52651397
tags question: http://stackoverflow.com/q/52590814
tags question: http://stackoverflow.com/q/52716440
tags question: http://stackoverflow.com/q/52634009
tags question: http://stackoverflow.com/q/52679580
tags question: http://stackoverflow.com/q/52633705
tags question: http://stackoverflow.com/q/52677479
tags question: http://stackoverflow.com/q/52745254
tags question: http://stackoverflow.com/q/52727017
tags question: http://stackoverflow.com/q/52611958
tags question: http://stackoverflow.com/q/52714889
tags question: http://stackoverflow.com/q/52669123
tags question: http://stackoverflow.com/q/52678376
tags question: http://stackoverflow.com/q/52661209
tags question: http://stackoverflow.com/q/52661318
tags question: http://stackoverflow.com/q/52670538
tags question: http://stackoverflow.com/q/52670012
tag name: opencv
tags question: http://stackoverflow.com/q/52644763
tags question: http://stackoverflow.com/q/52606453
tags question: http://stackoverflow.com/q/52736914
tags question: http://stackoverflow.com/q/52668690
tags question: http://stackoverflow.com/q/52599641
tags question: http://stackoverflow.com/q/52603515
tags question: http://stackoverflow.com/q/52653346
tags question: http://stackoverflow.com/q/52667760
tags question: http://stackoverflow.com/q/52698544
tags question: http://stackoverflow.com/q/52743787
tags question: http://stackoverflow.com/q/52661025
tags question: http://stackoverflow.com/q/52703880
tags question: http://stackoverflow.com/q/52653441
tags question: http://stackoverflow.com/q/52745750
tags question: http://stackoverflow.com/q/52679970
tags question: http://stackoverflow.com/q/52736754
tags question: http://stackoverflow.com/q/52635539
tags question: http://stackoverflow.com/q/52612012
tags question: http://stackoverflow.com/q/52715727
tags question: http://stackoverflow.com/q/52653663
tags question: http://stackoverflow.com/q/52668674
tags question: http://stackoverflow.com/q/52683825
tags question: http://stackoverflow.com/q/52594956
tags question: http://stackoverflow.com/q/52663062
tags question: http://stackoverflow.com/q/52628369
tags question: http://stackoverflow.com/q/52734200
tags question: http://stackoverflow.com/q/52733998
tags question: http://stackoverflow.com/q/52712983
tags question: http://stackoverflow.com/q/52716785
tags question: http://stackoverflow.com/q/52605556
tags question: http://stackoverflow.com/q/52738605
tags question: http://stackoverflow.com/q/52627087
tags question: http://stackoverflow.com/q/52682261
tags question: http://stackoverflow.com/q/52702847
tags question: http://stackoverflow.com/q/52642977
tags question: http://stackoverflow.com/q/52640023
tags question: http://stackoverflow.com/q/52637807
tags question: http://stackoverflow.com/q/52679734

http://stackoverflow.com/a/52918442
has body: I'm not sure but maybe you can change keras_model.ckpt.index to keras_model.ckpt for test.
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52597523
downvote count: 0
type: Answer

http://stackoverflow.com/q/52683118
accepted answer: http://stackoverflow.com/a/52683142
type: AnsweredQuestion
score: -1
type: Question
has comment: http://stackoverflow.com/comment/92294363
has comment: http://stackoverflow.com/comment/92294332
has answer: http://stackoverflow.com/a/52683142
has body: I'm currently learning python. I've been wanting to learn code for awhile now, and I'm finally in a place where I can. I watch online tutorials, and after a few hours of that. I go to this website called code combat just for fun. But enough of that. Here is my code. hero.moveRight() hero.attack("Weak Door") hero.say("C'Mon, Follow me!") hero.moveRight(2) hero.moveDown(2) enemy = hero.findNearestEnemy() while True: if enemy: hero.attack(enemy) &lt;----Line 10 else: if not enemy: hero.moveXY(54, 22) On Line 10 is when everything heads south. It gets stuck and the character on the game says "But its already dead, then acts confused. I put in the "else:" to see if it fixed it, But it didn't. Im really new to this. Thanks for the help!
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
has title: Code gets stuck, and doesn't know what to do next?
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/92282312
type: Comment
comment on: http://stackoverflow.com/a/52676148
has text: Yeah, maybe i have told that i am using this command behind a proxy.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92194976
comment on: http://stackoverflow.com/a/52630486
type: Comment
score: 1
type: AnswerComment
has text: I'm not sure how `Shop`'s dtype would affect the code above (it's int in my interpreter as well). But if it's about the column renaming, then you could use something like what jpp did, and only rename the columns that start with `Week`...

http://stackoverflow.com/q/52622905
score: 6
has answer: http://stackoverflow.com/a/52633612
has comment: http://stackoverflow.com/comment/92181176
tagged with: python
upvote count: 6
answer count: 4
type: AnsweredQuestion
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/92185559
type: Question
linked to: http://stackoverflow.com/q/2987433
has comment: http://stackoverflow.com/comment/92180949
has comment: http://stackoverflow.com/comment/92182056
has title: Migrate csv from gcs to postgresql
has body: I'm trying to migrate csv files from Google Cloud Storage (GCS), which have been exported from BigQuery, to a PostgreSQL Google cloud sql instance using a python script. I was hoping to use the Google API but found this in the documentation: Importing CSV data using the Cloud SQL Admin API is not supported for PostgreSQL instances. As an alternative I could use psycopg2 library and stream the rows of the csv file into the SQL instance. I can do this three ways Line by line: Read each line and then submit the insert command and then commit Batch stream: Read each line and then submit the insert commands and then commit after 10 lines or 100 etc. The entire csv: Read each line and submit the insert commands and then only commit at the end of the document. My concerns are these csv files could contain millions of rows and running this process for any of the three options mentioned above seems like a bad idea to me. What alternatives do I have? Essentially I have some raw data in BigQuery on which we do some preprocessing before exporting to GCS in preparation for importing to the PostgreSQL instance. I need to export this preprocessed data from BigQuery to the PostgreSQL instance. This is not a duplicate of this question as I'm preferably looking for the solution which exports data from BigQuery to the PostgreSQL instance wether it be via GCS or direct.
possible better answer: http://stackoverflow.com/a/58135438
has answer: http://stackoverflow.com/a/52625365
has answer: http://stackoverflow.com/a/58135438
tagged with: google-cloud-platform
downvote count: 0
has comment: http://stackoverflow.com/comment/92181318
has comment: http://stackoverflow.com/comment/92181956
accepted answer: http://stackoverflow.com/a/52625365
favorite count: 0
tagged with: postgresql
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52625978

http://stackoverflow.com/comment/92200612
comment on: http://stackoverflow.com/q/52633719
score: 0
type: Comment
type: QuestionComment
has text: If you need to convert string date to datetime, you just need df['date'] = pd.to_datetime(df['date'])

http://stackoverflow.com/q/52687918
accepted answer: http://stackoverflow.com/a/52687985
score: 0
has comment: http://stackoverflow.com/comment/92303003
has answer: http://stackoverflow.com/a/52687974
has title: Python instance from class not initiating
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52687985
type: Question
has body: I'm learning python and currently working on exercises on classes. With this one, I can't figure out what's wrong. The instructions are: Write a class named Pets with the following attributes: name type age It should have an __init__ method creating these attributes and should also have the following methods: set_name to assign a value to name set_type to assign a value to type set_age to assign a value to age get_name to return the value of name get_type to return the value of type get_age to return the value of age Then, write a program that initiates an object and prompts the user to input name, type and age. Use the methods of the object to find the name, type, and age of the pet and show it on the screen. This is the code I've written: class Pet(): def __init__(self, name, type, age): self.name = name self.type = type self.age = age def set_name(self): name = input("Type in the pet's name: ") def set_type(self): type = input("Type in the pet's type: ") def set_age(self): age = int(input("Type in the pet's age: ")) def get_name(set_name): return set_name def get_type(set_type): return set_type def get_age(set_age): return set_age pet = Pet(set_name, set_type, set_age) I get a NameError: name 'set_name' is not defined. I've tried different arguments when creating the object from the Pet class. How should I define methods and arguments to get this to work?
answer count: 2
has comment: http://stackoverflow.com/comment/92303280
favorite count: 0
tagged with: class
has comment: http://stackoverflow.com/comment/92303021
possible better answer: http://stackoverflow.com/a/52687974

http://stackoverflow.com/comment/93084456
comment on: http://stackoverflow.com/a/52708591
has text: thanks to you answer
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92409409
has text: I'm still getting "NameError: name 'n' is not defined"
comment on: http://stackoverflow.com/a/52742321
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92401090
has text: Hmm first you don't need 'list(word)' as you can iterate over a string. Second, I do not see why it should not get negative. Third, if I get your definition right `aaaaaa` would be less diverse than `bbbbbb`. so wouldn't it be better to calculate a mean and a standard deviation for a word?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52738057

http://stackoverflow.com/comment/92379717
has text: You need to read the whole file in to make it work, but it *will* work. Remove `for item in w:`, and use `for match in re.findall(r'(?s)Hex-STRING:\s*(.+)', w.read()):`
comment on: http://stackoverflow.com/q/52726309
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52749425
has comment: http://stackoverflow.com/comment/92444892
score: 0
has comment: http://stackoverflow.com/comment/92423311
type: Answer
has body: You already handled the special case where i=0, so the loop should start at 1. The loop should iterate across all elements in a after 0, so it should count up to the last valid index in a. That is NOT len(a)+1. You attempt to assign it to b[i] which does not exist yet. Instead just append the number you calculated (or store it in a temporary variable for readability and to make debugging easier). You also get the last item in b incorrectly in your return statement. Again, len(b)+1 is not correct. (code intentionally not posted, as this is homework, but this should be enough to get you there)
answers question: http://stackoverflow.com/q/52746084

http://stackoverflow.com/a/52740999
has comment: http://stackoverflow.com/comment/92406937
type: Answer
has comment: http://stackoverflow.com/comment/92407038
upvote count: 2
has comment: http://stackoverflow.com/comment/92406753
score: 2
has comment: http://stackoverflow.com/comment/92406950
has comment: http://stackoverflow.com/comment/92407128
has body: There's a few ways to do this, but the first that comes to mind is to enumerate the elements with a starting index of 1 in a nested list comprehension. &gt;&gt;&gt; [[index for index, value in enumerate(sub, 1)] for sub in my_list] [[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
has comment: http://stackoverflow.com/comment/92407145
downvote count: 0
has comment: http://stackoverflow.com/comment/92407527
answers question: http://stackoverflow.com/q/52740958

http://stackoverflow.com/q/52734736
tagged with: bokeh
possible better answer: http://stackoverflow.com/a/52734943
tagged with: pypi
has answer: http://stackoverflow.com/a/52736035
type: Question
has answer: http://stackoverflow.com/a/52734943
has body: I installed bokeh via pip and here is the information of the versions that are installed pooja@X1-Carbon-6:~$ python3 --version Python 3.5.2 pooja@X1-Carbon-6:~$ python --version Python 2.7.12 pooja@X1-Carbon-6:~$ bokeh --version 0.13.0 for python2, it works fine and could import bokeh lkhr@X1-Carbon-6:~notebooks$ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import bokeh &gt;&gt;&gt; However, it complains when I use python3 olkhr@X1-Carbon-6:~$ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import bokeh Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'bokeh' &gt;&gt;&gt; I want to use bokeh in my Python3 Jupyter-Notebook and having problem cos of this, if any suggestions are available, please let me know. Many thanks,
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/52736035
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92394363
has comment: http://stackoverflow.com/comment/94349710
has title: How to install bokeh for Python3
has answer: http://stackoverflow.com/a/52755095
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: pip

http://stackoverflow.com/a/52607954
has body: What prevent you to directly find_all that element? from bs4 import BeautifulSoup import requests page = requests.get("http://www.freejobalert.com/upsc-recruitment/" "16960/#Engg-Services2019") c = page.content soup = BeautifulSoup(c,"html.parser") tables = soup.find_all("td", attrs={'colspan':'2'}) print(tables)
accepted answer of: http://stackoverflow.com/q/52606907
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52606907

http://stackoverflow.com/a/52653981
has body: You need to obtain the correct dimensions. This can be done using meshgrid. Also, your desired plot is a surface plot, not a wireframe (though you can do that too). # import for colormaps from matplotlib import cm x=np.linspace(-10,10, num=100) y=np.linspace(-10,10, num=100) x, y = np.meshgrid(x, y) z = np.exp(-0.1*x**2-0.1*y**2) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(x,y,z, cmap=cm.jet) plt.show()
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52653734
type: Answer
answers question: http://stackoverflow.com/q/52653734
score: 4
has comment: http://stackoverflow.com/comment/92239468
upvote count: 4

http://stackoverflow.com/a/56800562
score: 0
type: Answer
has body: I guest the jar file may has built-in import or dependencies,so the three jar files isn't enough.As to how to find out java jar dependent relations,that is what java maven do. You can see the official website "project build setup" for help. In my case,i follow official java project setup,use "from org.apache.flink.streaming.connectors.kafka import FlinkKafkaConsumer" and add dependency " org.apache.flink flink-clients_2.11 1.8.0 " to pom.xml,then i can output kafka records to stdout now with the Python API.
answers question: http://stackoverflow.com/q/52744277

http://stackoverflow.com/q/52672727
has body: I have binary vector of length n. [0, 0, 0, 1....] How do I delete the columns of a matrix of size n*m in numpy, which corresponds to the value 1's in the binary vector? Is there any simple or elegant ways of doing this?
downvote count: 1
score: -1
has answer: http://stackoverflow.com/a/52672790
type: Question
tagged with: numpy
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92283546
has comment: http://stackoverflow.com/comment/92275225
favorite count: 0
tagged with: python
type: UnansweredQuestion
has title: how to delete columns in numpy according to binary mask?

http://stackoverflow.com/a/52630980
has comment: http://stackoverflow.com/comment/92195846
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52629587
score: 0
has body: From what I understand you want to implement a function that selects all items, the solution is to iterate using the setSelected() method of QListWidget as shown below: import sys from PyQt4 import QtCore, QtGui class ListWidget(QtGui.QListWidget): def __init__(self, parent=None): super(ListWidget, self).__init__(parent) self.setSelectionMode(QtGui.QListWidget.MultiSelection) @QtCore.pyqtSlot() def selectAll(self): for i in range(self.count()): it = self.item(i) if it is not None: it.setSelected(True) @QtCore.pyqtSlot() def clearSelection(self): for i in range(self.count()): it = self.item(i) if it is not None: it.setSelected(False) class Widget(QtGui.QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) lay = QtGui.QVBoxLayout(self) button_sel = QtGui.QPushButton("Select All") button_unsel = QtGui.QPushButton("Clear Selection") self.list_widget = ListWidget() for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": it = QtGui.QListWidgetItem(letter) self.list_widget.addItem(it) button_sel.clicked.connect(self.list_widget.selectAll) button_unsel.clicked.connect(self.list_widget.clearSelection) lay.addWidget(button_sel) lay.addWidget(button_unsel) lay.addWidget(self.list_widget) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())
type: Answer
has comment: http://stackoverflow.com/comment/92195975
accepted answer of: http://stackoverflow.com/q/52629587
has comment: http://stackoverflow.com/comment/92195945

http://stackoverflow.com/comment/92355930
comment on: http://stackoverflow.com/q/52712655
type: Comment
type: QuestionComment
score: 0
has text: What makes you think the Embedding layer has no name parameter?

http://stackoverflow.com/q/52693799
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/92323187
score: 0
has body: source It is ok when I just use color like green. But when I use this with custom image for gradation effect, it seems it always shows black lines inside no matter what kind of image I put in. I have not touched any code. Only thing I've done was changing the source of the image. Is there anyway to get rid of that blurry black lines? Why do they appear? ''' ProgressSpinner =============== Android Lollipop style progress spinner. ''' from kivy.lang import Builder from kivy.core.image import Image as CoreImage from kivy.properties import NumericProperty, ListProperty, BoundedNumericProperty, StringProperty, ObjectProperty from kivy.animation import Animation from kivy.clock import Clock from kivy.properties import BooleanProperty from kivy.uix.widget import Widget Builder.load_string(''' &lt;ProgressSpinnerBase&gt;: _size: min(self.height, self.width) _rsize: self._size / 2. _stroke: max(0.1, self._rsize / 20. if self.stroke_width is None else self.stroke_width) _radius: self._rsize - self._stroke * 2. &lt;ProgressSpinner&gt;: canvas: Color: rgba: self.color Line: circle: (self.center_x, self.center_y, self._radius, self._angle_center + self._angle_start, self._angle_center + self._angle_end) width: self._stroke cap: 'none' &lt;TextureProgressSpinner&gt;: canvas: StencilPush Color: rgba: 1, 1, 1, 1 Line: circle: (self.center_x, self.center_y, self._radius, self._angle_center + self._angle_start, self._angle_center + self._angle_end) width: self._stroke cap: 'none' StencilUse Color: rgba: self.color Rectangle: pos: self.center_x - self._rsize, self.center_y - self._rsize size: self._size, self._size texture: self.texture StencilUnUse Color: rgba: 1, 1, 1, 1 Line: circle: (self.center_x, self.center_y, self._radius, self._angle_center + self._angle_start, self._angle_center + self._angle_end) width: self._stroke cap: 'none' StencilPop &lt;RotatingTextureProgressSpinner&gt;: canvas: PushMatrix Rotate: angle: -self._angle_center origin: self.center StencilPush Color: rgba…
type: UnansweredQuestion
has title: Black lines in Kivy.garden.progressspinner
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/92314396

http://stackoverflow.com/comment/92396996
type: Comment
type: QuestionComment
has text: If you want data to persist after exiting the program, you need to write it to a file in some way (and then load that file when starting the program). For example, JSON would be a good way to store a dictionary.
comment on: http://stackoverflow.com/q/52735995
score: 0

http://stackoverflow.com/q/52628387
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has title: How to configure label in tkinter
has answer: http://stackoverflow.com/a/52632088
tagged with: smtplib
score: 0
answer count: 1
favorite count: 0
tagged with: python
has body: I have this few lines code to send mail in tkinter, what i want to do is configure the label with sending in progress... when the mail is sending but the label don't configure and until when error is output before the label is configured. I want the label to configure that mail is sending then when it's done configure mail sent from tkinter import messagebox import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders import socket import tkinter as tk def my_second_mail(): try: l.config(text="sending in progress...") FROMADDR = "my@gmail.com" PASSWORD = "22@201" TOADDR = ['@yahoo.com', '@gmail.com'] CCADDR = ['fkfkf@gmail.com'] # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = 'BACK UP FILES' msg['From'] = FROMADDR msg['To'] = ', '.join(TOADDR) msg['Cc'] = ', '.join(CCADDR) body = "mail test" msg.attach(MIMEText(body, 'plain')) filename = ['facebook.png'] for n in filename: # l.config(text="sending in progress...") print(n) attachment = open(str(n), 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= " + n) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(FROMADDR, PASSWORD) server.sendmail(FROMADDR, TOADDR + CCADDR, msg.as_string()) server.quit() messagebox.showinfo("success", "mail sent", parent=root) l.config(text="mail sent...") except socket.gaierror: messagebox.showerror("no internet", "no internet connectivity") root = tk.Tk() root.geometry("600x400") canvas = tk.Canvas(root, width=200, height=200, background="dodger blue") canvas.pack(fill="both", expand=True) l = tk.Label(canvas, bg="dodger blue", fg="white") l.place(x=250, y=20) b= tk.Button(canvas, text="send mail", command=my_second_mail, width=25, fg='do…
tagged with: tkinter

http://stackoverflow.com/comment/92183532
comment on: http://stackoverflow.com/q/52623935
has text: Observed:DATE: 01/10/2018, VOUCHER: 001, SPECIFICATION: OIL , CREDIT: 0 ,DEBIT: 0 ,REMARKS :JOHN ,BALANCE :1800 Expected:DATE: 01/10/2018, VOUCHER: 001, SPECIFICATION: OIL , CREDIT: 0 ,DEBIT: 200 ,REMARKS :JOHN ,BALANCE :1800
score: 0
type: Comment
type: QuestionComment

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

http://stackoverflow.com/q/52682074
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52685975
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92293483
tagged with: flask-wtforms
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has title: Parsing dates using WTForms Flask - Python
score: 1
upvote count: 1
type: Question
tagged with: flask
has body: Hi So I've been using WTForms with success for a good period of time now. The problem is on how to parse dates. I've always used to assign variables according to form data as follows firstname = form.firstname.data This will store the user's input from the form data into my variable called "firstname", which works just fine, my problem is when it comes to dates. I have the following code WTForms Class class BookingForm(Form): start_date = DateField('Start Date', format='%m/%d/%Y') end_date = DateField('End Date', format='%m/%d/%Y') The booking route @app.route('/book/', methods=['GET','POST']) @login_required def book(): try: form = BookingForm(request.form) if request.method == "POST" and form.validate(): start_date = form.start_date.data end_date = form.end_date.data # I Have also tried form.start_date.data.strftime('%m-%d-%Y') with no luck ... The HTML Template {jinja} &lt;div class="col-md-4"&gt; {{ render_date_field(form.start_date) }} &lt;/div&gt; &lt;div class="col-md-4"&gt; {{ render_date_field(form.end_date) }} &lt;/div&gt; I am also using datetime in python from datetime import datetime I've been trying to follow many docs on how to parse a date into a variable from a user input form with no luck, Does anybody know the right syntax? Thanks
answer count: 1

http://stackoverflow.com/q/52707190
downvote count: 0
has answer: http://stackoverflow.com/a/52711137
favorite count: 0
tagged with: dask
type: Question
has comment: http://stackoverflow.com/comment/92343299
tagged with: pandas
tagged with: spyder
has comment: http://stackoverflow.com/comment/92342908
tagged with: python
has comment: http://stackoverflow.com/comment/92343247
tagged with: python-3.x
upvote count: 2
accepted answer: http://stackoverflow.com/a/52711137
has comment: http://stackoverflow.com/comment/92342747
answer count: 1
has title: Dask: why has CPU usage suddenly dropped?
has body: I'm doing some Monte Carlo for a model and figured that Dask could be quite useful for this purpose. For the first 35 hours or so, things were running quite "smoothly" (apart from the fan noise giving a sense that the computer was taking off). Each model run would take about 2 seconds and there were 8 partitions running it in parallel. Activity monitor was showing 8 python3.6 instances. However, the computer has become "silent" and CPU usage (as displayed in Spyder) hardly exceeds 20%. Model runs are happening sequentially (not in parallel) and taking about 4 seconds each. This happened today at some point while I was working on other things. I understand that depending on the sequence of actions, Dask won't use all cores at the same time. However, in this case there is really just one task to be performed (see further below), so one could expect all partitions to run and finish more or less simultaneously. Edit: the whole set up has run successfully for 10.000 simulations in the past, the difference now being that there are nearly 500.000 simulations to run. Edit 2: now it has shifted to doing 2 partitions in parallel (instead of the previous 1 and original 8). It appears that something is making it change how many partitions are simultaneously processed. Edit 3: Following recommendations, I have used a dask.distributed.Client to track what is happening, and ran it for the first 400 rows. An illustration of what it looks like after completing is included below. I am struggling to understand the x-axis labels, hovering over the rectangles shows about 143 s. Some questions therefore are: Is there any relationship between running other software (Chrome, MS Word) and having the computer "take back" some CPU from python? Or instead, could it be related to the fact that at some point I ran a second Spyder instance? Or even, could the computer have somehow run out of memory? But then wouldn't the command have stopped running? ... any other possible explanation? Is it poss…
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/92309511
score: 0
has text: Would you able to initiate a child _browser_ embedded within another parent _browser_ manually?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52691203

http://stackoverflow.com/comment/92312895
has text: WAY easier than c++! You just lose gobs of performance with python. I LOVE it, but I don't need gobs of speed most times.
type: AnswerComment
comment on: http://stackoverflow.com/a/52692918
score: 0
type: Comment

http://stackoverflow.com/a/52602802
has body: In Octave ,I guess also in MATLAB, you can do: for ij = [{1;2} {2;3} {3;4} {4;5} {5;6} {6;7}] a(ij{:}) = 1; end But in general In MATLAB and Python it is better to prevent loops. There are much efficient indexing methods both in Python and MATLAB.
upvote count: 1
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52602592
type: Answer

http://stackoverflow.com/q/52640065
linked to: http://stackoverflow.com/q/45313301
answer count: 1
downvote count: 0
favorite count: 0
has title: Remove numpy rows contained in a list?
tagged with: python
has comment: http://stackoverflow.com/comment/92214605
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: set
type: Question
tagged with: numpy
has body: I have a numpy array and a list. I want to remove the rows contained in the list. a = np.zeros((3, 2)) a[0, :] = [1, 2] l = [(1, 2), (3, 4)] Currently I try to do this by making a set of a's rows, then exclude the set created from l, something like: sa = set(map(tuple, a)) sl = set(l) np.array(list(sa - sl)) or more simply sl = set(l) np.array([row for row in list(map(tuple, a)) if row not in sl] These work pretty well when each row is short. Is there a faster way? I need to optimize for speed.
tagged with: performance
has comment: http://stackoverflow.com/comment/92212874
tagged with: arrays
has answer: http://stackoverflow.com/a/52640331
accepted answer: http://stackoverflow.com/a/52640331

http://stackoverflow.com/comment/92249484
has text: @Jean-FrançoisFabre That's what the `(?i)` is for
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52659033
type: AnswerComment

http://stackoverflow.com/comment/92376722
type: Comment
type: QuestionComment
score: 0
has text: Looks like the current version has some known issues, they are working on it right now, maybe try the latest pull https://github.com/pypa/pipenv/issues/2950
comment on: http://stackoverflow.com/q/52725517

http://stackoverflow.com/q/52633279
answer count: 3
downvote count: 0
favorite count: 0
tagged with: tuples
type: UnansweredQuestion
tagged with: python
score: 2
has body: I am kind of new to python and currently struggling with returning the list of tuples in a way I want to. If I have a list of tuples that looks like [('a',),('b',),('c',),('d',),('e',),('f',)] How can I change it to [('a','b'),('c','d'),('e','f')] or [('a','b','c'),('d','e'),('f',)] ? Is there an easy way to regroup tuples? Any help would be appreciated.
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/52633501
has answer: http://stackoverflow.com/a/52633400
has title: Python tuples regrouping
has answer: http://stackoverflow.com/a/52633367

yahoo
type: Tag
tags question: http://stackoverflow.com/q/52639381
tag name: yahoo

http://stackoverflow.com/comment/92338769
type: QuestionComment
has text: At first glance I'd guess you need to indent the 'break' to the same level as the 'money = 0' in the 'else.'
score: 2
type: Comment
comment on: http://stackoverflow.com/q/52706139

http://stackoverflow.com/q/52721662
tagged with: unsupervised-learning
has answer: http://stackoverflow.com/a/62167763
type: Question
has answer: http://stackoverflow.com/a/52735568
tagged with: k-means
tagged with: cluster-analysis
answer count: 3
downvote count: 0
score: 8
has answer: http://stackoverflow.com/a/52721794
favorite count: 0
accepted answer: http://stackoverflow.com/a/52735568
upvote count: 8
has body: I have a database of images that contains identity cards, bills and passports. I want to classify these images into different groups (i.e identity cards, bills and passports). As I read about that, one of the ways to do this task is clustering (since it is going to be unsupervised). The idea for me is like this: the clustering will be based on the similarity between images (i.e images that have similar features will be grouped together). I know also that this process can be done by using k-means. So the problem for me is about features and using images with K-means. If anyone has done this before, or has a clue about it, please would you recommend some links to start with or suggest any features that can be helpful.
tagged with: python
tagged with: computer-vision
possible better answer: http://stackoverflow.com/a/52721794
type: AnsweredQuestion
has title: Clustering images using unsupervised Machine Learning

http://stackoverflow.com/a/52619210
has body: Navigating to /var/log/rabbitmq/rabbit@[server-name].log and scrolling back to when the issue first occurred led me to this message Disk free space limit now exceeded. Free bytes:999378944 Limit:1000000000. Turns out the hard drive was filled to the brim, which was causing all sorts of trouble for RabbitMQ and Celery, it seems. Freeing up space resolved all issues entirely.
has comment: http://stackoverflow.com/comment/92197844
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92190016
accepted answer of: http://stackoverflow.com/q/52616841
answers question: http://stackoverflow.com/q/52616841
type: Answer
score: 0

http://stackoverflow.com/q/52655757
score: 8
upvote count: 8
tagged with: python
has title: Error printing variables while debugging Cython
type: AnsweredQuestion
tagged with: cython
tagged with: pdb
type: Question
tagged with: gdb-python
has answer: http://stackoverflow.com/a/53175953
tagged with: gdb
downvote count: 0
answer count: 1
has body: I'm trying to debug some Cython code with gdb that is wrapping C++ code to be called from Python. I followed the instructions in the documentation but I'm getting some errors while debugging that are unrelated to my code. Example: (gdb) cy print some_variable Python Exception &lt;type 'exceptions.AttributeError'&gt; 'PyDictObjectPtr' object has no attribute 'items': Error occurred in Python: 'PyDictObjectPtr' object has no attribute 'items' I'm also getting this one sometimes (usually after the first one): Python Exception &lt;class 'gdb.error'&gt; There is no member named ob_sval.: Error occurred in Python command: There is no member named ob_sval. To debug the code I created an environment with Docker: FROM debian RUN apt-get update &amp;&amp; apt-get upgrade -y &amp;&amp; apt-get install -y \ build-essential gdb-python2 python-dbg python-dev \ python-pip python-numpy-dbg RUN pip install cython pygments CMD bash I found two related posts in the cython-users google group but with no answer.
accepted answer: http://stackoverflow.com/a/53175953
favorite count: 0

http://stackoverflow.com/comment/92273538
comment on: http://stackoverflow.com/a/52671497
type: Comment
score: 0
has text: I get the error: ImportError: No module named indexes.base when reading the pickle
type: AnswerComment

http://stackoverflow.com/a/52637851
answers question: http://stackoverflow.com/q/52637669
has body: You could create a filtered list that only will hold 2 or 3 and test that, if any(filtered_list) means it contains a 2 or 3 and True will be returned if not False def has23(num): return any([*filter(lambda x: x == '2' or x == '3', str(num))]) print(has23(21)) # =&gt; True print(has23(83)) # =&gt; True print(has23(54)) # =&gt; False
score: 0
type: Answer

http://stackoverflow.com/q/52662735
score: 1
type: Question
tagged with: numpy
has title: Accessing a pandas string column characters based on indices in a series or array
tagged with: dataframe
has answer: http://stackoverflow.com/a/52662912
tagged with: pandas
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52662912
type: AnsweredQuestion
has body: I have a pandas dataframe column (series) containing indices to a single character of interest inside the string elements of another column. Is there a way for me to access these characters of interest based on the index column in a vectorized manner, similar to the dataframe['name'].str.* functions? [edit: see comment below] If not (or regardless, really), what would you say is the preferred approach here? [Edit: this assumption was wrong, as pointed out by jpp, but I'm leaving it here for traceability] I'm trying to avoid being unnecessarily verbose, such as applying a translation function using map or having to construct a separate indexing recipe (like a dictionary containing the indices) in order to do something like myDataFrame['myDesiredResult'] = myDataFrame['myStrCol'].apply(myCharacterExtractionFunction, myIndexingRecipe) I'd prefer sticking to numpy and pandas and not mix in more modules if at all possible. Illustration of what the data might look like: myStrCol myIndices myDesiredResult 0 ABC 1 B 1 DEF 0 D 2 GHI 2 I Also, and maybe useful in order to get an understanding of how the numpy array is actually behaving inside the pandas wrapper, it would be great if someone could explain if it makes a difference to have a separate numpy array containing the indices, like this: import pandas import numpy myPandasStringSeries = pandas.Series(['ABC', 'DEF', 'GHI']) myPandasStringSeries 0 ABC 1 DEF 2 GHI myNumpyIndexArray = numpy.array([1, 0, 2]) myNumpyIndexArray array([1, 0, 2]) It seems to me that what I want is very similar to this suggestion relating to substrings but there doesn't seem to be a solution there yet. Apart from that, all I have found relates to the Series.str methods which operate using the same parameter for all elements of the Series like so: myDataFrame['newColumn'] = myDataFrame['oldColumn'].str.split('_').str.get(0)

http://stackoverflow.com/a/52691477
upvote count: 2
type: AcceptedAnswer
has body: You should use csv module on the Python standard library. Here is a simpler solution: import requests import csv from bs4 import BeautifulSoup as bs url = requests.get("https://www.top500.org/list/2018/06") soup = bs(url.content, 'html.parser') filename = "computerRank10.csv" csv_writer = csv.writer(open(filename, 'w')) for tr in soup.find_all("tr"): data = [] # for headers ( entered only once - the first time - ) for th in tr.find_all("th"): data.append(th.text) if data: print("Inserting headers : {}".format(','.join(data))) csv_writer.writerow(data) continue for td in tr.find_all("td"): if td.a: data.append(td.a.text.strip()) else: data.append(td.text.strip()) if data: print("Inserting data: {}".format(','.join(data))) csv_writer.writerow(data)
has comment: http://stackoverflow.com/comment/92310569
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92310728
accepted answer of: http://stackoverflow.com/q/52690994
answers question: http://stackoverflow.com/q/52690994
has comment: http://stackoverflow.com/comment/92310081

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

http://stackoverflow.com/a/52591509
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52591339
type: Answer
accepted answer of: http://stackoverflow.com/q/52591339
has body: Alternatively, you can also use the built-in filter function like this: List_main = ['a','b','c','d','e','f','g','h'] List_sub = ['c','f','d'] sub_filter = lambda x: x not in List_sub list_joined = list(filter(sub_filter, List_main)) + List_sub This will output ['a', 'b', 'e', 'g', 'h', 'c', 'f', 'd'].

http://stackoverflow.com/q/52592578
upvote count: 0
has body: I am trying to get a list of singles released in 2018 from allmusic.com. It is easy enough to go to their advanced search page and input those parameters, but then I would have to copy and paste the information by hand. All the information is in the html, but it has be generated by clicking the search button and the page navigation buttons. The url itself doesn't change. That puts it well out of my ability to crawl via my limited beautiful soup skills. Does anyone know how to web crawl java script generated html?
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52592682
downvote count: 3
answer count: 1
tagged with: javascript
score: -3
tagged with: web-crawler
has answer: http://stackoverflow.com/a/52592682
has title: web crawling pages with JS events
type: AnsweredQuestion

http://stackoverflow.com/q/52617611
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/42052356
downvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/52617700
has body: I am trying to wrap my head around Python multithreading by running some examples, and here is one whose behavior I don't quite understand #!python3.6 import threading import time class ThreadClass(): def __init__(self): self.thread = threading.Thread(target=self.callback) self.thread.start() def __del__(self): print("DESTROYED") def callback(self): print("start second thread") print("second threadId=", threading.get_ident()) print("self memory=", id(self)) time.sleep(2) print("stop second thread") def run(): print("start first thread") print("first threadId=", threading.get_ident()) thread = ThreadClass() print("threadClass memory=",id(thread)) print("stop first thread") run() print("end") The output I get is: start first thread first threadId= 140301467088640 start second thread second threadId= 140301462193920 self memory= 140301465746680 threadClass memory= 140301465746680 stop first thread end stop second thread DESTROYED What I don't understand is why the ThreadClass instance is not destroyed as soon as the run() function ends. My understanding is that instance of ThreadClass is on the stack of run(), so when run() ends, should its stack be cleared &amp; and the intstance deleted? But somehow that same instance of ThreadClass is left alive until another thread somewhere else in memory is done with it. In other words, how does Python share memory between threads?
has answer: http://stackoverflow.com/a/52617809
has title: How do threads share references to an instance?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92169613
score: 1

http://stackoverflow.com/comment/92395557
type: QuestionComment
has text: Possible duplicate of [Transpose list of lists](https://stackoverflow.com/questions/6473679/transpose-list-of-lists)
score: 4
comment on: http://stackoverflow.com/q/52735310
type: Comment

http://stackoverflow.com/q/52722996
tagged with: python
has comment: http://stackoverflow.com/comment/92371774
upvote count: 4
has answer: http://stackoverflow.com/a/52724328
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52723261
downvote count: 0
has answer: http://stackoverflow.com/a/52723114
type: Question
answer count: 8
has comment: http://stackoverflow.com/comment/92372453
has comment: http://stackoverflow.com/comment/92371343
has answer: http://stackoverflow.com/a/52725501
has title: Using strip() to remove only one element
linked to: http://stackoverflow.com/q/931092
has answer: http://stackoverflow.com/a/52723042
score: 4
accepted answer: http://stackoverflow.com/a/52723042
has answer: http://stackoverflow.com/a/52723242
has answer: http://stackoverflow.com/a/52723261
has body: I have a word within two opening and closing parenthesis, like this ((word)). I want to remove the first and the last parenthesis, so they are not duplicate, in order to obtain something like this: (word). I have tried using strip('()') on the variable that contains ((word)). However, it removes ALL parentheses at the beginning and at the end. Result: word. Is there a way to specify that I only want the first and last one removed?
has answer: http://stackoverflow.com/a/79461266
favorite count: 0
has answer: http://stackoverflow.com/a/52723116

http://stackoverflow.com/a/52742572
has comment: http://stackoverflow.com/comment/93241835
has comment: http://stackoverflow.com/comment/93241729
score: 5
upvote count: 5
downvote count: 0
type: Answer
has body: You can clone the repository from your jupyter notebook using bash. Run in your cell: %%bash git clone https://github.com/voice32/stock_market_indicators This will clone the stock_market_indicators repository to your directory. You will now be able to access the functions in your indicators.py file. You can import it by running in jupyter: %load stock_market_indicators/indicators.py
answers question: http://stackoverflow.com/q/52741983

http://stackoverflow.com/comment/92308910
comment on: http://stackoverflow.com/q/52690001
score: 0
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/181436/discussion-between-keshavgarg-and-phplover).
type: QuestionComment

http://stackoverflow.com/q/52641110
tagged with: python
has answer: http://stackoverflow.com/a/52641326
has body: I was checking the message flashing in flask framework from here. This is a basic example where a template file (Index.html) is used to provide the initial link and another template file (Login.html) creates the form. The files are: Login.html: Login {% if error %} Error: {{ error }} {% endif %} Username: Password: Index.html: Flask Message flashing {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} <li<{{ message }} {% endfor %} {% endif %} {% endwith %} Flask Message Flashing Example Do you want to log in? Flash.py: from flask import Flask, flash, redirect, render_template, request, url_for app = Flask(__name__) app.secret_key = 'random string' @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods = ['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or \ request.form['password'] != 'admin': error = 'Invalid username or password. Please try again!' else: flash('You were successfully logged in') return redirect(url_for('index')) return render_template('login.html', error = error) if __name__ == "__main__": app.run(debug = True) The part that is confusing me is inside index.html. It's using with messages = get_flashed_messages() to get the messages from the session. I do not fully understand why it's using with? I know with is used for resources, files, streams etc to control the closing procedure (and for not leaving something open when something goes wrong etc). What's the resource it's accessing using with in this context? I tried removing it (in this context) and an error occurred: jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'messages'. Also, example use cases from programcreek.com does not use with with get_flashed_messages so what's the case here?
has title: Use of with for getting flashed messages in flask
duplicate of: http://stackoverflow.com/q/29549259
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52641370
accepted answer: http://stackoverflow.com/a/52641370
possible better answer: http://stackoverflow.com/a/52641326
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/29549259
tagged with: flask
score: 0

http://stackoverflow.com/comment/92305392
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52689225
score: 0
has text: Is it possible to both calculate the horizontal and vertical to print both calculations?

http://stackoverflow.com/comment/92383792
type: Comment
score: 2
has text: I would use the `date` object of the `datetime` module. Probably not allowed, but here you also have to take leap years into account, etc. and some calendars even changed through time, making it very hard to parse it correctly without any error. For example, before 8 BC, a leap year took place every three years.
type: QuestionComment
comment on: http://stackoverflow.com/q/52729318

http://stackoverflow.com/q/52593482
has answer: http://stackoverflow.com/a/52593526
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92121938
score: 1
has body: The question is not about algorithms or fixing an error in code. I just want to make it clear how tracking time works. For example, there's line: x = my_func(4, 2) * time() The line run at 3.0 second and my_func(4, 2) takes 0.5 seconds to return the result. The question is when does time() start tracking time? At 3.0 second, when the line runs? Or at 3.5, after my_func(4, 2) is calculated?
has title: Which point in time does time() measure, relative to execution of a statement it's in?
type: Question
accepted answer: http://stackoverflow.com/a/52593526
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/q/52680031
has comment: http://stackoverflow.com/comment/92288806
has comment: http://stackoverflow.com/comment/92288731
tagged with: python
has comment: http://stackoverflow.com/comment/92288787
answer count: 0
linked to: http://stackoverflow.com/q/34399172
has comment: http://stackoverflow.com/comment/92288742
type: Question
has comment: http://stackoverflow.com/comment/92288664
has comment: http://stackoverflow.com/comment/92288701
tagged with: byte-order-mark
has comment: http://stackoverflow.com/comment/92288652
score: 0
has comment: http://stackoverflow.com/comment/92288708
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1
has body: I am importing data from a csv. The first line of data is bringing in "ï»¿0". The first line in the csv is 0 and I made sure that nothing was in front of the numbers. How can i get rid of ï»¿ ? with open('C:\\Users\jez40\Desktop\Tide_Data.csv', 'r') as data_file: data = csv.reader(data_file, delimiter=',') for i in data: t = i[0] here are the first few lines of the csv: 0, 1388.143433 5, 1388.143433 10, 1388.14624 15, 1388.147217 20, 1388.150024
favorite count: 0
has comment: http://stackoverflow.com/comment/92288803
has title: Importing Data from CSV without Byte Order Markers
type: UnansweredQuestion

http://stackoverflow.com/comment/92405644
score: 0
type: AnswerComment
has text: Thank you for the answer. But if I a webpage will send in an api request with the Item name and I need to return the 'RelatedItem' and 'CountinInventory' then the mask based option wouldn't be a good one right? I am curious. Do you think just returning the output values like 'Phone cover' and '20' alone is possible
comment on: http://stackoverflow.com/a/52738642
type: Comment

http://stackoverflow.com/a/52603237
type: Answer
has body: Filter out the empty strings, then simply join by ' '. &gt;&gt;&gt; address = ['63-1','STREET APT #3F','','NY'] &gt;&gt;&gt; ' '.join(filter(None, address)) '63-1 STREET APT #3F NY' filter(None, Iterable) will filter out all falsy values. In a list of strings, only the empty string is falsy.
upvote count: 4
answers question: http://stackoverflow.com/q/52603206
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/52603206
type: AcceptedAnswer

http://stackoverflow.com/q/52598126
has body: I have a pandas data frame which looks like below: ID Value 1 2 2 6 3 3 4 5 I want a new dataframe which gives ID Value 1 0 1 1 1 2 2 0 2 1 2 2 2 3 2 4 2 5 2 6 3 1 3 2 3 3 3 4 Any kind of suggestions would be appreciated.
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52598230
upvote count: 3
has answer: http://stackoverflow.com/a/52598230
has answer: http://stackoverflow.com/a/52598384
downvote count: 1
type: Question
tagged with: algorithm
tagged with: dataframe
has answer: http://stackoverflow.com/a/52598189
answer count: 3
tagged with: pandas
has title: Filling in sequence previous values based on current value in pandas
accepted answer: http://stackoverflow.com/a/52598189
favorite count: 0

http://stackoverflow.com/q/52712201
has comment: http://stackoverflow.com/comment/92364144
answer count: 1
has comment: http://stackoverflow.com/comment/92640686
tagged with: utf-8
has comment: http://stackoverflow.com/comment/92380638
has comment: http://stackoverflow.com/comment/92635158
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52722637
has comment: http://stackoverflow.com/comment/92637271
type: UnansweredQuestion
has title: Python importing .csv files in utf-8 or cp1252
downvote count: 2
tagged with: python
has body: I asked a question a while back about dealing with import of .csv files with special characters. At the time I was interested in solving the 90% case, but now I'm back for the last 10%. It's mostly the same setup as before: Many input files All .csv New: Now I want to preserve special characters in some inputs. However, I don't have control over the format of all of my input files, so I have a mix of files that I need to process. My attempt at the solution was to pass a keyword argument when I want to do a different encoding format. Here is the code: import csv import unicodecsv #&lt;Lots of other declarations and initialization&gt; def _csv_dict(self, file,index_field, ScrubMe, **kwargs): #some irrelevant initialization stuff here. if 'formatting' in kwargs: formatting = kwargs['formatting'] else: formatting = None #cp1252 is OS default with open(file, encoding=formatting, errors='ignore') as f: #newline = '', if formatting == None: reader = csv.DictReader(f, dialect = 'excel') else: #assume for now UTF-8 is the only other supported format reader = unicodecsv.DictReader(f, dialect = csv.excel) for line in reader: &lt;do some stuff - it's mostly building dictionaries, but I generally edit the data to only keep the stuff I care about and do a little data transformation to standard formats &gt; The result of the above is that if I pass an Excel file saved as a .CSV in native codec, the import works. However, the unicodecsv file with call including formatting='utf-8' keyword arg crashes The error message suggests that I'm passing the wrong type of object somewhere along the line. This happens the first time I attempt to read a line out of the UTF-8 file File "C:\Users\&lt;me&gt;\AppData\Local\Programs\Python\Python37\lib\site- packages\unicodecsv\py3.py", line 51, in &lt;genexpr&gt; f = (bs.decode(encoding, errors=errors) for bs in f) AttributeError: 'str' object has no attribute 'decode' From what I have read, UTF-8 is actually tab-separated instead of comma-separated…
has comment: http://stackoverflow.com/comment/92417336
upvote count: 1
has comment: http://stackoverflow.com/comment/92350848
type: Question
score: -1
has comment: http://stackoverflow.com/comment/92412586
linked to: http://stackoverflow.com/q/52087219
tagged with: file-io
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/92448263
type: AnswerComment
comment on: http://stackoverflow.com/a/52724841
type: Comment
has text: @MarioValentino: My assumption would be that you're intermingling this with other data transmissions, and mistaking part of the end of one transmission for the beginning of the length field of the next. Am I correct that you're sending data beyond just file length and data? Given your original design (where you assumed sending 10 bytes at a time from the client would receive 10 bytes at a time on the server, which is a bad assumption), it's highly likely you're picking up random bytes from earlier `send`s on the same socket that weren't properly `recv` when they were intended to be received.
score: 1

http://stackoverflow.com/a/66589828
accepted answer of: http://stackoverflow.com/q/52706998
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52706998
type: Answer
has body: This post gets decent traffic so I just want to let everyone know I never found the answer to this question. I tried a variety of configurations but ultimately flushing seems to rely more on the hardware itself than the software. I did end up transitioning to the code I mentioned and it seemed to help, albeit slightly. So I would recommend something like this: def send_cmd(self, cmd_to_send): self.ser.reset_output_buffer() self.ser.reset_input_buffer() self.ser.write(cmd_to_send) self.receive_cmd() def receive_cmd(self): # Read logic below If anyone can supply a better answer, I would still appreciate it :) Edit: I also was reading bytes individually, as I needed to. You may have more success using readlines() as Eduardo mentioned in the other answer.
score: 0

http://stackoverflow.com/q/52665890
tagged with: mysql-python
tagged with: ssh
has comment: http://stackoverflow.com/comment/92265882
tagged with: ssh-tunnel
tagged with: python-3.x
has body: I am trying to connect mysql db by ssh tunneling using python module "sshtunnel" but it is throwing an error like: mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'sql_user_name'@'172.45.678.910' (using password: YES) here is my code import mysql.connector import sshtunnel with sshtunnel.SSHTunnelForwarder( (ssh_host,ssh_port), ssh_username = ssh_username, ssh_pkey = ssh_pkey_path, remote_bind_address=(sql_host, sql_port), local_bind_address=("127.0.0.1",8080)) as server: mydb = mysql.connector.connect(host=sql_host,user=sql_user_name,password=sql_pwd,db=db_name) myCursor = mydb.cursor() my user_name and password is correct, I can successfully connect via sequal_pro using same credential and same ssh host, so why it is throwing an error here? and in error message which ssh_host('172.45.678.910') it is showing is also different, I never use this ssh_host in code,in variable "ssh_host" the ip is different, I tried all the solution available on the internet, but could not solve this issue
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/92265984
type: Question
has comment: http://stackoverflow.com/comment/92267695
has title: Python sshtunnel module failed to connect mysql db

http://stackoverflow.com/q/52628272
score: 0
has answer: http://stackoverflow.com/a/52628675
tagged with: scikit-learn
has body: I did created a scikit model which is similar to this. But now I want to extract two outputs. I don't know how to pass this while training. I did tried similar to Keras. [y,z] as list. But its not working in scikit. Did anyone tried this before? import numpy as np from sklearn import linear_model X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) Y = np.array([1, 1, 2, 2]) Z = np.array([1, 1, 2, 2]) clf = linear_model.SGDClassifier(max_iter=1000) clf.fit(X, [Y, Z]) Output: ValueError: bad input shape (2, 4)
tagged with: gradient-descent
tagged with: classification
has answer: http://stackoverflow.com/a/52628591
tagged with: python
has title: multiple output prediction from sklearn sgd classifer?
accepted answer: http://stackoverflow.com/a/52628675
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52628591
tagged with: machine-learning
type: Question
answer count: 2

http://stackoverflow.com/comment/92153188
type: Comment
comment on: http://stackoverflow.com/a/52609440
score: 0
has text: that's great info, but this doesn't work on numpy arrays, right?
type: AnswerComment

http://stackoverflow.com/a/52629902
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/113981871
score: 17
has comment: http://stackoverflow.com/comment/92195956
has comment: http://stackoverflow.com/comment/113245711
has comment: http://stackoverflow.com/comment/113267403
type: Answer
has comment: http://stackoverflow.com/comment/92196147
has body: One solution, as you mentioned, is to one-hot encode the categorical data (or even use them as they are, in index-based format) and feed them along the numerical data to an LSTM layer. Of course, you can also have two LSTM layers here, one for processing the numerical data and another for processing categorical data (in one-hot encoded format or index-based format) and then merge their outputs. Another solution is to have one separate embedding layer for each of those categorical data. Each embedding layer may have its own embedding dimension (and as suggested above, you may have more than one LSTM layer for processing numerical and categorical features separately): num_cats = 3 # number of categorical features n_steps = 100 # number of timesteps in each sample n_numerical_feats = 10 # number of numerical features in each sample cat_size = [1000, 500, 100] # number of categories in each categorical feature cat_embd_dim = [50, 10, 100] # embedding dimension for each categorical feature numerical_input = Input(shape=(n_steps, n_numerical_feats), name='numeric_input') cat_inputs = [] for i in range(num_cats): cat_inputs.append(Input(shape=(n_steps,1), name='cat' + str(i+1) + '_input')) cat_embedded = [] for i in range(num_cats): embed = TimeDistributed(Embedding(cat_size[i], cat_embd_dim[i]))(cat_inputs[i]) cat_embedded.append(embed) cat_merged = concatenate(cat_embedded) cat_merged = Reshape((n_steps, -1))(cat_merged) merged = concatenate([numerical_input, cat_merged]) lstm_out = LSTM(64)(merged) model = Model([numerical_input] + cat_inputs, lstm_out) model.summary() Here is the model summary: Layer (type) Output Shape Param # Connected to ================================================================================================== cat1_input (InputLayer) (None, 100, 1) 0 __________________________________________________________________________________________________ cat2_input (InputLayer) (None, 100, 1) 0 ______________________________________________________…
has comment: http://stackoverflow.com/comment/113980818
answers question: http://stackoverflow.com/q/52627739
has comment: http://stackoverflow.com/comment/92196850
accepted answer of: http://stackoverflow.com/q/52627739
has comment: http://stackoverflow.com/comment/92197034
upvote count: 17
has comment: http://stackoverflow.com/comment/113981541
has comment: http://stackoverflow.com/comment/97201321
has comment: http://stackoverflow.com/comment/113981641
has comment: http://stackoverflow.com/comment/113981838
has comment: http://stackoverflow.com/comment/92193911
has comment: http://stackoverflow.com/comment/92196623
has comment: http://stackoverflow.com/comment/113243488
has comment: http://stackoverflow.com/comment/113261224
has comment: http://stackoverflow.com/comment/92196428
has comment: http://stackoverflow.com/comment/92196203
has comment: http://stackoverflow.com/comment/92195639
has comment: http://stackoverflow.com/comment/92194408

http://stackoverflow.com/q/52686078
answer count: 1
has comment: http://stackoverflow.com/comment/92308964
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/57696113
score: 1
upvote count: 1
type: Question
tagged with: robotframework
has body: I want to automate a rest api get method using robotframework In robot we have a library called requests. Using this we can get the data and all. My question is that to automate that api is it OK just validate the status code 200? Or do we need to validate the entire json data? If we must to validate the data then how to validate? If we have one value we can validate that but if we have multiple how to validate??
downvote count: 0
has title: Rest API Get Automation using Robotframework

http://stackoverflow.com/comment/92309219
has text: FWIW I don't think it's the for loop -- manually looping over every pair takes me < 1s for 1000 rows. It's your np.concatenate, which has to copy the whole growing allArrays each time, in N^2. Standard practice is to either make an object of the right shape at the start and insert direclty into it or build a list and then convert to a numpy array at the end,
comment on: http://stackoverflow.com/q/52690963
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92411586
has text: "It is my understanding that Python cannot inherently move files to a network drive" - that's true of the normal OS move-by-renaming, but not a specific Python limitation I don't think? However [shutil.move](https://docs.python.org/2/library/shutil.html#shutil.move) should fall back to shutil.copy2 in this case, so should work.
type: Comment
comment on: http://stackoverflow.com/q/52743426
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92159688
type: AnswerComment
score: 0
type: Comment
has text: This failed to capture DFD in one of my trials.
comment on: http://stackoverflow.com/a/52602745

http://stackoverflow.com/q/52671833
has answer: http://stackoverflow.com/a/52673016
has body: I have a python program that accesses databases for stuff that needs to be displayed on a screen. It's purpose is to display when a person's order is ready to be picked up. I have all the code to get the data and display it on the window. However, I need every 60 seconds to re-query the databases as some orders will be picked up and need to disappear from the list and some need to be added. I just don't know how to do this, as it appears that once the app.mainloop() is called, it takes human interaction with the window to make something happen. Any assistance would be greatly appreciated... Sorry for being long winded!
tagged with: tkinter
upvote count: 1
has comment: http://stackoverflow.com/comment/92274828
linked to: http://stackoverflow.com/q/25753632
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/47943951
accepted answer: http://stackoverflow.com/a/52673016
type: Question
has title: How to refresh content of python tkinter window every 60 seconds
answer count: 2
has answer: http://stackoverflow.com/a/52673039
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92273714
has comment: http://stackoverflow.com/comment/92273519
possible better answer: http://stackoverflow.com/a/52673039
tagged with: python

http://stackoverflow.com/comment/92448452
has text: @Anthony As per your observation I have made some small modifications in my solution. I could have _optimized_ your code and performed the same _web scrapping_ opening the _Firefox Browser Client_ only once and traversing through various products. But to preserve your _logic_ and _innovation_ I have suggested the minimal changes required to get you through. Can you please try the updated solution and let me know the status please?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52738050
type: Comment

http://stackoverflow.com/comment/121284057
type: Comment
comment on: http://stackoverflow.com/a/52924241
score: 1
type: AnswerComment
has text: OSError: wkhtmltoimage exited with non-zero code 134. error: - qt.qpa.plugin: Could not find the Qt platform plugin "offscreen" in ""

http://stackoverflow.com/q/52704241
type: UnansweredQuestion
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/53685138
has answer: http://stackoverflow.com/a/52704678
has answer: http://stackoverflow.com/a/52711889
score: -1
has answer: http://stackoverflow.com/a/52704370
type: Question
has comment: http://stackoverflow.com/comment/92335003
has title: Calling a function for every dictionary in a list of dictionaries
tagged with: function
has comment: http://stackoverflow.com/comment/92335007
favorite count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/92335164
has comment: http://stackoverflow.com/comment/92335085
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52704321
has body: As input I have a list of dictionaries like the example below list = [ {"name": "John", "age": 36, "gender": "Male"}, {"name": "Lisa", "age": 40, "gender": "Female"}, {"name": "Mary", "age": 26, "gender": "Female"}, ... ] I want to run a function where I use the values in the dictionary as arguments, and for every dictionary in the list def value(person_name, person_age, person_gender): "returns a value based on arguments" As output I need to return a list of the values calculated by the function for every dictionary. For example: [def value(John, 36, Male), def value(Lisa, 40, Female), def value(Mary, 26, Female), ...] Thanks for any help :)
has comment: http://stackoverflow.com/comment/92335048
tagged with: list

ocr
tags question: http://stackoverflow.com/q/52732449
tags question: http://stackoverflow.com/q/52647131
tag name: ocr
tags question: http://stackoverflow.com/q/52599298
type: Tag
tags question: http://stackoverflow.com/q/52731296
tags question: http://stackoverflow.com/q/52733480
tags question: http://stackoverflow.com/q/52667760

http://stackoverflow.com/a/52677672
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52675659
downvote count: 0
has body: Selenium is immutable to site traffic or the load on the AUT (Application Under Test) So what matters for Selenium and WebDriver The following aspects should be part of the best practices when working with Selenium: If you are having any issue with initial Page Loading tweak the pageLoadStrategy. You can find a detailed discussion on pageLoadStrategy in How to make Selenium not wait till full page load, which has a slow script? Remove all the instances of time.sleep(n) to increase stability. You can find a detailed discussion on time.sleep(n) in How to sleep webdriver in python for milliseconds Implicit Wait was a good way to start with to deal with dynamic elements but may soon die in fire. You can find a detailed discussion on Implicit Wait in Using implicit wait in selenium If AUT (Application Under Tests) is built with JavaScript, AngularJS, ReactJS, Ember.js Explicit Wait would be your best bet. You can find a detailed discussion on Explicit Wait in Skip waiting for a website timer selenium Python
type: Answer

http://stackoverflow.com/a/52736035
accepted answer of: http://stackoverflow.com/q/52734736
type: Answer
score: 4
upvote count: 4
has body: It will sound trivial but you need to install both (jupyter notebook and bokeh) under the same environment (virtual or not). If you installed jupyter notebook using a snippet from the jupyter's website (pip3 install jupyter) then you have it installed in a non-virtual environment and from what I've understood you are trying to import bokeh which is installed in a virtual one. There are two solutions: You run everything under non-virtual environment (which is probably not the best/cleanest choice): install the notebook using pip3 install jupyter install bokeh using pip3 install bokeh start the notebook using jupyter notebook (without activating virtual environment) You run everything under virtual environment: activate your virtual environment install the notebook using python -m pip install jupyter install bokeh using python -m pip install bokeh start the notebook using jupyter notebook
downvote count: 0
answers question: http://stackoverflow.com/q/52734736
type: AcceptedAnswer

http://stackoverflow.com/comment/92220303
has text: really like your solution but again. It doesn't work properly with this list `[37, 1, 30, 38, 5, 39, 5, 5, 40, 33, 33, 33, 5, 33, 35, 42, 42, 42, 25, 36, 27, 27, 43, 27]` RESULT: `[37, 1, 30, 38, 5, 39, 7, 7, 40, 33, 33, 33, 14, 33, 35, 42, 42, 42, 25, 36, 27, 27, 43, 18]` as you can see, there's problem with 33
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52624389
type: Comment

http://stackoverflow.com/comment/92361297
type: AnswerComment
comment on: http://stackoverflow.com/a/52717903
has text: `time data datetime.datetime(2018, 5, 25, 0, 0) does not match format '%d %B %Y' (match)` threw this error. When changing the format to y B d i got `ValueError: unconverted data remains: 18`
type: Comment
score: 0

http://stackoverflow.com/a/52785831
answers question: http://stackoverflow.com/q/52669357
score: 0
has body: The only solution that I found is discussed on https://github.com/python-excel/xlrd/issues/149. Instead of pandas you need to use xlrd and make changes to xlrd/compdoc.py.
type: Answer

http://stackoverflow.com/comment/92132210
score: 0
comment on: http://stackoverflow.com/q/52598078
has text: @Johan no error at all. I got all values necessary inside the signal. If ai copy/past the same function inside the python shell, it works just fine.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92226075
type: Comment
comment on: http://stackoverflow.com/a/52646559
has text: BTW, it's better to post Python 3 code, unless the OP tags the question Python 2, or specifically asks for Python 2 code. Python 2 will reach its official End of Life in a little over a year, no one should be using it for new code. And people new to Python should _definitely_ be learning Python 3. They can learn Python 2 later if they really need it.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52736897
tagged with: user-agent
has title: Custom User-Agent in youtube-dl python script
answer count: 1
downvote count: 0
has body: I have the following piece of python code which calls youtube-dl and extracts the links that I need. ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'}) with ydl: result = ydl.extract_info( url, download=False # We just want to extract the info ) if 'entries' in result: # Can be a playlist or a list of videos video = result['entries'][0] else: # Just a video video = result if video: return video return None But I want to use the custom User-Agent in this program. I know I can specify the custom User-Agent while using the youtube-dl in the command line. Is there any way I can specify the custom user-agent in the program embedding youtube-dl. Thanks
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52738630
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52738630
score: 4
tagged with: youtube-dl
upvote count: 4
tagged with: python-2.7

http://stackoverflow.com/q/52743787
type: UnansweredQuestion
has body: I am working with images similar to these examples below: As in the above image, the images will always be a hexagon. Within each hexagon, there will be a shape which is connected to one some of the edges. I want to be able to grab this image and determine the shapes inside this. To do this, I want to store the objects in an array structure like this: [1,1,1,1,1,1] where the values are represented by whether or not the shape connects to these corresponding edges of the hexagon: [Top, Top Left, Bottom Left, Bottom, Bottom Right, Top Right] (going clockwise) Another example of the image would be: This image would be represented by the array [0,1,0,1,0,0]. In order to create this array, I am checking the pixel at each of the points on the images shown by a red dot to see if the color is blue. This works fine for these types of shapes. The complication for this task arises is that the hexagon may contain 2 separate shapes, which I want to store the array for each shape in the hexagon. An example would be like below: As can be seen with this image, the hexagon can have 2 shapes, although the 2 shapes will never share the same edge of the hexagon. I would want to represent this as: Shape 1: [0,1,0,0,1,0] Shape 2: [1,0,0,1,0,0] If I was to use my existing algorithm, I would just discern it as: [1,1,0,1,1,0] which is not what I am wanting to do. How can I discern between these shapes? Kind Regards,
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92418971
score: 1
tagged with: image-processing
upvote count: 1
has title: Python Image / Shape recognition task
has comment: http://stackoverflow.com/comment/92425440
type: Question
tagged with: opencv
tagged with: algorithm
tagged with: image-recognition
has comment: http://stackoverflow.com/comment/92418875
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/52707550
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52707754
type: Question
has title: Replacing bash script with python - Checking if process is running?
tagged with: bash
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52707754
has body: This is what I have currently (checks a number of processes, this is just one) and it works magically: if role=Agent then echo "Validations for the service $servicename..." livefilterd=$(pgrep -f backgroundd) if [ -n "$livefilterd" ] then printf "The $servicename service is running as: \n$livefilterd" let statusfilterd=1 else echo -ne '!!!The $servicename process is NOT running!!!\r';sleep 0.5;echo -ne ' The $servicename process is NOT running \r';sleep 0.5;echo -ne '!!!The $servicename process is NOT running!!!\r';sleep 0.5;echo -ne ' The $servicename process is NOT running \r';sleep 0.5; let "badkids=badkids+1" let statusfilterd=0 fi else print "Validation for $servicename is being skipped as it's not expected on this host due to the role of $role." fi I'd like to move this to python, and most of the script I've been able to figure out and test, but I'm having issues with the block above. This is where I've gotten, but I'm not sure I can nest a try/except within an if/else statement, and would greatly appreciate some help: servicename=backgroundd if role == 'Agent': print ("Validations for the service " + servicename + "...") try: get_pid("backgroundd") print ("YAY") print ("The " + servicename + " service is running as:" + servicename) statusfilterd = 1 except Exception: cprint("\n!!!!The " + servicename + " process is NOT running!!!!", 'red', attrs=['blink']) badkids = badkids+1 statusfilterd = 0 else print ("Validation for $servicename is being skipped as it's not expected on this host due to the role of $role.") print();print();time.sleep(0.5) Where is my mistake within this??? Many thanks in advance!!

http://stackoverflow.com/a/52620601
type: Answer
has body: Here is a "brute force" way to do this. You could generalize it to better handle different x/y ranges. Maybe you could use matplotlib and potentially go off this example from PIL import Image, ImageDraw im = Image.new('RGBA', (250, 250), "white") draw = ImageDraw.Draw(im) draw.rectangle([(0, 0), (249, 249)], outline='black') # just here to create a visible box draw.rectangle([(10, 40), (100, 200)], fill='red', outline='red') # Draw x ticks [draw.line(((x,250),(x,245)),fill='black') for x in range(0,249,5)] # Draw x labels [draw.text((x,235),str(x),fill='black')for x in range(0,249,25)] # Can do same for y... im
upvote count: 2
has comment: http://stackoverflow.com/comment/92208255
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52618190

http://stackoverflow.com/comment/92293330
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52682585
has text: If you want to see the value, you have to `print` it. Expression values only get auto-printed in interactive mode.

http://stackoverflow.com/comment/92230911
comment on: http://stackoverflow.com/q/52648593
type: Comment
type: QuestionComment
has text: @ShadowRanger, you may well be right. I have a bit of a penchant for over engineering things. I will ponder some more what I'm actually trying to do.
score: 0

http://stackoverflow.com/q/52675769
tagged with: python
tagged with: python-3.x
upvote count: 2
has body: Starting off with a few dict variables defined within a class context... class ContextFilter(logging.Filter): coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow', u'ERROR':u'red', u'INFO':u'blue'} colors = dict(zip([u'black', u'red', u'green', u'yellow', u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8)))) ...I was intending to generate a derived dict variable that effectively cached the results of colors[coloring[____]]; the intended dict contents are shown below: {'DEBUG': '35', 'WARNING': '33', 'ERROR': '31', 'INFO': '34'} However, using two of the dictionary constructor formats described here results in a runtime error message of NameError: name 'colors' is not defined (in spite of colors being defined immediately prior): class ContextFilter(logging.Filter): coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow', u'ERROR':u'red', u'INFO':u'blue'} colors = dict(zip([u'black', u'red', u'green', u'yellow', u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8)))) print(colors) # test statement; colors is in scope here color_map = {k:colors[v] for k, v in coloring.items()} . class ContextFilter(logging.Filter): coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow', u'ERROR':u'red', u'INFO':u'blue'} colors = dict(zip([u'black', u'red', u'green', u'yellow', u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8)))) print(colors) # test statement; colors is in scope here color_map = dict([(k, colors[v]) for k, v in coloring.items()]) Why did the above code snippets not behave as expected? Why was colors not in scope in the color_map constructor, even though it appears to otherwise be in scope within the class declaration? (Ultimately, I was able to get the desired behavior using the below code block; I'm asking this question to understand why my previous attempts at a "cleaner" solution weren't working.) class ContextFilter(logging.Filter): coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow', u'ERROR':u'red', u'INFO':u'blue…
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/13905741
score: 2
has title: Why can't a static class dict be constructed from another?
downvote count: 0
duplicate of: http://stackoverflow.com/q/13905741
answer count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/52609136
downvote count: 0
has comment: http://stackoverflow.com/comment/92159169
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92158576
has comment: http://stackoverflow.com/comment/92158639
has body: I've deployed Django project using Nginx web server, but on the website, only static files are displaying correctly. When I try to access a particular media file using website.com/media/file_name it throws an error Not found. The requested URL /media/dress.png was not found on this server. Here's my settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') KEY_DIR = os.path.join(BASE_DIR, 'etc') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ with open(os.path.join(KEY_DIR, 'secret_key.txt')) as f: SECRET_KEY = f.read().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ '*', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'endless_pagination', 'catalog', 'like', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bride.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'like.context_processors.like', ], }, }, ] WSGI_APPLICATION = 'app_name.wsgi.app…
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
has title: Nginx doesn't serve media files
has comment: http://stackoverflow.com/comment/92156512
tagged with: nginx
score: 1
type: Question

http://stackoverflow.com/q/52591696
has comment: http://stackoverflow.com/comment/92118283
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92119842
has title: Should I use the dictionary or the series to hold a bunch of dataframe?
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52592102
downvote count: 0
has comment: http://stackoverflow.com/comment/92118195
tagged with: panel
favorite count: 0
has body: Suppose I have several dataframes: df1, df2, df3, etc. The label with each dataframes is A1, A2, A3 etc. I want to use this information as a whole, so that I can pass them. Three methods came into my mind: method 1 use a label list: labels=["A1", "A2", "A3"...] and a list of dataframes dfs=[df1, df2, df3...]. method 2 use a dictionary: d={"A1": df1, "A2": df2, "A3": df3}. method 3 use a pandas series: s=pd.Series([df1, df2, df3], index=["A1", "A2", "A3"]). I will use the label and dataframes sequentially, therefore I think method1 and method3 should be my choice. However, using method 1 will need me to pass two items, while using method 3 I only need to keep one object. Is it a common practice to put the dataframes in a series? I seldom see people do this, is it against best practice? Is there any better suggestions?
tagged with: python
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/92118086
linked to: http://stackoverflow.com/q/39980323
type: Question
has comment: http://stackoverflow.com/comment/92118497
score: 3
possible better answer: http://stackoverflow.com/a/52592108
has comment: http://stackoverflow.com/comment/92118412
has comment: http://stackoverflow.com/comment/92118151
has answer: http://stackoverflow.com/a/52592108
has answer: http://stackoverflow.com/a/52592102

http://stackoverflow.com/q/52679652
has title: How to join three arrays without "None" in Python 3
has comment: http://stackoverflow.com/comment/92287941
tagged with: python
has answer: http://stackoverflow.com/a/52679696
has comment: http://stackoverflow.com/comment/92287931
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52679696
type: Question
has body: I'm trying to loop through three arrays containing lists of words and join them together, space-delimited. So far, I'm finding that if I use the following for loop: for lines in zip(lines_left, lines_middle, lines_right): I get this result (printed): ('wage \n', 'forswore \n', 'rake\n') My next step is to join them together and cleanup any leading or trailing white space. This is how I am attempting it: phrase = print(' '.join(line.strip() for line in lines)) However, my result (per line) is: wage forswore rake None How do I join the arrays without "None" on a new line? I tried using .strip("\n") as well, to no avail. Thanks in advance.
answer count: 1
score: 0

http://stackoverflow.com/q/52597455
type: Question
has answer: http://stackoverflow.com/a/52616132
tagged with: python
has comment: http://stackoverflow.com/comment/92166516
answer count: 1
has body: I am trying to write a Python utility function that accepts an object of a locally-defined class, and uses one of that class's methods as a user-defined function (UDF), in a PySpark DataFrame withColumn call. The utility function signature is: def spark_analyze(lp: LogProcessor): In the LogProcessor class, I have a method that I'd like to use as a UDF. The method definition is: schema = StructType([ StructField("total", IntegerType(), False), StructField("other", IntegerType(), False) ]) def ProcessLog(self, log_file): self.PrepareForLog() for event in pyspark_utils.spark_events_from_file(log_file): self.ProcessEvent(event) return [total, other] In the spark_analyze, I do the following, where lp is the passed-in object of type LogProcessor: @udf(lp.schema) def lpf(lcm_file): lp.ProcessLog(lcm_file) return (df.withColumn('results', lpf(col('logfile_dir'))) ... The produces a long Python stack trace, which starts like this: /home/david/libs.zip/pyspark_utils.py in spark_analyze(lp) 132 def lpf(lcm_file): 133 lp.ProcessLog(lcm_file) --> 134 return (df.withColumn('results', lpf(col('logfile_dir'))) 135 .withColumn('log name', spark_get_dataset_name(col('logfile_dir'))) 136 .select('log name', 'results.*') /usr/hdp/current/spark2-client/python/lib/pyspark.zip/pyspark/sql/functions.py in wrapper(*args) 1955 @functools.wraps(f) 1956 def wrapper(*args): -> 1957 return udf_obj(*args) 1958 1959 wrapper.func = udf_obj.func and ends with: /home/david/libs.zip/pyspark_utils.py in spark_analyze(lp) 132 def lpf(lcm_file): 133 lp.ProcessLog(lcm_file) --> 134 return (df.withColumn('results', lpf(col('logfile_dir'))) 135 .withColumn('log name', spark_get_dataset_name(col('logfile_dir'))) 136 .select('log name', 'results.*') /usr/hdp/current/spark2-client/python/lib/pyspark.zip/pyspark/sql/functions.py in wrapper(*args) 1955 @functools.wraps(f) 1956 def wrapper(*args): -> 1957 return udf_obj(*args) 1958 1959 wrapper.func = udf_obj.func I did some testing, and found that things work fi…
upvote count: 1
tagged with: user-defined-functions
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/92137434
tagged with: pyspark
type: UnansweredQuestion
tagged with: apache-spark
has title: Using a method from a Python class as a PySpark user-defined function
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/92347018
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52710396
has text: Assuming `b` is a number, it means `while b!=0:`
type: Comment

http://stackoverflow.com/q/52589839
linked to: http://stackoverflow.com/q/22404060
upvote count: 3
tagged with: fortran
tagged with: cython
has comment: http://stackoverflow.com/comment/92116150
type: Question
score: 3
has answer: http://stackoverflow.com/a/52592069
tagged with: openmpi
has title: Calling an MPI dependent Fortran module via Cython
has comment: http://stackoverflow.com/comment/92121497
downvote count: 0
answer count: 1
has body: I am trying to call a Fortran library, which uses Open MPI, from Python. I chose to use Cython as the layer between Python and Fortran. I got a minimal working example running from this answer, but I have problems when it comes to using Open MPI. Below you find my attempt on including MPI in this example. If I call the module ffunc from a Fortran program, it works, but if I try to access it from Python, I get mca_base_component_repository_open: unable to open mca_patcher_overwrite: /path/to/mca_patcher_overwrite.so: undefined symbol: mca_patcher_base_patch_t_class (ignored) mca_base_component_repository_open: unable to open mca_shmem_mmap: /path/to/mca_shmem_mmap.so: undefined symbol: opal_show_help (ignored) mca_base_component_repository_open: unable to open mca_shmem_posix: /path/to/mca_shmem_posix.so: undefined symbol: opal_shmem_base_framework (ignored) mca_base_component_repository_open: unable to open mca_shmem_sysv: /path/to/mca_shmem_sysv.so: undefined symbol: opal_show_help (ignored) As a minimal working example I have following: The Fortran module to call ffunc.p90: module ffunc use mpi implicit none integer, parameter :: dp = kind(1.0d0) contains subroutine func(a, b, c) real(dp), intent(in) :: a real(dp), intent(in) :: b real(dp), intent(out) :: c integer :: ierr call mpi_init(ierr) c = a + b call mpi_finalize(ierr) end subroutine func end module ffunc the Fortran-C wrapper pyffunc.f90: module fortran_wrapper use iso_c_binding, only: c_double use ffunc, only: func implicit none contains subroutine c_func(a, b, c) bind(c) real(c_double), intent(in) :: a real(c_double), intent(in) :: b real(c_double), intent(out) :: c call func(a, b, c) end subroutine c_func end module fortran_wrapper the C header pyffunc.h: extern void c_func(double* a, double* b, double* c); the Cython wrapper pyffunc.pyx: cdef extern from 'pyffunc.h': void c_func(double* a, double* b, double* c) def func(double a, double b): cdef: double c c_func(&amp;a, &amp;b, &amp;c) print('cython: a…
has comment: http://stackoverflow.com/comment/92119201
favorite count: 0
has comment: http://stackoverflow.com/comment/92117765
accepted answer: http://stackoverflow.com/a/52592069
tagged with: mpi
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52654182
upvote count: 1
has comment: http://stackoverflow.com/comment/92239986
accepted answer of: http://stackoverflow.com/q/52653985
has comment: http://stackoverflow.com/comment/92240932
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52653985
has comment: http://stackoverflow.com/comment/92240023
has body: As suggested by @gill Hamilton, you should use iterfind, but with a XPath expression, for instance: ".//ns:value". Here is a full example: import xml.etree.ElementTree as ET content = u"""\ polyStringNorm c:name lilpotter """ root = ET.fromstring(content) NS = {'ns': 'http://prism.evolveum.com/xml/ns/public/query-3'} for item in root.iterfind(".//ns:value", NS): print(item.tag) # -> {http://prism.evolveum.com/xml/ns/public/query-3}value
has comment: http://stackoverflow.com/comment/92240761
has comment: http://stackoverflow.com/comment/92240250
type: Answer
has comment: http://stackoverflow.com/comment/92239914

http://stackoverflow.com/q/52742797
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Form data not submitted when textarea already filled
type: AnsweredQuestion
tagged with: flask-wtforms
tagged with: jinja2
type: Question
linked to: http://stackoverflow.com/q/5117479
has body: I'm using WTForms and Jinja2 to make a page with an editable textarea. The idea is to edit text in a database, so the textarea should already be populated with text for the user to edit. Based on this question/answer I have something like the following code: In app.py: form = MyForm() # MyForm is defined elsewhere simply as # class MyForm(FlaskForm): content=TextAreaField() prepopulated = GetTextFromDatabase() form.content.data = prepopulated if form.validate_on_submit(): new_content = form.content.data SaveToDatabase(new_content) return flask.render_template('edit.html', form=form) In edit.html: {{ form.hidden_tag() }} {{ form.content }} Submit However, when submitting, the changes made to the text are not saved in the database. If I remove the form.content.data = prepopulated the changes are saved. So how can I prepopulate the textarea yet make sure any changes to the text are saved?
score: 0
accepted answer: http://stackoverflow.com/a/52760575
answer count: 1
has answer: http://stackoverflow.com/a/52760575

http://stackoverflow.com/comment/92346547
score: 0
type: Comment
has text: I've edited my answer to address your first comment. In terms of restarting the counter at certain dates, that is a completely different question than what you originally posted and warrants a separate question.
comment on: http://stackoverflow.com/a/52709797
type: AnswerComment

http://stackoverflow.com/q/52717485
type: Question
has body: I am using pdfkit in Python to convert my Django template to PDF. I am going to generate a pdf with 3 pages and I need my last page size should be landscape. I tried with options parameter but couldn't find how to apply page_size for a specific page. Note: Please comment if you are unclear with the question rather down voting, losing interest in this platform.
tagged with: python
tagged with: python-pdfkit
score: -1
has title: How to set page size for a specific page
downvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52733504
type: UnansweredQuestion
upvote count: 0
favorite count: 0

http://stackoverflow.com/comment/92216116
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52592826
has text: Thanks for your answer, but in my case the variables are calculated with respect to images in the directory, and they are not constant to be put in config file.

http://stackoverflow.com/q/52671447
has comment: http://stackoverflow.com/comment/92273654
has body: I want to check whether a single quantity is within a measurement. Or if a measurement is within a measurement. ie, this should return True: import pint u=pint.UnitRegistry() a=(1*u.m).plus_minus(0.1, relative=True) (1.05*u.m).within(a) Is this functionality/use case at all supported?
downvote count: 0
score: 1
favorite count: 0
tagged with: pint
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92274189
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92272853
has title: Check if a quantity is within some measurement in pint in python
has comment: http://stackoverflow.com/comment/92273968

http://stackoverflow.com/comment/92176128
type: Comment
score: 2
has text: The url "example.com" doesn't pass your `if` statement: `if link.split(':')[0] in prefix and link.split('.')[-1] in suffix:`.
comment on: http://stackoverflow.com/q/52621192
type: QuestionComment

http://stackoverflow.com/q/52708397
has comment: http://stackoverflow.com/comment/92343035
has answer: http://stackoverflow.com/a/52731192
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/92343156
score: -2
linked to: http://stackoverflow.com/q/24085680
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92343130
answer count: 2
accepted answer: http://stackoverflow.com/a/52731192
possible better answer: http://stackoverflow.com/a/52708701
upvote count: 0
has title: Python inconsistencies reading regex file
has answer: http://stackoverflow.com/a/52708701
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/92343179
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: I have a regex file that I am reading in and compiling. The issue I am having is the regex will sometimes leading \. Z\\d*\\.file_\\.? instead of Z\d*\.file_\.? It sometimes matching but others not.

http://stackoverflow.com/comment/92280016
type: AnswerComment
type: Comment
has text: The link you provided did suggest creating `session` for each thread instead of having the clients sharing the same session. Something like `boto3.Session().client`.
comment on: http://stackoverflow.com/a/52675074
score: 1

http://stackoverflow.com/q/52594160
has comment: http://stackoverflow.com/comment/92157493
type: Question
has comment: http://stackoverflow.com/comment/92163969
tagged with: python-imaging-library
has title: Memory error converting large RGB image to grayscale
tagged with: grayscale
has comment: http://stackoverflow.com/comment/92123950
has comment: http://stackoverflow.com/comment/113454856
tagged with: rgb
has comment: http://stackoverflow.com/comment/92126178
has comment: http://stackoverflow.com/comment/92129412
has answer: http://stackoverflow.com/a/52615165
score: 0
has comment: http://stackoverflow.com/comment/92125442
answer count: 1
has comment: http://stackoverflow.com/comment/92125722
has comment: http://stackoverflow.com/comment/92129374
tagged with: python
has comment: http://stackoverflow.com/comment/113453704
accepted answer: http://stackoverflow.com/a/52615165
has comment: http://stackoverflow.com/comment/92147272
has comment: http://stackoverflow.com/comment/92123596
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92132068
has comment: http://stackoverflow.com/comment/92162507
has comment: http://stackoverflow.com/comment/92123803
has body: I am trying to load original color fundus images in python for some learning project. These are RGB images of sizes approx. 4000*2000*3. I want to convert each image to grayscale before sending them for training into my model. For this, I've tried the following 2 approaches: Method 1: import matplotlib.image as mpimg def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) def load_images(folder): images = [] for filename in os.listdir(folder): img = mpimg.imread(os.path.join(folder, filename)) gray = rgb2gray(img) images.append(gray) return images Method 2: from PIL import Image def load_images(folder): images = [] for filename in os.listdir(folder): img = Image.open(os.path.join(folder, filename)) gray = img.convert('L') images.append(gray) return images In both the methods, I get the same Memory Error at lines gray = rgb2gray(img) and gray = img.convert('L') respectively. Is there any way I can convert such large images to grayscale one at a time and store it as a list?

http://stackoverflow.com/comment/92278823
type: Comment
comment on: http://stackoverflow.com/a/52656783
type: AnswerComment
has text: In my case the variable date is dynamic. For example, if you click the day 18 then this variable becomes Thursday, October 18, 2018. For day 17 this will be Wednesday, October 17, 2018. In your case this part is always sticked to Thursday, October 18, 2018. Making this only work for day 18.
score: 0

http://stackoverflow.com/q/52669226
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/92268440
accepted answer: http://stackoverflow.com/a/52669618
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/92268875
has title: Creating a new column in a dataframe based on the values on another column in pandas
downvote count: 1
upvote count: 0
tagged with: pandas
type: AnsweredQuestion
has body: So I have the dataframe: id Name Score 313 John 600 415 Zack 800 990 Harry 300 ... ... ... What I want to do is to create a new column in this dataframe that sees if the score is greater or less than the next and places 1 if it is greater and 0 if it is less. What I want looks like this: id Name Score Operator 313 John 600 1 415 Zack 800 0 990 Harry 300 1 ... ... ... .
has answer: http://stackoverflow.com/a/52669618
score: -1
favorite count: 0

http://stackoverflow.com/a/57607284
downvote count: 1
upvote count: 35
answers question: http://stackoverflow.com/q/52698283
has comment: http://stackoverflow.com/comment/136658298
type: Answer
has body: exceptions import UnrewindableBodyError ImportError: cannot import name UnrewindableBodyError The above error is likely due to "urllib3" package being broken. uninstall/install will fix the problem: sudo pip uninstall urllib3 sudo pip install --upgrade urllib3 Another issue could be that, urllib3 was installed via pip, and requests installed via yum repo, or vice-versa. In that case, the fix is to completely remove these libraries and install it via same repo. I recommend pip over yum to install both packages as it is easy to maintain and gives more control. Any further yum updates required for OS patching or VM maintenance activities etc., won't impact the packages installed via pip. First remove all installations of “urllib3” and “requests” via pip and yum: sudo pip uninstall urllib3 -y sudo pip uninstall requests -y sudo yum remove python-urllib3 -y sudo yum remove python-requests -y Now install both packages only via pip: sudo pip install --upgrade urllib3 sudo pip install --upgrade requests To install both packages only via yum: sudo yum install python-urllib3 sudo yum install python-requests Note: Always use virtual environment to avoid conflicts when an yum update happens at OS level.
score: 34

http://stackoverflow.com/q/52696447
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/92328385
has answer: http://stackoverflow.com/a/52701187
tagged with: matplotlib
score: 0
has body: I have created Gantt chart,I am trying to add the legend to my plot import pandas as pd import matplotlib.pyplot as plt data=[['A','B','7:00:00','7:30:00'],['A','C','8:00:00','8:30:00'], ['X','B','7:30:00','8:30:00'],['X','C','7:30:00','8:00:00'], ['P','Q','7:30:00','8:30:00'],['P','C','9:00:00','9:30:00']] df=pd.DataFrame(data,columns=['L','M','stime','etime']) start_time=[] end_time=[] for i,row in df.iterrows(): a=row['stime'].split(':') b=row['etime'].split(':') start_hrs=int(a[0])+(int(a[1])/60)+(int(a[2])/3600) end_hrs=int(b[0])+(int(b[1])/60)+(int(b[2])/3600) start_time.append(start_hrs) end_time.append(end_hrs) df['start']=start_time df['end']=end_time df['diff']=df['end']-df['start'] color = {"B":"turquoise", "C":"crimson","Q":"orange"} fig,ax=plt.subplots(figsize=(6,3)) w=[] for i, task in enumerate(df.groupby("L")): w.append(task[0]) for r in task[1].groupby("M"): data = r[1]"start", "diff" ax.broken_barh(data.values, (i-0.4,0.8), color=color[r[0]],label=r[1] ['M']) ax.set_yticks(range(len(label))) ax.set_yticklabels(label) ax.set_xlabel("time [hrs]") ax.set_ylabel("L") plt.legend() plt.tight_layout() plt.show() the legends are duplicate in the plot.How can I correct this?
has title: Avoid duplicate legends in broken_barh
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/92362254
score: 0
type: Comment
type: QuestionComment
has text: I found only the "pandas-groupby" tag. Hope this works.
comment on: http://stackoverflow.com/q/52718192

http://stackoverflow.com/comment/92253478
type: Comment
score: 1
type: AnswerComment
has text: @yasi - In my opinion here is not reason for creating dictionaries in first step, first use `timeseries= timeseries[timeseries.groupby('appId')['appId'].transform('size') >= 30]` and then if necessary `dfs = dict(tuple(timeseries.groupby('appId')))`
comment on: http://stackoverflow.com/a/52661186

http://stackoverflow.com/comment/92177511
score: 0
comment on: http://stackoverflow.com/q/52620953
has text: @Aran-Fey, Yes! Here's a number of my failed attempts: ipdb> re.search('><=',item[0]) ipdb> re.search('(<>=)',item[0]) ipdb> re.search('=',item[0]) <_sre.SRE_Match object; span=(0, 1), match='='> ipdb> re.search('(<[=>]?|==|>=?|\&\&|\|\|)',item[0]) ipdb> re.search('[<>=]',item[0]) <_sre.SRE_Match object; span=(0, 1), match='='> ipdb> re.search('<[=>]?|==|>=?|\&\&|\|\|',item[0]) ipdb> re.search('(<[=>]?|=|>=?)\s\d+', item[0]) ipdb> re.search('(<,>,=)', item[0]) ipdb> re.search('^\(\s*[a-zA-Z0-9_+\-\/* ]+\s*(>=|<=|>|<|==|!=)\s*[a-zA-Z0-9_+\-\/* ]+\s*\)$',item[0])
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92360664
comment on: http://stackoverflow.com/q/52716440
has text: What you mention is the Qt interface, which is not the default one. Last time I installed openCV you had to compile from source to enable it, but it may have changed with the last versions.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52689667
type: Answer
has comment: http://stackoverflow.com/comment/92306249
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92306561
answers question: http://stackoverflow.com/q/52689640
has body: students = {} name = input("Give me the student name(key): ") grade = input("What is their Grade(value): ") students[name] = grade You can just use students[key] = value
score: 0

http://stackoverflow.com/q/52746470
score: 0
has answer: http://stackoverflow.com/a/54032031
tagged with: desktop-application
answer count: 1
tagged with: javascript
has title: npm python-shell not working with electron
tagged with: python
accepted answer: http://stackoverflow.com/a/54032031
type: AnsweredQuestion
tagged with: electron
tagged with: npm
type: Question
has body: I am trying to link a python script with Electron app using the npm's python-shell package. The condition is to execute the script whenever I click on a button. So, suppose my directory contains: main.js (electron file) index.js (my script) index.html main.py In index.js, I write the following code to import python-shell and execute the main.py script: function get_input() { var python = require("python-shell") var path = require("path") var options = { scriptPath: path.join(__dirname, './python/') } var weather = new python('main.py', options); weather.on('message', function (message) { console.log(message); }) } In the index.html, I have created a button tag to run this function on click: Go! In the main.py, all I do for now is print "hello". Now when I run, npm start I recieve the following error: Does anyone know why this is not working? I saw many articles on Electron, they all do the same thing and it works. If there is something that I am missing, please let me know. Thank you.

http://stackoverflow.com/q/52640007
answer count: 1
tagged with: string
favorite count: 0
tagged with: python
tagged with: regex
has body: Hi guys is there a clean way to organize this data into its correct columns to geolocate it later? import pandas as pd coordinates = {'event': ['1', '2', '3', '4'], 'direction': ['E', 'E,N', 'N,E', 'N'], 'location': ['316904', '314798,5812040', '5811316,314766', '5811309']} df = pd.DataFrame.from_dict(coordinates) df What it need it to look like: Event direction location easting northing 1 E 316904 316904 NA 2 E,N 314798,5812040 314798 5812040 3 N,E 5811316,314766 314766 5811316 4 N 5811309 NA 5811309 I can split the location with: df['easting'], df['northing'] = df['location'].str.split(',',1).str but I need the condition when E THEN 1st value is easting, second northing OR condition when N than 1st value is easting and so on.. any ideas would be gladly appreciated!
type: AnsweredQuestion
score: 2
downvote count: 0
has title: Conditional String Split based on another column str Python
type: Question
has answer: http://stackoverflow.com/a/52640469
accepted answer: http://stackoverflow.com/a/52640469
upvote count: 2
tagged with: pandas

http://stackoverflow.com/comment/92310977
has text: 1) What is `__str__` supposed to return? 2) What is this `print` Supposed to do here anyway?
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52691996
type: Comment

http://stackoverflow.com/a/52722106
score: 2
has comment: http://stackoverflow.com/comment/92373976
has comment: http://stackoverflow.com/comment/92375292
answers question: http://stackoverflow.com/q/52722004
has comment: http://stackoverflow.com/comment/92374448
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92374636
has body: you'll have no problems with Python 3 with your exact code (this issue is often encountered when passing windows literal strings where the r prefix is required). With python 2, first you'll have to wrap your filename with quotes, then all special chars will be interpreted (\t, \n ...). Unless you input r"DB\test.txt" using this raw prefix I was mentionning earlier but it's beginning to become cumbersome :) So I'd suggest to use raw_input (and don't input text with quotes). Or python version agnostic version to override the unsafe input for python 2 only: try: input = raw_input except NameError: pass then your code will work OK and you got rid of possible code injection in your code as a bonus (See python 2 specific topic: Is it ever useful to use Python&#39;s input over raw_input?).
upvote count: 2

http://stackoverflow.com/comment/92214427
comment on: http://stackoverflow.com/q/52640941
score: 0
type: QuestionComment
type: Comment
has text: @RedX : items[i] is a list using which I am running a loop to grep values. In the above example it will have values like "establishmentCause,Freq,Radio Bearer ID,Physical Cell ID"

http://stackoverflow.com/q/52597599
tagged with: depth-first-search
tagged with: networkx
type: Question
accepted answer: http://stackoverflow.com/a/52598057
upvote count: 5
answer count: 2
score: 5
downvote count: 0
has title: In NetworkX, how to get the DFS tree including the node data?
favorite count: 0
has body: In a directed graph in which the nodes have not only IDs, but also data (a dictionary of attributes), I'd to obtain the DFS tree starting from a given source node, including the data of the child nodes. I've noticed, however, that the nx.dfs_tree function seems to return a tree without any data: In [1]: import networkx as nx In [2]: G = nx.DiGraph() In [3]: G.add_nodes_from([(0, {'name': 'foo'}), (1, {'name': 'bar'}), (2, {'name ...: ': 'baz'})]) In [4]: G.add_edge(0, 1) In [5]: G.add_edge(1, 2) In [6]: T = nx.dfs_tree(G, 1) In [7]: T.nodes[1] Out[7]: {} In [8]: T.nodes[2] Out[8]: {} In [9]: T.nodes Out[9]: NodeView((1, 2)) In [10]: G.nodes[1] Out[10]: {'name': 'bar'} As seen from the example above, T.nodes[1] is an empty dictionary, whereas G.nodes[1] contains the data dictionary originally passed in. How can I make it so that T.nodes[1] and other tree nodes contain the same data as the original graph?
has answer: http://stackoverflow.com/a/52598057
tagged with: python
possible better answer: http://stackoverflow.com/a/69449896
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69449896

http://stackoverflow.com/a/67309014
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/52686489
downvote count: 0
has body: How about this: from datar import f from datar.tibble import tribble from datar.tidyr import pivot_longer df = tribble( f.y, f.female, f.male, 1, 2, 3, 4, 5, 6 ) pivot_longer(df, [f.female, f.male], names_to="gender") # y name value # 0 1 female 2 # 1 4 female 5 # 2 1 male 3 # 3 4 male 6 I am the author of the datar package. Please feel free to submit issues if you have any questions about using it.
type: Answer

http://stackoverflow.com/q/52654214
has comment: http://stackoverflow.com/comment/92240027
tagged with: dataframe
score: 0
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52654577
has comment: http://stackoverflow.com/comment/92239855
has body: I need to calculate a new column in my dataframe using a if in the calculation but have no luck with anything I have tried. This is what I have OrderNum Discount OrderQty UnitPrice REMAININGQTY 0 115702 0.0 25.0 145.00 25.0 1 115793 0.0 20.0 823.00 20.0 2 115793 0.0 20.0 823.00 20.0 3 116282 0.0 1.0 699.95 1.0 4 116765 0.0 36.0 295.00 6.0 This is what I need. column = PricePer the calculation = IIf(df.discount&lt;&gt;0,df.unitprice-(df.discount/df.orderqty),df.unitprice) How do I accomplish this?
has answer: http://stackoverflow.com/a/52654577
tagged with: python
accepted answer: http://stackoverflow.com/a/52654304
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92239929
has answer: http://stackoverflow.com/a/52654304
has title: Create new column in pandas dataframe using if statement against another column
type: Question

http://stackoverflow.com/a/52603294
has comment: http://stackoverflow.com/comment/92142742
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92149836
has body: Unequal join is not recommended for spark join. Usually, I generate a new column as the join key for this kind of operation. However, for your case, you do not need joining to determine which bin of the histogram each observation falls into because each bin's upper and lower bounds can be precalculated and you can calculate the bin with the observation. What you can do is to write a UDF which finds the bin for you and returns the bin as a new column. You may refer to pyspark: passing multiple dataframe fields to udf
answers question: http://stackoverflow.com/q/52598878
has comment: http://stackoverflow.com/comment/92141168
downvote count: 0
has comment: http://stackoverflow.com/comment/92140817
has comment: http://stackoverflow.com/comment/92146299
type: Answer

http://stackoverflow.com/q/52741990
has comment: http://stackoverflow.com/comment/92408983
type: Question
has answer: http://stackoverflow.com/a/52751642
has answer: http://stackoverflow.com/a/52746306
has comment: http://stackoverflow.com/comment/92409085
has comment: http://stackoverflow.com/comment/92409175
answer count: 3
has comment: http://stackoverflow.com/comment/92409595
downvote count: 0
has answer: http://stackoverflow.com/a/52742929
favorite count: 0
has title: Parse tabular output from Subprocess Check_Output
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92409639
tagged with: python
has body: I'm working on a Python(3.6) project in which I need to parse data from a tabular output of subprocess.check_output. Here's How I'm using this: The output is: NAME HOSTS ADDRESS PORTS AGE mysvcs * 107.178.250.150 80 1m This out loads an empty column for ADDRESS like this: NAME HOSTS ADDRESS PORTS AGE mysvcs * 80 1m But after few moments it loads the 107.178.250.150 in the 3rd column of second row. So, how can I get this address when it has been populated. Here's how I'm trying: address = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True) all_address = out_ip.decode().split('\n') print(all_address) address = all_address[1] print(address) if not address: while address == '': out_address = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True) all_address = out_ip.decode().split('\n') ip = all_address[1] print(address) But it's even not running the while loop and output as: b'ADDRESS\n80\n' ['ADDRESS', '80', ''] 80 Update: Here's how I have tried stovfl's answer: ip = '' # Limit to 5 loops for n in range(5): result = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True) # Make a List from the result, spliting at NewLine _list = result.decode().split('\n') # Check if Value 2 (Index==1) matches a IP Address if re.match(r'(\d+\.\d+\.\d+\.\d+)', _list[1]): ip = _list[1] print("match:{}".format(_list[1])) # End the loop break # Wait a second, before next try time.sleep(1) address = 'http://' + ip
has comment: http://stackoverflow.com/comment/92409401
tagged with: subprocess
score: 1
upvote count: 1

http://stackoverflow.com/comment/92375820
type: Comment
has text: @Starbucks, I believe this is an issue with specific combinations of `numpy` and `pandas`. This seems to be fixed in newer versions. What versions of `numpy` and `pandas` are you running? Are you able to update?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52724284

http://stackoverflow.com/comment/92222174
type: QuestionComment
comment on: http://stackoverflow.com/q/52644714
type: Comment
score: 0
has text: @Andre Motta I think you did not get me. I should return the string as it is if it starts with "[*" else if it starts with "[" then I should return an empty string

http://stackoverflow.com/comment/92350967
score: 0
comment on: http://stackoverflow.com/q/52712513
type: Comment
type: QuestionComment
has text: Are you wanting it split down the middle? For example, the first line turned into `20150926` and `T104044Z`?

http://stackoverflow.com/comment/92213304
type: Comment
comment on: http://stackoverflow.com/a/52640471
type: AnswerComment
has text: Returning error as "ValueError: too many values to unpack (expected 2)"
score: 0

http://stackoverflow.com/comment/92411552
type: Comment
comment on: http://stackoverflow.com/q/52743426
score: 0
has text: The computer you're running the from, it has access to the network drive, correct?
type: QuestionComment

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

http://stackoverflow.com/comment/92352590
score: 1
comment on: http://stackoverflow.com/q/52713316
type: Comment
type: QuestionComment
has text: Can you point me to anything that discusses why? My guess from reading other comments is that python keeps an internal pointer to each index number (similar to if I had done ...for i in range(len(pdklist)): and then del or remove by index number. Every time an item gets deleted, the index number changes and things get out of whack. But that is a guess. Is it documented anywhere for me to read about it? Don't go to any trouble looking for it though. Just if you know off hand.

http://stackoverflow.com/comment/92209371
type: AnswerComment
has text: Thanks for pointing out to documentation, seems like uploading from disk is the only viable option
comment on: http://stackoverflow.com/a/52635338
type: Comment
score: 1

http://stackoverflow.com/q/52744190
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52744634
accepted answer: http://stackoverflow.com/a/52744634
type: Question
tagged with: sympy
possible better answer: http://stackoverflow.com/a/52747418
has answer: http://stackoverflow.com/a/52747418
answer count: 2
score: 2
downvote count: 0
favorite count: 0
upvote count: 2
has title: Sympy evalf doesn't work with 1 variable subs() in 2 variable expression
tagged with: python
has body: For a college project in python using Sympy, i need to evaluate the output of a 2 var symbolic function after partial substitution, eg: f = (x-1)/sqrt((x-10)^2+(y-10)^2) / x = 1 => f = 0 If i use an 1 var func, it works fine: &gt;&gt;&gt; from sympy import * &gt;&gt;&gt; x = symbols('x') &gt;&gt;&gt; F = 1-x &gt;&gt;&gt; F.evalf(subs={x: 1}) 0.e-125 But in the case of a 2 var function, subs doesn't seem to do the substitution right: &gt;&gt;&gt; from sympy import * &gt;&gt;&gt; x,y = symbols('x y') &gt;&gt;&gt; F = (x-1)/sqrt((x-10)**2+(y-10)**2) &gt;&gt;&gt; F.evalf(subs={x: 1}) (x - 1.0)*((x - 10.0)**2 + (y - 10.0)**2)**(-0.5) I expected F = 0 since x = 1

http://stackoverflow.com/comment/92112690
has text: Put your `fares =driver.find_elements_by_xpath("//td[@....")` inside the for loop.
comment on: http://stackoverflow.com/q/52588759
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92411649
has text: Thank you so much for taking the time to write your useful explanation. Thank you also for sharing that link, I read it all twice, very very helpful. Please, I would have one last question. If I have multiple child scripts, say child005.py, child009.py, child020.py eccetera all using "from child002 import calculation_two", is there a way for me to check how many child I need to update? (Similar to what you mention "child003.calculation_two = calculation_two" but assuming I don't know how many child are referencing calculation_two) Thanks
comment on: http://stackoverflow.com/a/52729168
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52712949
downvote count: 0
has body: You can use the str.join method instead of always printing a pipe as an ending character: for row in mult_table: print(' | '.join(map(str, row))) Or you can use the sep parameter: for row in mult_table: print(*row, sep=' | ')
answers question: http://stackoverflow.com/q/52712899
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/q/52670060
score: 0
accepted answer: http://stackoverflow.com/a/52670174
answer count: 1
tagged with: tensor
has body: My questions is rather simple but seemed to be unsolved. Input: (bs, timesteps, input_dim) --> Tensor("stack:0", shape=(?, 4, 400), dtype=float32) Layer: output = LSTM(100, input_shape = (timesteps, input_feature), return_sequence = True) (input) Expect: (bs, timesteps, output_dim) --> Tensor("gru_20/transpose_1:0", shape=(?, 4, 100), dtype=float32) Output: Tensor("gru_20/transpose_1:0", shape=(?, ?, 100), dtype=float32) Why does Keras not infer the number of timesteps, even it receives an input_shape? When I use the model summary the result it shows has the correct output shape: lstm_2 (LSTM) (None, 4, 100) 3232 But not during construction. So, when I want to unstacked the Tensor to a list of Tensors for every timesteps * (bs, 10) by using unstack(output, axis=1)] I receive ofc this error: ValueError: Cannot infer num from shape (?, ?, 100) Where is my mistake? BTW. Adding TimeDistributed(Dense(100))(questions) results in the correct output dim: Tensor("time_distributed_17/Reshape_1:0", shape=(?, 4, 100), dtype=float32) but not an option because of shared weights. If not, what is the workaround?
has comment: http://stackoverflow.com/comment/92270112
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52670174
has title: KERAS: Get a SLICE of RNN timesteps with return_sequence = True
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92270509
tagged with: keras

http://stackoverflow.com/comment/92158518
has text: What's the definition of a typo? Do you consider "diagonal" a typo of diagnose?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52612059

http://stackoverflow.com/q/52726572
score: 4
has comment: http://stackoverflow.com/comment/92413841
has comment: http://stackoverflow.com/comment/92378582
has comment: http://stackoverflow.com/comment/92392312
tagged with: python
favorite count: 0
tagged with: selenium-chromedriver
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92378562
tagged with: selenium
has body: in my project we are using stripe for payments. Payment form looks like this: https://stripe.com/docs/stripe-js/elements/quickstart We use the same test card nb value : 4242 4242 4242 4242 to test payments. The problem is that sometimes selenium send keys: 4242 4242 4242 4224 ! I cant figure out whats going on, when running locally on browser, everything works fine. Setup: chromedriver 2.41 - Chrome headless mode Running tests on Travis, Python 3.6 Selenium 3.12 Is the headless mode a problem? or iframe? or maybe something else. stripe_form = WebDriverWait(driver, 120).until(EC.presence_of_element_located((By.NAME, '__privateStripeFrame3'))) driver.switch_to.frame(stripe_form) fill_form_field(driver, 'cardnumber', '4242424242424242') fill_form_field(driver, 'exp-date', '04 / 20') fill_form_field(driver, 'cvc', '123') fill_form_field(driver, 'postal', '12345') driver.switch_to.default_content() with wait_for_page_load(driver, timeout=120): driver.find_element_by_id('submitBtn').click()
type: Question
upvote count: 4
has title: Distorted string value in python selenium test with python 3
downvote count: 0
has comment: http://stackoverflow.com/comment/92587728
has comment: http://stackoverflow.com/comment/92396282

http://stackoverflow.com/comment/92273864
type: QuestionComment
score: 0
has text: @anubhava passing pos to `.match` makes it start matching from that pos
comment on: http://stackoverflow.com/q/52671935
type: Comment

http://stackoverflow.com/a/52610029
answers question: http://stackoverflow.com/q/52609724
type: Answer
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92154603
has body: This might not be the most optimal but should do the trick: import re from collections import OrderedDict my_string = '''DecodingIndex[ 1] PresentationIndex[ 2] DecodingIndex[ 2] PresentationIndex[ 3] DecodingIndex[ 3] PresentationIndex[ 1]''' my_list = list(my_string.split("\n")) my_dict = {} for x in my_list: match = re.search("\[\s*(\d+)\s*\]$", x) my_dict[match.group(1)] = x ordered_dict = OrderedDict(sorted(my_dict.items(), key=lambda t: t[0])) print(ordered_dict) The part that might be slow for you is reading the file in? This should all run very fast. I'm starting with a string assuming you can get the file into a string. I split the string on \n but you can also just read the file in so each line is an item in the list. Then I loop it and regex match for that number you want to sort by. Make that value the key in a dict. Then using collections sort the dictionary by the key. All done! Hope that helps.
has comment: http://stackoverflow.com/comment/92157102
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52609724

http://stackoverflow.com/comment/92191601
type: Comment
comment on: http://stackoverflow.com/a/52627018
score: 0
type: AnswerComment
has text: I would prefer to add some noise, not add a specific value.

http://stackoverflow.com/comment/92123278
type: QuestionComment
score: 1
has text: Similar to this question? https://stackoverflow.com/questions/52535609/circle-detection-without-overlaping/52536189#52536189
comment on: http://stackoverflow.com/q/52591762
type: Comment

http://stackoverflow.com/comment/92149444
has text: @DizietAsahi What I want is to plot a point based on a condition (once the time of the row is greater than the time on the slider, the point should be plotted). In the example you provided, the update function only operates on the x and y variables (coordinates).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52606313
type: QuestionComment

http://stackoverflow.com/comment/92164537
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52614955
has text: ...whereas for the sizes you can just use `ls -l`/`dir`, and `unzip -t` (on UNIX) to check whether the file still has a valid ZIP footer.
score: 0

http://stackoverflow.com/comment/92226200
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52646902
score: 0
has text: Sounds like you want a dictionary like `{'a': 3, 'b': 2}`, not separate variables `a` and `b`.

http://stackoverflow.com/q/52655283
has comment: http://stackoverflow.com/comment/92242490
favorite count: 0
tagged with: memory-management
tagged with: python
accepted answer: http://stackoverflow.com/a/52655949
has body: Does Matlab have any equivalent to Python's id function? I tried some Python-like syntax to create a copy of a Matlab table and was surprised that it actually created a table with a variable whose value was the table, and whose variable name was the table variable identifier. I'm trying to get a sense of how assignment works in Matlab, whether it is by reference or creates a copy, and I'd like to get the address of the object if at all possible.
tagged with: matlab
score: 4
type: AnsweredQuestion
upvote count: 5
tagged with: memory
downvote count: 1
type: Question
has title: Matlab equivalent for Python's id function
answer count: 1
has comment: http://stackoverflow.com/comment/92243332
has answer: http://stackoverflow.com/a/52655949

http://stackoverflow.com/comment/92390730
has text: You could replace that lazy dot star with `[^#]*`.
comment on: http://stackoverflow.com/a/52732203
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92160177
type: Comment
comment on: http://stackoverflow.com/q/52606751
type: QuestionComment
has text: @NerdGiraffe That's interesting. Maybe you could try to generate the values in a loop, like `for func, layer in zip(funcs, model.layers):`, instead of a list comprehension, and print the `layer` before calling each `func`, so at least you have an idea if any of the layers can be evaluated and where it is failing.
score: 0

http://stackoverflow.com/comment/92205752
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52610828
type: Comment
has text: The fact that you are in test mode does not matter. Test mode only ignores dependencies among tasks (to not be confused with a dry-run test mode). Here what happens is that the BashOperator executes in a temporary folder (see https://airflow.apache.org/_modules/airflow/operators/bash_operator.html). If you want to make it work, use an absolute path instead. For example, if you run `date > ~/date.txt` inside the BashOperator, you will see a date.txt file in your home folder.

neural-network
tags question: http://stackoverflow.com/q/52732523
tags question: http://stackoverflow.com/q/52643184
tags question: http://stackoverflow.com/q/52708764
tags question: http://stackoverflow.com/q/52632647
tags question: http://stackoverflow.com/q/52678215
tags question: http://stackoverflow.com/q/52738146
tags question: http://stackoverflow.com/q/52682511
tags question: http://stackoverflow.com/q/52727944
tags question: http://stackoverflow.com/q/52666142
tags question: http://stackoverflow.com/q/52733031
tags question: http://stackoverflow.com/q/52677919
tags question: http://stackoverflow.com/q/52607063
type: Tag
tags question: http://stackoverflow.com/q/52636328
tags question: http://stackoverflow.com/q/52690303
tags question: http://stackoverflow.com/q/52617334
tags question: http://stackoverflow.com/q/52601631
tags question: http://stackoverflow.com/q/52737844
tags question: http://stackoverflow.com/q/52735975
tags question: http://stackoverflow.com/q/52716910
tag name: neural-network
tags question: http://stackoverflow.com/q/52673987

http://stackoverflow.com/comment/92391312
type: Comment
has text: Since you are able to install it through pycharm it seems to be a version mismatch issue. Try to use python 3.6 it is much more stable. And use a virtual environment.
comment on: http://stackoverflow.com/a/52718964
score: 0
type: AnswerComment

http://stackoverflow.com/q/52701932
tagged with: dataframe
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92330339
tagged with: numpy
has title: How to delete rows having same value in more than 3 columns
has answer: http://stackoverflow.com/a/52702330
downvote count: 0
score: 1
favorite count: 0
has body: I have below Data Frame. A B C D E F G 1 4 9 4 6 9 8 2 2 2 2 2 5 9 2 2 2 2 2 2 2 2 6 9 5 4 4 5 2 8 1 9 5 8 9 2 2 2 5 6 3 6 I need output as below: A B C D E F G 1 4 9 4 6 9 8 2 6 9 5 4 4 5 2 8 1 9 5 8 9 2 2 2 5 6 3 6 It means rows having more than three columns as same value should be deleted. We can see in the Second and Third rows are having 5 and 7 columns as same value respectively . We need to delete those rows. Could any please help me.
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/52702296
tagged with: python
has answer: http://stackoverflow.com/a/52702110
has comment: http://stackoverflow.com/comment/92330872
answer count: 3
upvote count: 1
linked to: http://stackoverflow.com/q/46256279
has comment: http://stackoverflow.com/comment/92330383
has comment: http://stackoverflow.com/comment/92330442

http://stackoverflow.com/q/52609243
downvote count: 0
has body: I want to do something like this: def f(ind, region, matrix): ... Parameter ind is placeholder or Tensor and contains coordinate x, y of central element, region is tuple of integers that represents shape of region. And you need to calculate indices and get region from matrix. Example: ind = [2, 2] region = [3, 3] matrix = [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5]] indices = tf.placeholder(tf.in32, shape=...) region = [3, 3] mat = tf.placeholder(tf.float32, shape=...) res = f(indices, region, mat) with tf.Session() as sess: r = sess.run(res, feed_dict={ indices: ind, mat: matrix }) Result is: r = [[2, 2, 2], [3, 3, 3], [4, 4, 4]] because central element on (2, 2) is 3, and region of size 3 by 3 around is given by result r.
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92278497
tagged with: python
has title: TensorFlow slice Tensor
answer count: 0
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92153145

http://stackoverflow.com/comment/92122586
comment on: http://stackoverflow.com/q/52592935
type: Comment
type: QuestionComment
has text: @DavidZemens I am assuming that there is an underlying technical or practical reason why the library is implemented in this way? If so I am expecting an answer which would explain why this is the case.
score: 0

http://stackoverflow.com/a/52678695
has body: I don't think you understand decorators. Let's make a minimal example. def my_decorator(some_function): def new_function(*args, **kwargs): 'announces the result of some_function, returns None' result = some_function(*args, **kwargs) print('{} produced {}'.format(some_function.__name__, result)) return new_function # NO FUNCTION CALL HERE! @my_decorator def my_function(a, b): return a + b my_function(1, 2) # will print "my_function produced 3" We have a simple function my_function which returns the sum of its two arguments and a decorator which will just print out the result of whatever function it decorates. Note that @my_decorator def my_function(a, b): return a + b is equivalent to def my_function(a, b): return a + b my_function = my_decorator(my_function) Since my_decorator accepts a function as an argument (here we are giving it my_function) and returns a new function new_function (without calling it!), we effectively override my_function because we reassign the name to whatever my_decorator returns. In action: &gt;&gt;&gt; my_function(1, 2) my_function produced 3 Note that at every point in the example when a function is called, it happens with the parentheses-syntax. Here are all the function calls that happen in the first block of code I posted, in order: my_decorator(my_function) is called and the return value is reassigned to the name my_function. This either happens through the @ syntax or more explicitly in the equivalent code snippet. my_function(1, 2) is called. At this point, my_function is the new_function that got returned by the decorator. Brain-parse it as new_function(1, 2). Inside the body of new_function, the argument we gave to my_decorator is called (result = some_function(*args, **kwargs)) which happens to be the value of my_function before the reassignment that happened in step 1. print is called. If you want to understand how new_function is holding on to some_function despite my_decorator already having returned from its call, I suggest lo…
answers question: http://stackoverflow.com/q/52678357
downvote count: 0
type: Answer
upvote count: 6
score: 6

http://stackoverflow.com/comment/92291430
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52681443
has text: :) Sorry, I am not sure I have done that before. I will look now. Your comment is well noted and I will make sure I provide a copy and run code next time. I learn everyday.
score: 0

http://stackoverflow.com/q/52637821
has body: I need to run a few batch files that setup a lot of environment variables and paths. Then I run my application that requires those environment variables and paths to be specified. If I am doing this on DOS it is as simple as running these batch files in series and then running my command. But I need to wrap this up in python. Once the Popen() call for setup.bat is done, the next Popen() call with my command does not find this environment. How do I solve this problem other than recreating all the environment manually in the python script? The problem specifically for me is I need to run the compiler setup batch files (like Intel and Visual Studio) and then run make that uses these compilers on windows. Thanks, -Sachin
has comment: http://stackoverflow.com/comment/94628070
type: UnansweredQuestion
has title: How to run setup batch file from python and carry over the environment to later commands?
answer count: 0
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/5469301
score: 0
has comment: http://stackoverflow.com/comment/92209283

http://stackoverflow.com/q/52669277
has body: How can I do if: a = np.array([[1,2,3],[5,6,7]]) b = np.array([0,1]) I search to concatenate a and b so as the result would be: np.array([1,2,3,0],[5,6,7,1]) Thanks a lot
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52669317
has answer: http://stackoverflow.com/a/52669783
accepted answer: http://stackoverflow.com/a/52669783
score: 2
type: AnsweredQuestion
has title: Concatenate np.arrays python
upvote count: 3
downvote count: 1
linked to: http://stackoverflow.com/q/17428621
type: Question
possible better answer: http://stackoverflow.com/a/52669317
tagged with: numpy
has answer: http://stackoverflow.com/a/52669624
answer count: 3

http://stackoverflow.com/a/52692334
has comment: http://stackoverflow.com/comment/92320334
type: Answer
answers question: http://stackoverflow.com/q/52689144
has comment: http://stackoverflow.com/comment/92318732
has comment: http://stackoverflow.com/comment/92326561
upvote count: 1
has comment: http://stackoverflow.com/comment/92320753
score: 1
accepted answer of: http://stackoverflow.com/q/52689144
has comment: http://stackoverflow.com/comment/92320789
type: AcceptedAnswer
downvote count: 0
has body: It seems normal because Ansible does not refer to Python virtual environment in your case: ansible python module location = /usr/local/Cellar/ansible/2.6.3/libexec/lib/python2.7/site-packages/ansible executable location = /usr/local/bin/ansible-playbook In virtualenv non-installed packages are initialized from real system environment. So you can achieve it by setting up Ansible within virtualenv Have a look at this example: my_user@my_machine:~$ ansible --version ansible 2.6.3 ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] After installation of Ansible in virtualenv (py_venv) my_user@my_machine:~$ pip install ansible==2.5.5 Ansible refers to the paths of Python virtual environment: (py_venv) my_user@my_machine:~$ ansible --version ansible 2.5.5 ansible python module location = /home/my_user/py_venv/local/lib/python2.7/site-packages/ansible executable location = /home/my_user/py_venv/bin/ansible python version = 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] ps: Need to deactivate and activate again the virtualenv once to load the Ansible from virtual environment after the installation.

http://stackoverflow.com/comment/92193284
comment on: http://stackoverflow.com/q/52629639
has text: Generally `Max retries` is when you have an endless recurrtion, correct me if I'm wrong `auth.login()` is a recurrtion with no break point.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92328178
type: QuestionComment
has text: Thanks you for the comment @jdehesa. I have edited the question. I'm having some troubles when I'm trying to use the Tensorflow Dataset API instead of feed_dict because I'm having more overfitting in my results. I also think that this is a precision problem but maybe I'm doing something wrong with the tensorflow API.
comment on: http://stackoverflow.com/q/52698202
score: 0
type: Comment

http://stackoverflow.com/q/52647131
has body: I am using Google Cloud OCR for reading text from images of printed documents (currently), which uses the client.text_detection() attribute. However, I want to modify the model so it can recognize both handwritten and printed text. The handwritten part needs the client.document_text_detection() attribute. How do I combine the two?
type: Question
has comment: http://stackoverflow.com/comment/92228163
tagged with: google-cloud-platform
answer count: 1
tagged with: ocr
has title: Google Cloud OCR for both printed and handwritten data
score: 0
has answer: http://stackoverflow.com/a/52673678
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52673678
tagged with: http://stackoverflow.com/tag/json
tagged with: google-cloud-storage

http://stackoverflow.com/comment/92388714
score: 1
has text: To agree, `%s` is roughly equivalent to `{!s}`, but by no means `{}` for the general case.
type: AnswerComment
comment on: http://stackoverflow.com/a/52731763
type: Comment

http://stackoverflow.com/a/52703339
type: AcceptedAnswer
type: Answer
has body: After a bit of after thought it seems to me that what you are trying to achieve is not the main purpose of keras , and while it is entirely possible to do this in keras , creating the custom loss function and maintaining its flow goes out of scope of keras , I recommend that you switch to tensorflow entirely and if needed use the tf.layers for simplicity , I have also created the custom loss function , though i recommend that you try changing it to suite your needs better. import tensorflow as tf import numpy as np x=np.random.randn(5,5,3) x=x.reshape(1,*x.shape) y_val=np.random.randn(1,3) inputv=tf.placeholder(tf.float32,shape=(None,5,5,3)) y=tf.placeholder(tf.float32,shape=(None,3)) w=tf.Variable(tf.truncated_normal([1,3,3,1],stddev=0.1),name="W") b=tf.Variable(tf.constant(0.1,shape=[3]),name="B") conv=tf.nn.conv2d(inputv,w,strides=[1,1,1,1],padding="SAME") act=tf.nn.relu(conv+b) flat=tf.contrib.layers.flatten(act) w1=tf.Variable(tf.truncated_normal([75,3],stddev=0.1),name="W") b1=tf.Variable(tf.constant(0.1,shape=[3]),name="B") logits=tf.nn.relu(tf.matmul(flat,w1)+b1) loss=tf.reduce_mean(tf.concat([tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits[0][1:],labels=y[0][1:]),tf.losses.mean_squared_error(y[0][0],logits[0][0])],0)) train_step=tf.train.AdamOptimizer(1e-4).minimize(loss) sess=tf.Session() sess.run(tf.global_variables_initializer()) val=sess.run((logits,loss,train_step),feed_dict={inputv:x,y:y_val}) sess.close()
has comment: http://stackoverflow.com/comment/92365141
has comment: http://stackoverflow.com/comment/92334298
accepted answer of: http://stackoverflow.com/q/52698670
score: 0
answers question: http://stackoverflow.com/q/52698670

http://stackoverflow.com/q/52620175
has title: Integrate airbrake with Python
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92196422
has comment: http://stackoverflow.com/comment/92299021
tagged with: airbrake
has answer: http://stackoverflow.com/a/52644295
type: Question
has comment: http://stackoverflow.com/comment/92174181
has body: When I'm trying to integrate python logging with airbrake, I get following errors: main.py import pybrake from config2.config import config airbrake_handler = None def filter_airbrake_msgs(notice): if config.environment in ['production', 'staging']: return notice return None def config_airbrake(): print(config.py_brake) notifier = pybrake.Notifier( project_id=config.py_brake.project_id, project_key=config.py_brake.project_key ) config_airbrake() ENV=development python3 main.py Error : ERROR pybrake get_git_revision failed: [Errno 2] No such file or directory: '/user/xxx/xxx/xxx/.git/HEAD'
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/52619417
upvote count: 3
answers question: http://stackoverflow.com/q/52619344
downvote count: 0
has comment: http://stackoverflow.com/comment/92211426
type: Answer
has body: Reshaping your df2 makes it a lot easier to do a straightforward merge: In [42]: df2.set_index("dates").unstack().to_frame("value") Out[42]: value dates aud 01-Jan 0.72 02-Jan 0.73 03-Jan 0.74 30-Jan 0.71 gbp 01-Jan 1.29 02-Jan 1.30 03-Jan 1.40 30-Jan 1.26 eur 01-Jan 1.15 02-Jan 1.16 03-Jan 1.17 30-Jan 1.18 In this form, you just need to match the df1 fields with df2's new index as such: In [43]: df1.merge(df2.set_index("dates").unstack().to_frame("value"), left_on=["currency", "dates"], right_index=True) Out[43]: dates currency amount value 0 02-Jan aud 100 0.73 1 03-Jan gbp 330 1.40 You can also left merge it if you don't want to lose missing data (I had to fix your df1 a little for this: In [44]: df1.merge(df2.set_index("dates").unstack().to_frame("value"), left_on=["currency", "dates"], right_index=True, how="left") Out[44]: dates currency amount value 0 02-Jan aud 100 0.73 1 03-Jan gbp 330 1.40 2 04-Jan eur 500 NaN
has comment: http://stackoverflow.com/comment/92219668
has comment: http://stackoverflow.com/comment/92210865
score: 3

django-orm
tags question: http://stackoverflow.com/q/52699407
tags question: http://stackoverflow.com/q/52731018
tags question: http://stackoverflow.com/q/52685896
type: Tag
tags question: http://stackoverflow.com/q/52610283
tags question: http://stackoverflow.com/q/52639277
tags question: http://stackoverflow.com/q/52713608
tags question: http://stackoverflow.com/q/52619441
tags question: http://stackoverflow.com/q/52705904
tag name: django-orm
tags question: http://stackoverflow.com/q/52745415
tags question: http://stackoverflow.com/q/52694844

http://stackoverflow.com/a/52681335
answers question: http://stackoverflow.com/q/52681196
has comment: http://stackoverflow.com/comment/92291786
has comment: http://stackoverflow.com/comment/92291084
type: Answer
has comment: http://stackoverflow.com/comment/92291955
has comment: http://stackoverflow.com/comment/92292137
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92291397
has comment: http://stackoverflow.com/comment/92291171
upvote count: 1
has comment: http://stackoverflow.com/comment/92291723
has body: Your username and key is either not provided or invalid. Goto https://www.kaggle.com/username/account and create new API token. kaggle.json file will be downloaded. Place it in ~/.kaggle/kaggle.json or C:\Users\User\.kaggle\kggle.json. Also, you have to click "I understand and accept" in Rules Acceptance section for the data your going to download.

http://stackoverflow.com/comment/92198381
has text: To draw a horizontal line you can use [ax.axhline()](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.axhline.html)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52632356

http://stackoverflow.com/q/52720594
tagged with: computational-geometry
has body: Given a rectangle R1 and a list of of rectangles R2,R3,.... How can I find all rectangles that are connected with the main rectangle R1. I don't just need the rectangle that are directly connected to R1 but also all that are indirectly connected to R1. For Example if R2 is connected to R1 and R3 is connected to R2. R3 is considered connected to R1. Rectangles are given in the form (xmin, ymin, xmax, ymax). All rectangles are parallel to the axis. Rectangles are considered connected when they are either overlapping or touching. When they just touch in the corner they are not considered connected. Example: ____________ _111________ _11122______ ____22______ ____22______ ____333333__ ____22______ __55___4444_ __55___4444_ In this example R1,R2,R3 are connected with each other. So I need to return R1,R2,R3. R4, and R5 are not connected. An obvious solution would be to compare each each rectangle with eachother O(n^2). But I think there should be faster solutions. I have tried to use Implement a sweep line algorithm with an Interval Tree. But it is to slow. I need a solution in O(n log n)
has comment: http://stackoverflow.com/comment/92366727
upvote count: 1
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/92366344
has comment: http://stackoverflow.com/comment/92366516
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52720940
score: 1
favorite count: 0
tagged with: python
has title: How can I find all rectangles adjacent to particular rectangle on a given list of rectangles?
type: UnansweredQuestion

http://stackoverflow.com/q/52708275
answer count: 1
downvote count: 0
favorite count: 0
tagged with: responsive
type: UnansweredQuestion
tagged with: holoviews
tagged with: python
has answer: http://stackoverflow.com/a/54535916
score: 2
upvote count: 2
tagged with: bokeh
type: Question
tagged with: charts
has title: Python Holoviews responsive chart with sizing_mode property
has body: I'm using Holoviews and Bokeh and have an issue. Using Bokeh I can specify the sizing_mode="scale_width" property, so my charts will be responsive. And it works fine now. But I couldn't find anything like this for Hovowiews. boxwhisker = hv.BoxWhisker(df, ['cyl', 'origin'], 'mpg', label='') boxwhisker.options(show_legend=False, height=200, sizing_mode='scale_width') renderer = hv.renderer('bokeh') boxChart = renderer.get_plot(boxwhisker).state boxChart.name = 'boxChart' curdoc().add_root(boxChart) sizing_mode='scale_width' is second line is not working, so I have my chart size fixed, not responsive. Is the any solution for it?

http://stackoverflow.com/comment/92253965
has text: Yes sure , Just call your function name into robotframework . and don't forget to import your py file by using : Library test.py . you can look at my answer i have import file test.py into robotframework
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52658727

http://stackoverflow.com/a/52655848
accepted answer of: http://stackoverflow.com/q/52655732
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52655732
has body: That is correct. As you can read in the np.matmul documentation: Notes The matmul function implements the semantics of the @ operator introduced in Python 3.5 following PEP465.
type: Answer
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/92206933
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52636846
has text: @Kingsley this is for user input in an online console. When there are many records in JSON dictionaries and you remove last of them, you get a trailing comma and can easily forget it... So, it's better to automate such small things.

http://stackoverflow.com/comment/92259253
has text: Note that I altered your JSON by adding double quotes to values marked true and false throughout the file.
comment on: http://stackoverflow.com/a/52636811
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/52681662
accepted answer: http://stackoverflow.com/a/52681788
answer count: 1
score: 0
tagged with: lxml
tagged with: python
tagged with: parsing
has answer: http://stackoverflow.com/a/52681788
has title: access elements and attribs DIRECTLY using lxml etree
type: AnsweredQuestion
has body: Given the following xml structure: xxx <c>yyy</c> blah blah <c>another blah blah</c> How can I access directly the value of "from.b" of each "a" without loading first "from" (with find()) of each "a"? As you can see there are exactly the same elements under "from" and "to". So the method findall() would not work as I have to differentiate where the value of "b" is coming from. I would like to get the method of direct access because if I have to load each child element (there is a lot) my code would be quite verbose. And in addition in my case performance counts and I have a lot of XML docs to parse! So I have to find the fastest method to go through the document (and store the data into a DB) Within each "a" element there is exactly 1 "from" element and within each "from" element there is exactly 1 "b" element. I have no problem to do this with lxml objectify, but I want to use etree because first I have to parse the XML document with etree because I have to validate first the xml schema against an XSD doc and I do not want to reparse the whole document again.
type: Question

http://stackoverflow.com/comment/92371608
type: AnswerComment
has text: I like this solution however the sentence may have zero or more parenthetical sentences. On my bad, I should have clarified this in the question
score: 0
comment on: http://stackoverflow.com/a/52714364
type: Comment

http://stackoverflow.com/comment/92365608
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52716299
has text: @muze so what do you want as output when lines merge? you define lines as 2 points, and if they merge, you will have 1 line with 3 points.
type: Comment

http://stackoverflow.com/q/52630920
tagged with: python
has body: I have built a site in virtual env using django and have followed the steps from AWS document for deploying the site. I have deployed my site to AWS web server using Elastic Beanstalk and have setup a python environment running 3.6 and django 2.1.1. I have pulled the logs and am getting the following error: Traceback (most recent call last): File "/opt/python/current/app/weddingProject/wsgi.py", line 12, in &lt;module&gt; from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' Target WSGI script '/opt/python/current/app/weddingProject/wsgi.py' cannot be loaded as Python module. I have read other posts and they are saying that django is not installed however, the requirements.txt file does have it listed as a package to install. So I am not sure whats causing the issue and I dont know how to check the server to ensure it is installed. When I run pip freeze > requirements.txt I do see django listed as a package to install. I run eb deploy and for some reason django is not being installed.
score: 4
has answer: http://stackoverflow.com/a/64469153
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92196124
has answer: http://stackoverflow.com/a/65096881
has answer: http://stackoverflow.com/a/52701822
has comment: http://stackoverflow.com/comment/92195242
type: Question
has comment: http://stackoverflow.com/comment/92199377
has comment: http://stackoverflow.com/comment/92195964
has answer: http://stackoverflow.com/a/66902281
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/92195579
has comment: http://stackoverflow.com/comment/92196055
has comment: http://stackoverflow.com/comment/92195757
upvote count: 4
has comment: http://stackoverflow.com/comment/92195244
accepted answer: http://stackoverflow.com/a/52701822
possible better answer: http://stackoverflow.com/a/66902281
linked to: http://stackoverflow.com/q/7225900
has answer: http://stackoverflow.com/a/52785785
downvote count: 0
has title: ModuleNotFoundError: No module named 'django
tagged with: amazon-elastic-beanstalk
favorite count: 0
has comment: http://stackoverflow.com/comment/92196043
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92195995
has comment: http://stackoverflow.com/comment/92195678
has comment: http://stackoverflow.com/comment/92195248
answer count: 5
tagged with: django

http://stackoverflow.com/q/52603221
has body: Im trying to map CO2 levels based on public data from NASA on global map and depict those values as (long,lat,value) as topographic map, based on the data and by using Panoply software, this is what my plot should look like: The data is in .nc4 format and read correctly, however I cant get the data plot Im using Cartopy API &amp; following this example:(https://scitools.org.uk/cartopy/docs/latest/gallery/waves.html#sphx-glr-gallery-waves-py). Also I do not want to use Basemap. Attempt # 1: See Python code below: from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt import numpy as np import cartopy.crs as ccrs """ function that download each OCO - 2 data that is in .nc4 format from file "subset_OCO2_L2_ABand_V8_20180929_010345.txt" which is list of links for all data with date range 2015 - 09 - 01 to 2016 - 01 - 01# make sure that you have a valid user name &amp; password by registering in https: //earthdata.nasa.gov/ #implementation based on http: //unidata.github.io/netcdf4-python/#section1""" def download_oco2_nc4(username, password, filespath): filespath = "C:\\Users\\Desktop\\oco2\\oco2_LtCO2_150831_B8100r_171009083146s.nc4" dataset = Dataset(filespath) print(dataset.file_format) print(dataset.dimensions.keys()) print(dataset.variables['xco2']) XCO2 = [] LONGITUDE = [] LATITUDE = [] # XCO2 XCO2 = dataset.variables['xco2'][:] print("-&gt;", type(XCO2)) print(dataset.variables['latitude']) # LATITUDE LATITUDE = dataset.variables['latitude'][:] print(dataset.variables['longitude']) # LONGITUDE LONGITUDE = dataset.variables['longitude'][:] return XCO2, LONGITUDE, LATITUDE, dataset def mapXoco2(): fig = plt.figure(figsize = (10, 5)) ax = fig.add_subplot(1, 1, 1, projection = ccrs.Mollweide()) XCO2, LONGITUDE, LATITUDE, dataset = download_oco2_nc4(1, 2, 3) dataset.close() XCO2_subset = list() counter = 0 for xco2 in XCO2: if counter &lt; 10: XCO2_subset.append(xco2) counter = counter + 1 else: break print("XCO2_subset="+str(len(XCO2_subset)))…
downvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/52603705
tagged with: cartopy
type: AnsweredQuestion
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92163934
type: Question
has title: Python Cartopy mapping
tagged with: geospatial
score: -1
has answer: http://stackoverflow.com/a/52603705
tagged with: python

http://stackoverflow.com/q/52619153
has comment: http://stackoverflow.com/comment/92172532
type: Question
has answer: http://stackoverflow.com/a/52619484
possible better answer: http://stackoverflow.com/a/52619301
accepted answer: http://stackoverflow.com/a/52619484
upvote count: 1
has answer: http://stackoverflow.com/a/52625291
favorite count: 0
has body: So I'm currently creating a program that requires me to format call functions back to classes. The one issue I'm running into is I cannot return an item's position in a list of multiple lists. I'll give you an example: class Global(): str_input = "" str_input_prv_word = "" str_input_nxt_word = "" prv_word = "" cur_word = "" nxt_word = "" class Dog(): wolf = [['fat', 'small'],[1, 3]] input = "That's a small wolf" def lis_str(): ##### SPLIT INPUT STRING INTO DUPLICATE LISTS ##### Global.str_input = input.split() Global.str_input_prv_word = input.split() Global.str_input_nxt_word = input.split() lis_str() def ya_done(): ##### WHY CAN'T I FIND THE POSITION? :( ##### print(Global.prv_word) print(Global.cur_word) print(Global.nxt_word) ##### PRINT POSITION OF ADJECTIVE DESCRIBING DOG IN DOG LIST ##### exec(f"""if Global.prv_word in Dog.{Global.cur_word}: print(Dog.{Global.cur_word}.index('{Global.prv_word}'))""") def create_words(): ##### CREATE NEXT WORD FOR GLOBAL CLASS ##### if len(Global.str_input_nxt_word) != 0: if len(Global.nxt_word) == 0: Global.nxt_word = Global.str_input_nxt_word.pop(1) if len(Global.nxt_word) != 0: Global.nxt_word = Global.str_input_nxt_word.pop(0) if len(Global.str_input_nxt_word) == 0: None ##### CREATE CURRENT WORD AND PREVIOUS WORD FOR GLOBAL CLASS ##### if len(Global.str_input) != 0: if len(Global.cur_word) != 0: Global.prv_word = Global.str_input_prv_word.pop(0) Global.cur_word = Global.str_input.pop(0) if len(Global.str_input) != 0: create_words() ##### CREATE THE FINAL PREVIOUS WORD ##### else: ya_done() create_words() Now this is just an example, I wrote it very quickly but I still face the exact same issue. Now if I remove the second list in the Dog list i.e. [1, 3] Example: class Dog(): wolf = ['fat', 'small'] It runs fine and returns the value "1" as it should for the word "small." How can I find the position of an item in a list within a list? Any help would be greatly appreciated! Thank you.
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/92172649
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52619301
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52619338
type: AnsweredQuestion
has title: How do I use .index to search for an item's position in list within a list?

http://stackoverflow.com/q/52679970
tagged with: contour
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: image-thresholding
tagged with: opencv
score: 1
has title: How to define threshold in opencv inorder to get the whole line together including space in python
type: Question
has answer: http://stackoverflow.com/a/52703184
has body: I want to draw a green rectangle on the whole line including space on this image. In order to do this, I'm thresholding the image in such a way. But this is not allow me to get the whole line in contour and unluckily getting an output in such a way. Please help me out with this guys! Thanks

http://stackoverflow.com/q/52691035
has title: Replace Nan with coefficient for last number?
possible better answer: http://stackoverflow.com/a/52691506
type: Question
answer count: 2
favorite count: 0
accepted answer: http://stackoverflow.com/a/52691206
tagged with: python
has comment: http://stackoverflow.com/comment/92309038
has body: I have a list: [1, 3 ,5, 7, NaN, NaN, NaN, 15, NaN] I also have growth rate, let’s say it is : 0.5 . I want my list to be filled with last number before NaN multiplied by 0.5 + 1. It’s is basically ffil * 1.5. But I don’t understand how to turn that into python code. Can someone help?
linked to: http://stackoverflow.com/q/944700
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52691506
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52691206
score: -2

http://stackoverflow.com/comment/92378979
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52720802
type: Comment
has text: @Jamin I have updated my code for the windows side of things. I am still reviewing linux.

http://stackoverflow.com/a/52720550
score: 2
has body: It's just np.maximum(A, 0). Contrary to np.max function, it accepts two arguments, and compares them element-wise. In your case, since the second argument is a scalar value, the comparison will happen by broadcasting it.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52720467
downvote count: 0
has comment: http://stackoverflow.com/comment/92366196
type: Answer
answers question: http://stackoverflow.com/q/52720467
upvote count: 2
has comment: http://stackoverflow.com/comment/92366144

http://stackoverflow.com/comment/92200142
type: QuestionComment
has text: I am not having a access to PC, so I can't replicate for now.
comment on: http://stackoverflow.com/q/52633245
score: 0
type: Comment

http://stackoverflow.com/q/52712121
has comment: http://stackoverflow.com/comment/92350767
has body: I'm given a .csv file with three data separated by comma. For example, the data looks like this: transaction, client, amount 1,1,10.50 2,1,3.0 3,1,2.75 4,2,90.0 5,3,25.0 6,3,0.05 I need to make a dictionary so that the output would be something like this: {1: {1: 10.50, 2: 3.0, 3: 2.75}, 2: {4: 90.0}, 3: {5: 25.0, 6: 0.05}} Also, is there any way to do it with a loop or a built in function similar to map? Note, that the second column of each line is supposed to be the main key. Thanks in advance. I'm going crazy trying to figure it out!
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52712350
accepted answer: http://stackoverflow.com/a/52712350
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52712535
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52712535
has title: I need to make an automated 3d dictionary in python
score: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/92326647
type: Comment
comment on: http://stackoverflow.com/a/52699761
type: AnswerComment
score: 0
has text: did your automation scroll to the element with JS executor from the example i provided ? p.s. i have update the answer with actions class move & click.

http://stackoverflow.com/a/78953792
answers question: http://stackoverflow.com/q/52708470
type: Answer
has body: I just had to use, import numpy as np from numpy import * everything worked fine, was able to run pi.
score: 0
has comment: http://stackoverflow.com/comment/139233562

cluster-analysis
tags question: http://stackoverflow.com/q/52732600
tags question: http://stackoverflow.com/q/52591137
tags question: http://stackoverflow.com/q/52721662
tags question: http://stackoverflow.com/q/52665061
tags question: http://stackoverflow.com/q/52722423
tag name: cluster-analysis
type: Tag

http://stackoverflow.com/q/52742586
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
tagged with: tensorflow
type: Question
upvote count: 2
has title: tf.layers.dense underperforms low-level api?
answer count: 1
has body: I've built a simple NN using TF that supposes to learn a quadratic equation. Surprisingly, tf.layers.dense underperforms actually writing the NN myself, but I can't seem to understand why. I would very much appreciate it someone can point to what it is I'm missing - here's the code: Data generation import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf import matplotlib.pyplot as plt from sklearn.utils import shuffle def f(x): return x**2-6*x+9 def data_generator_const_sigma(x,sigma,samples): return np.random.normal(f(x),sigma,samples) x_vals = np.arange(1,5.2,0.2) x_arr = np.array([]) y_arr = np.array([]) samples = 50 for x in x_vals: x_arr = np.append(x_arr, np.full(samples,x)) y_arr = np.append(y_arr, data_generator_rel_sigma(x,0.1,samples)) x_arr, y_arr = shuffle(x_arr, y_arr) x_test = np.arange(1.1,5.1,0.2) plt.figure(figsize=(7,7)) plt.grid(True) plt.xlabel('x') plt.ylabel('f(x)') plt.scatter(x_arr,y_arr) plt.plot(x_vals,map(f,x_vals),c='m') Output: Low level API: def nn_layer(prev_layer, weights, bias, activation=None): layer = tf.add(tf.matmul(prev_layer,weights),bias) if activation == 'tanh': layer = tf.nn.tanh(layer) elif activation == 'relu': layer = tf.nn.relu(layer) return layer hidden_layers_size = [12,12] epochs=1000 batch_size=50 learning_rate=0.0003 display_step=50 w = dict() b = dict() tf.reset_default_graph() L = len(hidden_layers_size) + 2 _ls = [1]+hidden_layers_size+[1] for i in range(1,L): w[i] = tf.get_variable(name='w'+str(i), shape=[_ls[i-1],_ls[i]], initializer=tf.contrib.layers.xavier_initializer()) b[i] = tf.get_variable(name='b'+str(i), shape=_ls[i], initializer=tf.zeros_initializer()) x = tf.placeholder(name='x',shape=(None,1),dtype=tf.float32) y = tf.placeholder(name='y',shape=(None,1),dtype=tf.float32) layer = x for i in range(1,L): if i != L-1: layer = nn_layer(layer,w[i],b[i],'tanh') else: layer = nn_layer(layer,w[i],b[i]) output = layer cost = tf.reduce_mean(tf.losses.mean_squared_error(labels=y,predi…
favorite count: 0
has answer: http://stackoverflow.com/a/52755149

http://stackoverflow.com/comment/92249498
type: AnswerComment
has text: I tried an alternate longer term solution and converted my data to sql
comment on: http://stackoverflow.com/a/52590344
type: Comment
score: 0

http://stackoverflow.com/q/52614854
type: Question
has body: I am creating a form that allows users to edit an event saved to a django database. The problem is when it runs the code, a new instance is created in the database, the old one remains in the database and both are then available to view in the site Below is (some of) the HTML form that is used to call the edit view and edit the instance in the database &lt;div class="modal-footer"&gt; &lt;form action="edit/" method="POST"&gt; {% csrf_token %} &lt;input type="hidden" name="event_edit_id" id="event_edit_id"&gt; &lt;input class="btn btn-primary btn-block" type="submit" value="Save Changes"/&gt; &lt;/form&gt; &lt;/div&gt; Next, is the View that is used to edit the event for the id sent with the form: def edit(request): if request.method == "POST": event_id = int(request.POST.get('event_edit_id')) event = Events.objects.get(pk=event_id) form = AddEventForm(request.POST or None, instance=event) if form.is_valid(): form.save() return redirect('calendar') I know I am missing something but I just can't see it, any help appreciated! EDIT I've noticed that when the code is submitted for edit, it goes straight to /calendar/ instead of /calendar/edit so this is the urls file I use to map the files urlpatterns = [ path('', views.calendar, name="calendar"), path('delete/', views.delete, name="delete"), path('edit/', views.edit, name="edit"), ]
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52615127
has answer: http://stackoverflow.com/a/52616093
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django Edit Form Creates New Instance
has comment: http://stackoverflow.com/comment/92164532

http://stackoverflow.com/a/52696532
score: 1
type: Answer
answers question: http://stackoverflow.com/q/52696075
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52696075
has body: First, you didn't grid your result Label. Secondly, you can change your save() function to modify the result text everytime. from tkinter import * #Create window that is 500x500 window = Tk() window.geometry("500x500") #This is the final command that is outputted def save(): result.config(text="/" + var2.get() + " " + entryx1.get() + " " + entryy1.get() + " " + entryz1.get() + " " + entryx2.get() + " " + entryy2.get()+ " " + entryz2.get() + " " + var1.get()) #This is what you call when you want to display the dropdown input var2 = StringVar() #Creating the dropdown drop2 = OptionMenu(window,var2,"fill","setblock") drop2.configure(font=("Arial",10)) #This makes the text that displays in the window coordx1 = Label(window,text="First X Coordinate: ") coordy1 = Label(window,text="First Y Coordinate: ") coordz1 = Label(window,text="First Z Coordinate: ") coordx2 = Label(window,text="Second X Coordinate: ") coordy2 = Label(window,text="Second Y Coordinate: ") coordz2 = Label(window,text="Second Z Coordinate: ") result = Label(window,text=save) #This makes the text boxes that the user types in entryx1 = Entry(window) entryy1 = Entry(window) entryz1 = Entry(window) entryx2 = Entry(window) entryy2 = Entry(window) entryz2 = Entry(window) #This is the submit button submit = Button(window,text="Submit",command=save) #Second dropdown variable var1=StringVar() #Creation of second dropdown list drop1 = OptionMenu(window,var1,"destroy","hollow","keep","outline","replace") drop1.configure(font=("Arial",10)) dropdownLabel = Label(window,text="Selector: ") dropdownLabel2 = Label(window,text="Command: ") #This says what goes where. 'E' and 'W' represent East and West coordx1.grid(row=1,sticky=E) coordy1.grid(row=2,sticky=E) coordz1.grid(row=3,sticky=E) coordx2.grid(row=4,sticky=E) coordy2.grid(row=5,sticky=E) coordz2.grid(row=6,sticky=E) entryx1.grid(row=1,column=1) entryy1.grid(row=2,column=1) entryz1.grid(row=3,column=1) entryx2.grid(row=4,column=1) entryy2.grid(row=5,column=1) entry…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52711721
has body: I'd try making the first option clause non-capturing: (?:\(.*\))|( +)
type: Answer
answers question: http://stackoverflow.com/q/52711543
score: 0

http://stackoverflow.com/comment/92113920
type: QuestionComment
type: Comment
score: 1
has text: Please update your question with code which shows where this `logger` comes from. Also, which line does the error refer to? You should also update the question with the full error traceback.
comment on: http://stackoverflow.com/q/52589404

http://stackoverflow.com/q/52717994
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92390664
tagged with: weekday
has body: I have a dataframe that represents this: I need to create another column 'Mark' and here is why it is complicated. For the value 'C' execution day is Sunday 8/11/2018. The next day would be Monday 9/11/2018. So I need to calculate the weekdays values of the previous week. For this case I need to calculate 1/11/2018,2/11/2018,3/11/2018,4/11/2018 and 5/11/2018. However, if the next day of execution day is Friday or Saturday I would need to take the values of the previous week 'Friday' and 'Saturday'. For example, B executes on Thursday 12/11/2018'. The day after is 'Friday'. So I need to calculate the average of the previous week's Fridayand Saturday which are 6/11/2018 and 7/11/2018 Initially I did not had the Day column, which I added afterwords by using df['Execution']=pd.to_datetime(df['Execution']) df['Day']=df['Execution'].dt.weekday_name And I can get to the point where it prints something if execution date matches with one of the column dates. Here is the code- for j,row in df.iterrows(): x=str(row['Execution']) x=x[slicing] for i, val in enumerate (df.columns.values): print(df.columns[i]) if i&lt;l1: val=str(val) val=val[slicing] if x==val: #Execution date matches column date print('yay') I am trying to learn python on my own and I have started by learning pandas dataframe. However, Now I am lost and could not figure out the logic to proceed. Can anyone enlighten me the way?
has title: How to compare dataframe dates with the values of row and column keeping weekdays and holidays apart
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52732780
upvote count: 0
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/92390243
has comment: http://stackoverflow.com/comment/92390524
tagged with: pandas
has comment: http://stackoverflow.com/comment/92390468
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52732780
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/92390508

http://stackoverflow.com/comment/92213506
score: 0
type: AnswerComment
has text: There are a lot of good tutorials. E.g. check https://www.programiz.com/python-programming/methods/string/format
type: Comment
comment on: http://stackoverflow.com/a/52640376

http://stackoverflow.com/q/52727547
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52762285
linked to: http://stackoverflow.com/q/4568704
downvote count: 0
score: 1
tagged with: mysql
has answer: http://stackoverflow.com/a/52729218
type: Question
accepted answer: http://stackoverflow.com/a/52727691
has body: I am trying to print each row from a table using print function to print each row. select_stmt = "SELECT user,password FROM account" mycursor.execute(select_stmt) myresult = mycursor.fetchall() for row in myresult: print (row) Currently it prints in a haphazard fashion: (None, 'A***9****') (None, None) ('usertest', 'pwtest') How do you pad each column so it looks more legible? Thanks
upvote count: 1
has title: Python - How do you pad the output of a mysql table
favorite count: 0
has answer: http://stackoverflow.com/a/52727691
answer count: 3
has comment: http://stackoverflow.com/comment/92380564
linked to: http://stackoverflow.com/q/10195139
possible better answer: http://stackoverflow.com/a/52729218
has comment: http://stackoverflow.com/comment/92380343

http://stackoverflow.com/q/52655623
score: 4
has body: I am using this dataset and reading it through pandas dataframe. I need to work with the paperAbsrtract column only which has some missing data. filename = "sample-S2-records" df = pd.read_json(filename, lines=True) abstract = df['paperAbstract'] Because there are some missing data in the abstract dataframe, I want to remove those rows that are empty. So following the documentation, I do below abstract.dropna(how='all') But this doesn't remove those empty rows. They are still there in the abstract dataframe. What am I missing?
upvote count: 4
tagged with: pandas
has comment: http://stackoverflow.com/comment/92262813
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92242639
has comment: http://stackoverflow.com/comment/116029959
favorite count: 0
has comment: http://stackoverflow.com/comment/92247023
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63458212
tagged with: python
has title: Removing an empty row from pandas dataframe
linked to: http://stackoverflow.com/q/29314033
type: Question
has comment: http://stackoverflow.com/comment/92277185
tagged with: dataframe

http://stackoverflow.com/a/52672315
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52672268
upvote count: 17
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52672268
score: 16
has body: you could catch the exception and log the error at this time, so if another exception occurs you can log it as well, and propagate the exception upstream. try: # some code if not condition_met: missing = set_one - set_two raise ValueError('Missing keys: {}'.format(missing)) except Exception as e: # or ValueError to narrow it down logging.error(str(e)) raise # propagate the exception again note than logging an exception without logging the traceback leaves something unfinished, specially if the exception is caught and handled upstream. It's very likely that you're never going to fix that particular error.

http://stackoverflow.com/comment/92360290
comment on: http://stackoverflow.com/q/52716299
score: 0
type: Comment
has text: @hadik I meant lines arent parallel to each other. and thanks for url i will check it
type: QuestionComment

http://stackoverflow.com/comment/92274007
type: QuestionComment
comment on: http://stackoverflow.com/q/52672046
score: 0
has text: Are you sure that all dependencies were installed successfuly?
type: Comment

http://stackoverflow.com/comment/92239150
type: Comment
score: 2
has text: You can use `ffmpeg` with x264 lossless encoding and `-crf 0` like this https://trac.ffmpeg.org/wiki/Encode/H.264#LosslessH.264
comment on: http://stackoverflow.com/q/52653441
type: QuestionComment

http://stackoverflow.com/comment/92397634
score: 0
comment on: http://stackoverflow.com/a/52725059
type: AnswerComment
has text: If you add word boundary to the lookbehind it would capture only the first 5 characters of things like `abc12345`: `\b[a-z]{1,4}[0-9]{1,4}(?<=\b\w{5})`
type: Comment

http://stackoverflow.com/comment/92304708
score: 0
type: Comment
type: QuestionComment
has text: What bands do your rasters have? For photographic images the bands are usually red, green, and blue. But lots of other combinations exist, including non-visible frequencies. For example, [LANDSAT rasters have 11 bands](https://landsat.gsfc.nasa.gov/landsat-8/landsat-8-bands/), which can be combined in various interesting ways.
comment on: http://stackoverflow.com/q/52688614

http://stackoverflow.com/comment/92115849
has text: You can prepare a regular expression, and the match "in bulk". Regular expressions can (it depends on how it is implemented) do this in linear time of the *string to match*, not the dictionary size.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52590564

http://stackoverflow.com/comment/92390437
comment on: http://stackoverflow.com/q/52732744
score: 1
has text: And frankly: if you have to restart a process on every data change you might want to rethink your architectural design.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52728928
tagged with: flask
has title: Setting up a database handler for flask logger
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52748303
tagged with: python
upvote count: 6
type: AnsweredQuestion
has body: I'm looking to set up a logging database handler that will save all the information that Flask currently outputs into the console (unhandled exceptions, werkzeug, sqlachemy), as well as my custom logging messages. I'm having trouble setting this all up. Questions: 1) Why doesn't the simulated Arithmetic Error in the about view doesn't get picked up by any logger? 2) Why doesn't the werkzeug logger correctly display the server loaded and only has output 'error on request %s' for the simulated Aritmetic error. 3)Is there any simpler way just to pipe everything that is written by the Flask server (and its components) to a DB? Appreciate the responses and any other suggestion. What I've done until now: models.py class Log(DB.Model): __tablename__ = 'logs' id = DB.Column(DB.Integer, primary_key=True) # auto incrementing logger = DB.Column(DB.String(100)) # the name of the logger. (e.g. myapp.views) level = DB.Column(DB.String(100)) # info, debug, or error? trace = DB.Column(DB.String(4096)) # the full traceback printout msg = DB.Column(DB.String(4096)) # any custom log you may have included created_at = DB.Column(DB.DateTime, default=DB.func.now()) # the current timestamp def __init__(self, logger=None, level=None, trace=None, msg=None): self.logger = logger self.level = level self.trace = trace self.msg = msg def __unicode__(self): return self.__repr__() def __repr__(self): return "&lt;Log: %s - %s&gt;" % (self.created_at.strftime('%m/%d/%Y-%H:%M:%S'), self.msg[:50]) core.py """ This module contains the core objects of the application: the Flask (APP) object and the database object. """ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from samo.config import CONFIG_BY_NAME, ENVIRONMENT APP = Flask(__name__) APP.config.from_object('samo.config') APP.config.from_object(CONFIG_BY_NAME[ENVIRONMENT]) DB = SQLAlchemy(APP) DB.create_all() LOGIN_MANAGER = LoginManager() LOGIN_MANAGER.init_app(APP) LOGIN_MANAGER.session_protect…
score: 6
type: Question
accepted answer: http://stackoverflow.com/a/52748303

http://stackoverflow.com/comment/92224971
type: Comment
type: QuestionComment
has text: @toti08, I see your point. I had played around with the .json file in a few different formats (some with unique sections such as question1, question2, etc.) but I ended up thinking that the duplicates would make it easier to select a random file. I suppose I was mistaken, thanks for highlighting the need for unique sections toti08!
comment on: http://stackoverflow.com/q/52645142
score: 0

http://stackoverflow.com/a/58696248
downvote count: 0
answers question: http://stackoverflow.com/q/52661315
has body: If you are using any third-party firewall applications like Simplewall, then make sure that python.exe has permission to access internet. I had the same problem after I uninstalled Simplewall because it left filters enabled, so I had to install it again then it worked.
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/92229438
comment on: http://stackoverflow.com/q/52648593
has text: As [`deceze`](https://stackoverflow.com/users/476/deceze) said, what's wrong with defining a setter for the property? By the way, this would totally work on Python 2.x even without a setter (which is not a good thing, but still...)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52733461
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/52733240
score: 7
has body: You'd need to use np.concatenate (which can cancatenate arrays of different shape, unlike the various np.*stack methods). Then, you need to use np.broadcast_to to get that (5774,) shaped array to (5774, 15, 1) (because concatenate still needs all the arrays to have the same number of dimensions). C = np.concatenate((A, np.broadcast_to(np.array(B)[:, None, None], A.shape[:-1] + (1,))), axis = -1) Checking: A = np.random.rand(5774, 15, 100) B = np.random.rand(5774) C = np.concatenate((A, np.broadcast_to(np.array(B)[:, None, None], A.shape[:-1] + (1,))), axis = -1) C.shape Out: (5774, 15, 101)
accepted answer of: http://stackoverflow.com/q/52733240
type: AcceptedAnswer
upvote count: 8

http://stackoverflow.com/q/52737526
has comment: http://stackoverflow.com/comment/92410325
tagged with: python
has body: I am trying to make a real time graph using matplotlib and have tried it successfully. But there is one issue what I faced. I was not able to zoom the data while the data is shown on graph. That is blocking my observation. See the following is my code: plt.ion() fig = plt.figure() fig.set_size_inches(30,10) ax1 = fig.add_subplot(111) ax2 = ax1.twinx() #plt.show(block=False) plt.show() first_time = 1 def main(): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: server.bind((bind_ip, bind_port)) server.listen(8) # max backlog of connections print (('Listening on {}:{}').format(bind_ip, bind_port)) while True: client_sock, address = server.accept() print (('Accepted connection from {}:{}').format(address[0], address[1])) client_handler = ThreadWithReturnValue( target=handle_client_connection, args=(client_sock,) # without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject ) client_handler.start() y_forecast_pred,candles = client_handler.join() ax1.clear() ax2.clear() if(first_time): line1, = ax1.plot(y_forecast_pred[:,0],color='blue', label='Y Forecast 1 first buffer',marker=".") candlestick2_ohlc(ax2,candles.o.values[seq_len:],candles.h.values[seq_len:],candles.l.values[seq_len:],candles.c.values[seq_len:],width=0.6,alpha=0.7) else: line1.set_ydata(y_forecast_pred[:,0]) candlestick2_ohlc(ax2,candles.o.values[seq_len:],candles.h.values[seq_len:],candles.l.values[seq_len:],candles.c.values[seq_len:],width=0.6,alpha=0.7) ax1.legend() ax1.relim() plt.draw() plt.pause(0.001) except KeyboardInterrupt: pass finally: server.close() The screen gets hanged up. Please help me in getting the plotting smoothly and capable of zooming in real time.
answer count: 0
score: 0
has title: Not able to zoom data using Matplotlib Python
has comment: http://stackoverflow.com/comment/92427878
tagged with: matplotlib
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35215335
has comment: http://stackoverflow.com/comment/92404776
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92409914
type: Question

http://stackoverflow.com/a/52698476
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52697394
downvote count: 0
answers question: http://stackoverflow.com/q/52697394
score: 1
has body: The grid_forget() method will cause the grid geometry manager to stop managing a widget. So if you put your widgets for a row into a frame and grid that, you can grid_forget the frame to have all the widgets in the frame removed from display together. However, you might want to investigate the Ttk treeview which can display tabular information or the tktable package (see this answer).

http://stackoverflow.com/q/52713217
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92364760
has title: In matplotlib, what's the best way to synchronize axes limits of subplots (similar to matlab `linkaxes()`)?
has body: I have a two-column figure, where the left-hand-side and the right-hand-side column have different scales so I can't use a global statement of fig, ax = plt.subplots(nrows=5, ncols=2, sharex=True, sharey=True). My goal is to synchronize x and y limits for each column of the subplots, so that when I zoom in and out in jupyter with widget backend, each column is synchronized on their own. Here are one solution based ideas I found on stack overflow: import numpy as np import matplotlib.pyplot as plt # Make fake data # fake data for left-hand-side subplots column x1 = np.linspace(0, 4 * np.pi, 50) y1 = np.tile(np.sin(x1), (5, 1)) # fake data for left-hand-side subplots column x2 = 2 * x1 y2 = 2 * abs(y1) # Plotting fig, ax = plt.subplots(nrows=5, ncols=2) fig.subplots_adjust(wspace=0.5, hspace=0.1) ax_ref1, ax_ref2 = (ax[0, 0], ax[0, 1]) for axi, y1_i in zip(ax[:, 0].flatten(), y1): axi.plot(x1, y1_i) # Link xlim and ylim of left-hand-side subplots ax_ref1.get_shared_x_axes().join(ax_ref1, axi) ax_ref1.get_shared_y_axes().join(ax_ref1, axi) ax_ref1.set(title='Left-hand-side column') for axi, y2_i in zip(ax[:, 1].flatten(), y2): axi.plot(x2, y2_i) # Link xlim and ylim of Right-hand-side subplots ax_ref2.get_shared_x_axes().join(ax_ref2, axi) ax_ref2.get_shared_y_axes().join(ax_ref2, axi) ax_ref2.set(title='Right-hand-side column') plt.show() This will generate a two-column image that allows the desirable x and y limit synchronization. But I wonder if there is a more concise way to do this--something similar as matlab's linkaxes() function. Thanks!
tagged with: matplotlib
linked to: http://stackoverflow.com/q/17329292
type: Question
has comment: http://stackoverflow.com/comment/92354037
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52724656
favorite count: 0
score: 3
has comment: http://stackoverflow.com/comment/92354078
tagged with: python
has comment: http://stackoverflow.com/comment/92374544

http://stackoverflow.com/q/52714874
type: UnansweredQuestion
type: Question
has body: I have set up with Python a tool to retrieve Average Monthly Search volume of provided keywords (and generated ideas), however I cannot seem to find a way one could get these results by device type (desktop, mobile, tablet). The documentation is pretty confusing in this regard, one would think the Platform criterion could be used for the desired result (https://developers.google.com/adwords/api/docs/reference/v201802/TargetingIdeaService.Platform), but I have not found a way to send it and the only info I found on this was a Google dev saying it's not possible (but that was in 2017). Has anyone been able to successfully get Average Search Volume from the TargettingIdeaService by device type? Is it even possible?
answer count: 1
tagged with: google-ads-api
has answer: http://stackoverflow.com/a/52735743
has title: Google Adwords API TargettingIdeaService device type
tagged with: python
score: 0

http://stackoverflow.com/comment/92201281
score: 0
type: Comment
type: QuestionComment
has text: You want to put a delay in between the `get_info` calls so they are not made all at once, right?
comment on: http://stackoverflow.com/q/52623178

http://stackoverflow.com/q/52634073
has answer: http://stackoverflow.com/a/52635538
type: Question
has comment: http://stackoverflow.com/comment/92203755
possible better answer: http://stackoverflow.com/a/52635538
downvote count: 0
has comment: http://stackoverflow.com/comment/92204230
answer count: 3
score: 3
has answer: http://stackoverflow.com/a/52655770
has comment: http://stackoverflow.com/comment/92204293
favorite count: 0
has comment: http://stackoverflow.com/comment/92203602
has answer: http://stackoverflow.com/a/52634148
has title: How can I spot class redefinitions?
has comment: http://stackoverflow.com/comment/92203903
tagged with: python
has comment: http://stackoverflow.com/comment/92201438
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52655770
upvote count: 3
has body: Here is a very simple setup: class A(object): x = 1 class B(object): x = 2 class C(object): x = 3 class B(B): x = 4 class C(object): x = 5 print A.x, B.x, C.x which outputs the expected: 1, 4, 5 is it possible to detect that B has been 'redefined' but C has been 'replaced'? either during the creation phase or subsequently by inspecting the objects? These classes are being used as configuration objects, there is a loader class above this which imports the module and then introspects to find the classses and their attributes which are then used by the application to instance named parameters. e.g. class tcp_port(number): minimum = 1024 maximum = 2048 really python is just being used as a convenient scripting language to define parameters in the main app. These files are available for edit by that most dangerous of people: The Customer So the requirement is to be able to detect at run time if a class has (accidentally) reused a name that has already been defined, but to safely pass the occasional case where a class is redefined, but then tweaks or add some attribute: class tcp_port(tcp_port): maximum = 4096 So... I'm hoping for some runtime sanity checker rather than a lint-like solution. Also, this needs to happen when the class is defined, not instanced. ... is there global function which gets called to create a class (or any other object)? a bit like have a __new__ but in the global context?

http://stackoverflow.com/comment/92266672
score: 0
type: QuestionComment
type: Comment
has text: you need to loop over your input string for eg: if name of string is `'Number' with value = 'abf573'` and test whether this `char` is in `valid_char( string) = abcdefABCDEF012..9` if its not print('invalid') and break the loop.........
comment on: http://stackoverflow.com/q/52668241

http://stackoverflow.com/comment/92162497
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52613897
has text: Ruling out an invalid shell, the only other reason I can think of that will cause that error is an invalid `cwd`, but you already ruled that out too. So still strange.

http://stackoverflow.com/a/62064822
type: Answer
score: 2
has body: df.apply() is almost as slow as df.iterrows(), both are not recommended, see How to iterate over rows in a DataFrame in Pandas --> search for "An Obvious Example" of @cs95a and see the comparison graph. As the fastest ways (vectorization, Cython routines) are not easy to implement, the 3rd best and thus usually best solution is list comprehension: # print 3rd col def some_func(row): print(row[2]) df['result_col'] = [some_func(*row) for row in zip(df'col_1', 'col_2',... ,'col_n'.to_numpy())] or # print 3rd col def some_func(row): print(row[2]) df['result_col'] = [some_func(row[0]) for row in zip(df'col_1', 'col_2',... ,'col_n'.to_numpy())] or # print 3rd col def some_func(x): print(x) df['result_col'] = [some_func(row[0][2]) for row in zip(df'col_1', 'col_2',... ,'col_n'.to_numpy())] Further reading: Memory efficient way for list comprehension of pandas dataframe using multiple columns list comprehension in pandas What is the most efficient way to loop through dataframes with pandas? Loop through dataframe one by one (pandas) EDIT: Please use df.iloc and df.loc instead of df[[...]], see Selecting multiple columns in a Pandas dataframe
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52607864

http://stackoverflow.com/q/52643556
tagged with: selenium-chromedriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52644136
upvote count: 2
tagged with: selenium
type: Question
linked to: http://stackoverflow.com/q/40661739
possible better answer: http://stackoverflow.com/a/67305073
has answer: http://stackoverflow.com/a/67305073
has body: I'm using chromedriver in headless mode. I compile the script using pyinstaller as one exe file. Everything works fine, except that I get the following console window whenever I open a chrome page: I've tried the options --windowed alone, --noconsole alone, --windowed and --noconsole together but I still get this window. How can I get rid of it?
answer count: 2
has answer: http://stackoverflow.com/a/52644136
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: pyinstaller
has title: Getting rid of chromedirver console window with pyinstaller
tagged with: python
score: 2

http://stackoverflow.com/a/52632575
accepted answer of: http://stackoverflow.com/q/52632522
upvote count: 3
score: 3
has body: You can just iterate through your string with a list comprehension, then use ''.join: alphabet = "abcdefghijklmnopqrstuvwxyz ?" s = 'THIS is a t#est' &gt;&gt;&gt; ''.join([i if i in alphabet else '?' for i in s]) # '???? is a t?est' Or as a function: def clean_text(xcode): return ''.join([i if i in alphabet else '?' for i in xcode]) As a different approach, you can think about using a regex: import re s = 'THIS is a t#est' &gt;&gt;&gt; re.sub('[^abcdefghijklmnopqrstuvwxyz ?]', '?',s) # '???? is a t?est'
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52632522
type: Answer

http://stackoverflow.com/q/52723251
tagged with: mysql-connector-python
favorite count: 0
tagged with: python-3.x
type: Question
has title: MySQL Connector/Python: How to use the start_transaction() method?
tagged with: python
answer count: 3
tagged with: mysql
downvote count: 1
has answer: http://stackoverflow.com/a/76599786
has answer: http://stackoverflow.com/a/67890609
has body: I am trying to access some records using MySQL Connector/Python but I am unable to understand how start_transaction() is used. I would be great if someone could shed some light on uses cases where it is required. Update: After reading the docs carefully it looks like, the start_transaction() method is only required when autocommit=True. Is that true? I am still confused over this and documentation doesn't provide any examples.
has answer: http://stackoverflow.com/a/52723551
type: UnansweredQuestion
upvote count: 4
score: 3

http://stackoverflow.com/q/52745705
has title: How to select random key with common values?
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52745853
has comment: http://stackoverflow.com/comment/92416537
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52746284
accepted answer: http://stackoverflow.com/a/52746284
downvote count: 6
type: AnsweredQuestion
has body: so I'm trying to create an AI just for fun, but I've run into a problem. Currently when you say Hi it will say Hi back. If you say something it doesn't know, like Hello, it will ask you to define it, and then add it to a dictionary variable knowledge. Then whenever you say Hello, it translates it into Hi and will say Hi. But, I want it to loop through what you've defined as hi and say a random thing that means hi. So if you tell it Hello, What's Up, and Greetings all mean hi, it will work to say any of them and it will return Hi. But how would I make it say either Hi, Hello, What's Up, or Greetings once it knows them? (just examples) I have tried this: def sayHello(): for index, item in enumerate(knowledge): if knowledge[item] == 'HI': print(knowledge[index] + "! I'm Orion!") However I get this error: Traceback (most recent call last): File "python", line 28, in &lt;module&gt; File "python", line 12, in sayHello KeyError: 0
type: Question
has answer: http://stackoverflow.com/a/52745853
answer count: 2
upvote count: 0
tagged with: key-value
has comment: http://stackoverflow.com/comment/92416113
tagged with: random
score: -6
has comment: http://stackoverflow.com/comment/92416133
favorite count: 0

http://stackoverflow.com/a/52616962
has comment: http://stackoverflow.com/comment/92171882
upvote count: 1
has body: You can using .left get all bins s1=pd.Series([1,2,3,4,5,6,7,8,9]) s2=pd.Series([2,3,4,6,1]) a=pd.qcut(s1,10).unique() bins=[x.left for x in a ] + [np.inf] pd.cut(s2,bins=bins)
score: 1
accepted answer of: http://stackoverflow.com/q/52616845
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52616845
type: Answer

setup.py
tags question: http://stackoverflow.com/q/52646055
tags question: http://stackoverflow.com/q/52660176
tags question: http://stackoverflow.com/q/52735269
tag name: setup.py
type: Tag
tags question: http://stackoverflow.com/q/52694006

http://stackoverflow.com/q/52708334
has answer: http://stackoverflow.com/a/52708505
downvote count: 1
has body: I have a pandas DataFrame that has column which contains lists. I am trying to get the means of the lists in this column. Here is an example of what my DataFrame looks like: Loc Background 0 115227854 [0.000120481927711] 1 115227854 [0.000129117642312, 0.000131429072111, 0.00016... 2 115227855 [0.000123193166886] 3 115227855 [0.000142845482001, 0.000184789750329, 0.00018... 4 115227856 [0.000173490631506] I would like to do something like this to set a new Mean column equal to the mean of the data in each of the lists found in the Background column: sig_vars['Mean'] = sig_vars['Background'].mean() And here is the DataFrame if needed: df = {'Background': {0: [0.00012048192771084337], 1: [0.00012911764231185137, 0.0001314290721107509, 0.000163015792154865, 0.00018832391713747646, 0.00019627513412134165, 0.00020383723596708027, 0.0002114408734430263, 0.00022564565426983117, 0.000247843759294141], 2: [0.00012319316688567673], 3: [0.00014284548200146926, 0.00018478975032851512, 0.00018864365214110544, 0.00019392685725367248, 0.00022931689046296532, 0.00023965141612200435, 0.00036566589684372596, 0.00043096760847454704, 0.0004584752423369138], 4: [0.00017349063150589867]}, 'Loc': {0: 115227854, 1: 115227854, 2: 115227855, 3: 115227855, 4: 115227856}}
type: Question
has answer: http://stackoverflow.com/a/52708432
accepted answer: http://stackoverflow.com/a/52708432
has title: Pandas mean of list within dataframe
has answer: http://stackoverflow.com/a/71227572
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52708505
has answer: http://stackoverflow.com/a/52708722
favorite count: 0
has answer: http://stackoverflow.com/a/52708578
answer count: 5
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/92143332
has text: What do you mean it "went away"? Please explain what behavior you saw. And I think you need to give more details about how you interface with the server.
score: 0
comment on: http://stackoverflow.com/q/52604512
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52673608
answers question: http://stackoverflow.com/q/52635661
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52635661
score: 2
has body: I should have been using QuerySelectField and lambda and added repr in my models. This is what worked for me: Forms.py coi_name = QuerySelectField(label='COI', query_factory=lambda: db.session.query(Coi).filter_by(active=1), get_pk=lambda coi_id: coi_id, get_label=lambda coi_name: coi_name, allow_blank=True) Models.py def __repr__(self): return '{}'.format(self.coi_name)

http://stackoverflow.com/comment/92388371
type: Comment
score: 0
has text: return (s.isdecimal())
type: QuestionComment
comment on: http://stackoverflow.com/q/52731600

http://stackoverflow.com/q/52717595
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/92363084
tagged with: facebook-ads-api
tagged with: facebook-marketing-api
tagged with: facebook
tagged with: python
score: -2
has title: getting the conversion for which the ad is optimised using fb ad insights api
downvote count: 2
has answer: http://stackoverflow.com/a/52757987
answer count: 1
type: UnansweredQuestion
upvote count: 0
has body: I am facing a very trivial problem with facebook ad_insights API. I have many campaigns running for me on facebook. They are optimised for different events, like 'purchase','initiate checkout','add to cart'. When I request the end point, I get a response similar to this, { "data": [ { "actions": [ { "action_type": "link_click", "value": 19 }, { "action_type": "offsite_conversion.fb_pixel_purchase", "value": 1 }, { "action_type": "offsite_conversion.fb_pixel_view_content", "value": 19 }, { "action_type": "post_like", "value": 88 }, { "action_type": "page_engagement", "value": 107 }, { "action_type": "post_engagement", "value": 107 }, { "action_type": "offsite_conversion", "value": 20 } ], "spend": 5.16, "account_id": "10201496xxxxxxxxxx", "campaign_name": "Link Clicks to Website (CPC)", "ad_name": "[2015/11/27] New Arrivals", "adset_name": "Custom Audience - Visitors or Lookalike - Visitors", "impressions": "2634", "date_start": "2015-11-01", "date_stop": "2015-12-01" }, ... as we can see there is offsite_conversion.fb_pixel_view_content and there is offsite_conversion.fb_pixel_purchase. Some of my campaigns are optimised for purchases and some are for view content. How can I find out which is the event that my campaign is optimised for dynamically from the API response itself?

http://stackoverflow.com/comment/92430134
score: 0
comment on: http://stackoverflow.com/q/52704023
type: Comment
type: QuestionComment
has text: works fine for me mate, try removing the requirement, maybe a version conflict?

http://stackoverflow.com/q/52698248
linked to: http://stackoverflow.com/q/28858634
has comment: http://stackoverflow.com/comment/92324428
answer count: 1
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92338356
tagged with: qliksense
favorite count: 0
has comment: http://stackoverflow.com/comment/92339766
has answer: http://stackoverflow.com/a/53096016
linked to: http://stackoverflow.com/q/49257450
type: UnansweredQuestion
has title: Qlik sense ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
linked to: http://stackoverflow.com/q/41691327
upvote count: 0
has body: I'm trying to connect Qlik sense API editor through Python with below code and I'm getting below error. OS : Mac Pyton version : 3.X ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) from websocket import create_connection import ssl senseHost = "HOST1" privateKeyPath = "/Users/ABC" ## userDirectory and userId can be found at QMC -&gt; Users userDirectory, userId = "DIR", "user1" url = "wss://" + senseHost + ":443/app" # valid certs = ({"ca_certs": privateKeyPath + "root.pem", "certfile": privateKeyPath + "client.pem", "keyfile": privateKeyPath + "client_key.pem", "cert_reqs": ssl.CERT_REQUIRED, "server_side": False }) ssl.match_hostname = lambda cert, hostname: True ws = create_connection(url, sslopt=certs, header={'X-Qlik-User: UserDirectory=%s; UserId=%s' % (userDirectory, userId)}) print ("connetced") session = ws.recv() print (session) There is similar question in StackOverFlow but there is no clear answer how it git resolved. Can anyone help here please ?
score: -1
type: Question
tagged with: openssl

http://stackoverflow.com/comment/92175505
has text: @BearBrown Thank you so much sir! It solved my problem. Sorry, just a newbie on using Python regex.
comment on: http://stackoverflow.com/q/52620752
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52607283
has comment: http://stackoverflow.com/comment/92149269
has body: I am trying to install PyFTGL, to display text in my OpenGL project. I usually install libraries using pip, but sudo pip3 install PyFTGL returns the following error: Could not find a version that satisfies the requirement PyFTGL (from versions:) No matching distribution found for PyFTGL I also tried easy_install after reading this wiki, but sudo easy_install PyFTGL returns the following error: error: Could not find suitable distribution for Requirement.parse('PyFTGL') What am I doing wrong ? I am using python3.6 on my Macbook OSX Yosemite. EDIT: after installing dependencies (FTGL, freetype, and boost-python) I still seem to miss a library. I get the following error message when running the python setup.py install command from the source code directory: ld: library not found for -lGLU clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'clang++' failed with exit status 1 Although I can already do this in python: from OpenGL.GLU import *
tagged with: ftgl
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: Installing PyFTGL: distribution not found
has comment: http://stackoverflow.com/comment/92148833
tagged with: opengl
tagged with: pyopengl
type: Question
has comment: http://stackoverflow.com/comment/92149106
score: 0

http://stackoverflow.com/q/52617381
tagged with: ldap
has body: Recently I have noticed my Django project starts up much slower comparing to a month ago, typically 5~6 seconds slower, I don't remember updating any packages and also validated on Ubuntu server that it doesn't suffer the same problem, so my only guess is that due to my MacOS upgrade. So I ran python profiler: python -m cProfile -o /tmp/result manage.py Then inspected the result using snakeviz: snakeviz /tmp/result This indicated the slowness is in the ldap package by hovering __init__.py:5: Then I went into the __init__.py and discovered that the following line took the most of the time: LIBLDAP_API_INFO = _ldap.get_option(_ldap.OPT_API_INFO) Further digging into get_option it goes into source code of _ldap.cpython-36m-darwin.so def get_option(*args, **kwargs): # real signature unknown pass Just wondering if anyone is having similar issues and how to fix it?
tagged with: python
tagged with: macos
favorite count: 0
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/97561591
has title: _ldap.get_option(_ldap.OPT_API_INFO) is slow after upgrading to MacOS Mojave
type: Question
has comment: http://stackoverflow.com/comment/129714837
score: 3
has comment: http://stackoverflow.com/comment/97417126
has comment: http://stackoverflow.com/comment/123362654
downvote count: 0
has comment: http://stackoverflow.com/comment/97415926
linked to: http://stackoverflow.com/q/43328378

http://stackoverflow.com/comment/92278701
type: QuestionComment
score: 3
has text: The OpenCV pip installer via `pip install opencv-python-contrib` do *not* have the non-free modules such as SIFT anymore. You will have to manually compile OpenCV to get access to those. Alternatively you can find an installer elsewhere that includes them.
comment on: http://stackoverflow.com/q/52669705
type: Comment

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

http://stackoverflow.com/comment/92181112
comment on: http://stackoverflow.com/a/52623835
score: 0
type: Comment
has text: As I said, 'children' can be any Gtk.Widget, not just Gtk.Entry
type: AnswerComment

http://stackoverflow.com/q/52699892
tagged with: python
tagged with: pymel
has answer: http://stackoverflow.com/a/52703845
type: Question
has body: I am currently working on a script to make a simple crane-like rig. I have a variable to define the amount of joints I want. I also have a variable for the amount of groups/controllers I want. These amounts may vary so the script would be semi-"dynamic". So what I end up with is a couple of joints (joint1, joint2, joint3, ... etc) and a couple of groups (group1, group2, group3, ... etc). My problem is that I do not know how I would go about parenting my "group1" to "joint1" and "group2" with "joint2" etc. all in one go. Since I want to be able to change the amounts of joints and groups I can't hardcode it. Any help would be appreciated :)
score: 0
has title: Parenting multiple objects by their last number, maya python
answer count: 2
tagged with: parent
tagged with: maya
has answer: http://stackoverflow.com/a/52707224
type: UnansweredQuestion

http://stackoverflow.com/a/52651071
answers question: http://stackoverflow.com/q/52636289
has comment: http://stackoverflow.com/comment/92278972
type: Answer
upvote count: 1
has body: Since you can't change the array characteristics at all, I think you're stuck with O(n^2). numpy would gain some vectorization, but would change the access for others sharing the array. Start with the innermost operation: for k in range(0,m): count += (arr[i][k] == arr[j][k]) Change this to a one-line assignment: count = sum(arr[i][k] == arr[j][k] for k in range(m)) Now, if this is truly an array, rather than a list of lists, use the array package's vectorization to simplify the loops, one at a time: count = sum(arr[i] == arr[j]) # results in a vector of counts You can now return the j indices where count[j] / m &gt; 0.7. Note that there's no real need to return i for each one: it's constant within the function, and the calling program already has the value. Your array package likely has a pair of vectorized indexing operations that can return those indices. If you're using numpy, those are easy enough to look up on this site.
score: 1
has comment: http://stackoverflow.com/comment/92336799
downvote count: 0

http://stackoverflow.com/comment/92262284
has text: I see, so initialize the value in main, not after the imports?
comment on: http://stackoverflow.com/a/52641809
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92327629
type: AnswerComment
comment on: http://stackoverflow.com/a/52700554
type: Comment
has text: That looks fine, but how do we get all values above 4, let say if have another score entry with 9
score: 0

http://stackoverflow.com/q/52679784
score: 3
tagged with: cross-validation
has body: I have a regression problem, where I am cross-validating the results and evaluating the performance. I know beforehand that the ground truth cannot be smaller than zero. Therefore, I would like to intercept the predictions, before they are fed to the score metric, to clip the predictions to zero. I thought that using the make_scorer function would be useful to do this. Is it possible to somehow post-process the predictions after cross-validation, but before applying an evaluation metric to it? from sklearn.metrics import mean_squared_error, r2_score, make_scorer from sklearn.model_selection import cross_validate # X = Stacked feature vectors # y = ground truth vector # regr = some regression estimator #### How to indicate that the predictions need post-processing #### before applying the score function??? scoring = {'r2': make_scorer(r2_score), 'neg_mse': make_scorer(mean_squared_error)} scores = cross_validate(regr, X, y, scoring=scoring, cv=10) PS: I know there are constrained estimators, but I wanted to see how a heuristic approach like this would perform.
has title: post-process cross-validated prediction before scoring
linked to: http://stackoverflow.com/q/32401493
accepted answer: http://stackoverflow.com/a/52680471
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52680471
type: Question

http://stackoverflow.com/comment/92374809
type: Comment
has text: Ok, so `classes.py will continue to live in `sample/` . I went to the linux terminal and ran `export PYTHONPATH=/path/to/project` and then `printenv | grep PYTHON` to make sure that it was there, but that doesn't seem to have been enough to make it work. Something else needs to go near the import statements but am trying to work out what..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52724409

http://stackoverflow.com/q/52676742
has answer: http://stackoverflow.com/a/52677139
favorite count: 0
has comment: http://stackoverflow.com/comment/92283259
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92284345
upvote count: 2
linked to: http://stackoverflow.com/q/3387691
accepted answer: http://stackoverflow.com/a/52677139
has comment: http://stackoverflow.com/comment/92284615
has comment: http://stackoverflow.com/comment/92284728
has body: So I am trying to pull information from a dictionary list that I made in a specific format but for the life of me I cannot create a loop that pulls the information from exactly where I need it at all, it prints nothing but I receive no errors. Here's an example: class Global(): prv_word = 'dumb' cur_word = 'dog' nxt_word = 'head' class Animal(): dog = [ {'head': {'funny': [8 , 7 , 1],'dumb': [9 , 3 , 2],'poofy': [18 , 4 , 11]}}, {'tail': {'funny': [12, 2 , 4], 'dumb': [3 , 9 , 7],'poofy':[28 , 5 , 60]}}] dog_cur = f'Animal.{Global.cur_word}' if hasattr(Animal, Global.cur_word): for list in dog_cur: if Global.nxt_word in list: adj = Global.nxt_word index = list.index(Global.nxt_word) for lis in list: if Global.prv_word in lis: adj2 = Global.prv_word index2 = lis.index(Global.prv) end = dog_cur[index][adj][adj2] print(end) ##### TROUBLESHOOT ##### ##### This works! But how do I format the loop to generate this result? ##### (print(Animal.dog[0]['head']['dumb'])) can someone help show me a way to make this loop pop up with a relevant value of [9, 3, 2]. I also don't think the formatted dog_cur variable will work... Is there another way to format that variable to equal the same result as f'Animal.{Global.cur_word}' I believe if you look at my loop, you'll be able to see I'm trying to pull the values from a list within a dictionary. In my actual program, the Global values are constantly changing so that's why I need a loop that can find those values. Help will be greatly appreciated! Thank you
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52677305
score: 1
has comment: http://stackoverflow.com/comment/92284265
has comment: http://stackoverflow.com/comment/92284655
type: Question
has title: Python: How do I format a loop to pull specific values in a dictionary list?
has comment: http://stackoverflow.com/comment/92282803
answer count: 3
possible better answer: http://stackoverflow.com/a/52677003
tagged with: python
has comment: http://stackoverflow.com/comment/92283037
has answer: http://stackoverflow.com/a/52677003
has comment: http://stackoverflow.com/comment/92282602

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

http://stackoverflow.com/q/52679046
favorite count: 0
has title: Saxon: Transformation of XML
has body: I'm transforming an XML-file using Saxon9he.jar. My original file has several attributes, such as: <w deprel="hi" head="1-1-2" id="1-1-1" lemma="Hi" pos="NN">Hi</w> <w deprel="ATTR" head="1-1-2" id="1-1-2" lemma="everyone" pos="NN">everyone</w> After the transformation, Saxon writes each attribute on a single line. But I'd like to have them on a single line, like in the original. How can I achieve this? What do I have to change in the jar-file? Thanks for any help!
tagged with: python
type: AnsweredQuestion
tagged with: saxon
upvote count: 1
downvote count: 1
type: Question
tagged with: saxon-js
has answer: http://stackoverflow.com/a/52680054
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52680054

http://stackoverflow.com/q/52742217
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52815277
has body: I'm newbie using gettext library to translate text. I want to translate the text that there is in the next file: dobles_message.py def set_message(self, language): t = gettext.translation("basketmetrics_i18n", "../i18n", fallback=True, languages=["'" + language + "'"]) t.install() _ = t.gettext self.message = _("mensaje_dd_1") To do that,first I have create dobles_message.po with this instrucction: xgettext -i dobles_message.py -o dobles_message.pot -d basketmetrics_i18n Then, I have created these directory structure i18n/es/LC_MESSAGES and i18n/en/LC_MESSAGES and I have created the .po version for each languate with these instructions: msginit -i dobles_message.pot -o ../i18n/es/LC_MESSAGES/basketmetrics_i18n.po -l es msginit -i dobles_message.pot -o ../i18n/en/LC_MESSAGES/basketmetrics_i18n.po -l en Thrid, I have change the charset and translate the text of each file. And fourth, I have created the .mo files from each .po file with this instruction in directory i18n/es/LC_MESSAGES and in directory i18n/en/LC_MESSAGES msgfmt basketmetrics_i18n.po -o basketmetrics_i18n.mo But, when I run my application instead of translate the text, muy application shows me the msgid. These is how is my structure of files and directories: And the content of my files are next ... dobles_message.pot # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR &lt;EMAIL@ADDRESS&gt;, YEAR. # #, fuzzy msgid "" msgstr "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2018-10-10 13:22+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME &lt;EMAIL@ADDRESS&gt;\n" "Language-Team: LANGUAGE &lt;LL@li.org&gt;\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: dobles_message.py:15 msgid "mensaje_dd_1" msgstr "" basketmetrics_i18n.po (English version) # Engl…
tagged with: python-3.x
type: Question
answer count: 2
tagged with: python
tagged with: gettext
has answer: http://stackoverflow.com/a/52744792
score: 0
has title: Python: Translating text shows msgid instead msgstr

http://stackoverflow.com/comment/92421939
score: 1
type: Comment
has text: In short: We need your code, here. (Not all of it, in an external link. That is what [mcve] refers to.)
type: QuestionComment
comment on: http://stackoverflow.com/q/52742364

http://stackoverflow.com/q/52714982
has title: How to create an excel file at user given location in python2.7?
has comment: http://stackoverflow.com/comment/92358686
tagged with: python-2.7
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92356889
favorite count: 0
upvote count: 0
has answer: http://stackoverflow.com/a/52715048
type: UnansweredQuestion
downvote count: 1
tagged with: xlsxwriter
score: -1
has body: Actually the path and name will be given by two user defined variable(string) while creating an excel I tried with below logic but the excel file didn't get generated at that folder location. Input_Output_Save_Folder_location = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory")) workbook = xlsxwriter.Workbook(Input_Output_Save_Folder_location +"/"+Excel_name+".xlsx")
type: Question

http://stackoverflow.com/a/52683044
downvote count: 0
answers question: http://stackoverflow.com/q/52682423
type: Answer
upvote count: 1
score: 1
has body: Although jpp has already answered most of the part, I notice that there is another 'score; column you want. arrays= [['score', -2, -2, -1, -1, 0, 0, 1, 1, 2 ,2, 'score'], [None, 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) columns = pd.MultiIndex.from_tuples(tuples, names = ['time', None ]) df = pd.DataFrame(index = ['Step 1', 'Step 2', 'Step 3', 'Step 4', 'Step 5'], columns=columns) df time score -2 -1 0 1 2 NaN one two one two one two one two one two Step 1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN Step 2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN Step 3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN Step 4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN Step 5 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN It kinda feels like a hack

http://stackoverflow.com/q/52706200
has comment: http://stackoverflow.com/comment/92339290
has comment: http://stackoverflow.com/comment/92338811
has comment: http://stackoverflow.com/comment/92338762
type: Question
has comment: http://stackoverflow.com/comment/92338765
tagged with: object
has title: Python: += strange behaviour in static method
tagged with: class
tagged with: static-methods
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/92338971
downvote count: 1
answer count: 1
has body: I've come across some strange behavior with +=, while learning about static methods. Here is my code: class Box: totalMass = 0 def __init__(self, mass): Box.totalMass += mass def getMassconsumption(): return Box.totalMass o1 = Box(2) o2 = Box(10) print(Box.getMassconsumption()) As expected it returns the value: 12 However, when I change line 4 with: Box.totalMass += 1 It returns the value: 2 Increasing the added value to 2, 3, 4 etc. gives: 4 6 8 Multiples of 2, regardless the input. Now I am pretty sure that I don't understand the code in my exercise book, nor how += works in this situation. Could someone explain what is happening here?
favorite count: 0
has comment: http://stackoverflow.com/comment/92339076
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52706325
has comment: http://stackoverflow.com/comment/92338987
tagged with: python

http://stackoverflow.com/q/52740107
tagged with: aws-lex
has answer: http://stackoverflow.com/a/52821777
downvote count: 0
has title: Send group (multiple) messages from Lambda to Lex
answer count: 1
tagged with: aws-lambda
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/52493642
score: 1
upvote count: 1
type: Question
has body: I am currently trying to send multiple messages from AWS Lambda to Lex in Python 3.6, but Lex considers my answers as incorrect. I got multiple errors such as : Received invalid response from Lambda: Can not construct instance of Message, problem: contentType must not be null "content" can not be blank Syntax error in module 'lambda_function': unexpected character after line continuation character [after trying to escape my JSON] Received invalid response from Lambda: Can not deserialize instance of java.lang.String out of START_OBJECT token at... So basically, I am doing this like this : messages = [ { 'contentType': 'PlainText', 'group': 0, 'value': 'Applying this criteria, you have %d result(s) left.' % len(json.loads(session_attributes['results'])) }, { 'contentType': 'PlainText', 'group': 1, 'value': 'What do you want to do next ?' } ] format_message('PlainText', messages) with format_message which TEMPORARILY looks like this (because I've tried many MANY things to make it work... without any success) -- but this one does not work either : def format_message(message_type, content): return {'messages': content} In the end, it gives this format of response (with other lex pre-requisites such as slots etc. but I won't display them here because I don't think it is relevant) : {'message': {'messages': [{'group': 0, 'contentType': 'PlainText', 'value': 'Applying this criteria, you have 1 result(s) left.'}, {'group': 1, 'contentType': 'PlainText', 'value': 'What do you want to do next ?'}] I have tried to convert 'messages' array into a string, send it as a JSON etc. but nothing seems to work. I read all of the documentation listed in this issue... Have someone already found a solution please ? Thank you,
tagged with: amazon-web-services

http://stackoverflow.com/comment/92128639
comment on: http://stackoverflow.com/q/52596921
has text: Iterating over the dictionary keys gives you a string of length two. Iterating over the string gives you a string of length one. Why *would* they be the same?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52743652
accepted answer: http://stackoverflow.com/a/52744107
upvote count: 1
tagged with: geojson
type: Question
answer count: 1
has body: I have a python list that looks like this: type(route) &gt;&gt;&gt;list print(route) [{'type': 'LineString', 'coordinates': [[-94.586472, 39.098705], [-64.586487, 39.098716], [-64.585969, 39.094146], [-64.586037, 39.093936], [-64.586037, 39.093936], [-64.586046, 39.093933]]}, {'type': 'LineString', 'coordinates': [[-94.581459, 39.093506], [-64.581451, 39.09351], [-64.581444, 39.093506], [-64.581459, 39.093433], [-64.581726, 39.093418], [-64.588631, 39.087582]]}, {'type': 'LineString', 'coordinates': [[-94.584312, 39.042758], [-64.584312, 39.042758], [-64.583225, 39.099256], [-64.584328, 39.09932]]}] How can I convert this into a valid GeoJSON file? I've tried test = FeatureCollection(features=route), but that created an invalid file when I later dumped it.
downvote count: 0
has answer: http://stackoverflow.com/a/52744107
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: How to Create GeoJSON from Python List of LineStrings
score: 1

http://stackoverflow.com/q/52727388
has title: How do I avoid my scipy interpolated spline from adding extraneous zeros?
tagged with: scipy
type: Question
score: 0
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52736392
tagged with: python
has body: I'm trying to fit a spline to my array: dej when I use interpolate.splrep I'm getting output that is longer, and the last x-coordinate is repeated 4 times, and their y value is 0, while the first x value is repeated 4 times, each overwriting one other data point and extending the array by 2. My whole array is 4 points longer. In [12]: len(dej[:,0]) Out[12]: 140 In [13]: len(dej[:,1]) Out[13]: 140 In [14]: moo = interpolate.splrep(dej[:,0],dej[:,1]) In [15]: len(moo) Out[15]: 3 In [16]: len(moo[0]) Out[16]: 144 In [17]: len(moo[1]) Out[17]: 144 This causes an offset in the data so the fitted spline doesn't overlay on the data. This is probably a property of smoothing, but is there a way to turn it off? image of offset fit and data

http://stackoverflow.com/a/52674741
has comment: http://stackoverflow.com/comment/92279064
has comment: http://stackoverflow.com/comment/92279073
has comment: http://stackoverflow.com/comment/92279057
accepted answer of: http://stackoverflow.com/q/52674718
score: 4
has comment: http://stackoverflow.com/comment/92279224
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92279103
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/52674718
has body: You can use pd.Series.isin with Boolean indexing: A = pd.Series([2,3,4,6,7]) B = pd.Series([4,5,6,7,8,9]) res = B[~B.isin(A)].values array([5, 8, 9], dtype=int64) Or a NumPy variant: res = B.values[~np.isin(B.values, A.values)] You can also use set.difference: res = list(set(B) - set(A)) [8, 9, 5] Note, however, using built-ins with Pandas / NumPy is usually not optimal.

http://stackoverflow.com/q/52677832
type: Question
score: 0
answer count: 1
has body: I'm developing a log analysis system. The input are log files. I have an external Python program that reads the log files and decide whether a record (line) or the log files is "normal" or "malicious". I want to use Elasticsearch Update API to append my Python program's result ("normal" or "malicious") to Elasticsearch by adding a new column called result. So I can see my program's result clearly via Kibana UI. Simply speaking, my Python code and Elasticsearch both use log files as input respectively. Now I want to update the result from Python code to Elasticsearch. What's the best way to do it? I can think of several ways: Elasticsearch automatically assigns a ID (_id) to a document. If I can find out how Elasticsearch calculates _id, then my Python code can calculate it by itself, then update the corresponding Elasticsearch document via _id. But the question is, Elasticsearch official documentation doesn't say about what algorithm it uses to generate _id. Add an ID (like line number) to the log files by myself. Both my program and Elasticsearch will know this ID. My program can use this ID to update. However, the downside is that my program has to search for this ID every time because it's only a normal field instead of a built-in _id. The performance will be very bad. My Python code gets the logs from Elasticsearch instead of reading the log files directly. But this makes the system fragile, as Elasticsearch becomes a critical point. I only want Elasticsearch to be a log viewer currently. So the first solution will be ideal in the current view. But I'm not sure if there are any better ways to do it?
accepted answer: http://stackoverflow.com/a/52678103
tagged with: elasticsearch
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52678103
has title: Best practice to update a column of all documents to Elasticsearch

http://stackoverflow.com/a/52654861
answers question: http://stackoverflow.com/q/52650006
has comment: http://stackoverflow.com/comment/92303294
score: 1
downvote count: 0
has body: You need to modify your MenuSerializer. Specifically, you need to change the restaurant field to be a CharField and also provide a source attribute. Something like the following: class MenuSerializer(serializers.ModelSerializer): restaurant = serializers.CharField(source='restaurant.name') # ... other stuff in the serializer Here, I am assuming that your Restaurant model has a name field. You can read more about Serializer fields here: https://www.django-rest-framework.org/api-guide/fields/
has comment: http://stackoverflow.com/comment/92308198
type: Answer
upvote count: 1

http://stackoverflow.com/a/52738037
has body: You have created a class but haven't called it anywhere. This is because the code for creating an instance of the class is inside the class itself. You should be very careful about indentations in python. Here's the fixed code: class Person: def __init__(self, first_name): self.first_name = first_name name = Person('John') print(name.first_name)
upvote count: 3
has comment: http://stackoverflow.com/comment/92402686
score: 3
answers question: http://stackoverflow.com/q/52737919
has comment: http://stackoverflow.com/comment/92401027
has comment: http://stackoverflow.com/comment/92402877
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52737919
type: Answer
has comment: http://stackoverflow.com/comment/92400917

http://stackoverflow.com/comment/92229949
type: Comment
type: QuestionComment
score: 0
has text: @ShadowRanger, from the perspective of the user, I just want `config.param2` to result in the newly assigned value (`new_val` in this case). When not clobbered, the property method on the parent should be evaluated. I'm only using class attributes because it results in a simple API. How would you use instance attributes here?
comment on: http://stackoverflow.com/q/52648593

http://stackoverflow.com/comment/92240338
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52654160
has text: Did you check how much time it takes for the `map_async` to complete vs how much it takes to combine the resulting dicts? I believe the time taken to combine the dicts is bigger, which means that parallelizing the first part is not really helping that much.

http://stackoverflow.com/q/52714649
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52715020
type: Question
tagged with: numpy
tagged with: image
has answer: http://stackoverflow.com/a/52755276
answer count: 2
upvote count: 1
favorite count: 0
type: UnansweredQuestion
has body: I've an image in which the boundaries of the person's body are so sharp. How can I unsharp/smooth them? When you zoom in the image the edges are so sharp. And it's binary mask looks like below.
tagged with: python
tagged with: opencv
has title: Unsharpen/smoothen the boundaries of a person'r body in an image

http://stackoverflow.com/q/52689625
downvote count: 0
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
has body: Recently, I'm building a seq2seq model with Esmiator API, but it comes out a problem that has been bothering me a few days. It will come out a ValueError when I predict twice. ... predictions = list(mymodel.predict( lambda: ev_func_with_sentence(last_result))) predictions = list(mymodel.predict( lambda: ev_func_with_sentence(last_result))) ... ... ValueError: Tensor("embedding/Cast:0", shape=(?, 3000), dtype=int32) must be from the same graph as Tensor("embedding/embeddings/Read/ReadVariableOp:0", shape=(103727, 200), dtype=float32). mymodel was defined like this: mymodel = tf.estimator.Estimator( model_fn=model_fn, model_dir=model_dir, params={ 'features': _get_features(), 'learning_rate': learning_rate }, config=tf.estimator.RunConfig( save_checkpoints_steps=1, save_summary_steps=1, ) ) Here is my input_func: def ev_data_with_sentence(last_results=None): model = Word2Vec.load(configs.WORD2VEC_FILE) datas = ev_set() if last_results is None: # A [batch * 30] array last_results = numpy.zeros([len(datas), configs.MAX_TITLE_WORD]) for data, result in zip(datas, last_results): content = data.get('content') xs = tokenization(content, is_sentence=True) X = index_word_with_sentence(xs, model) # X.shape == (?, 50, 60) yield X, result def ev_func_with_sentence(last_results): def _warp(data, labels): return {'x1': data, 'x2': labels} data = tf.data.Dataset().from_generator( lambda: ev_data_with_sentence(last_results), output_types=((tf.float32, tf.int64))) data = data.batch(configs.batch_size) data = data.map(_warp) data = data.make_one_shot_iterator() inputs = data.get_next() return inputs It makes me crazy. Help! Please!
type: Question
has title: Meet ValueError: Tensor must be from the same graph as Tensor when I predict twice

http://stackoverflow.com/comment/99949029
type: Comment
has text: I am having a weird result using your bi cubic function. When I try to interpolate an image from 512x512 to 1024x1024, there is an empty row at the bottom of the interpolated image and empty column on the right side of image. Any ideas as to why?
comment on: http://stackoverflow.com/a/52702678
score: 0
type: AnswerComment

http://stackoverflow.com/comment/122699578
has text: This is great. `Dict` and `List` are ugly and remind me of Java.
type: AnswerComment
type: Comment
score: 6
comment on: http://stackoverflow.com/a/68908479

http://stackoverflow.com/comment/92245272
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52655974
has text: yep :) this meant that python was looking relative to your system root, rather than the current directory
type: AnswerComment

http://stackoverflow.com/comment/92274073
has text: What exactly does your code do wrong? If you're getting an exception, edit the full traceback into the question. If it's providing incorrect results, provide sample input, actual output, and expected output.
comment on: http://stackoverflow.com/q/52672130
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92185329
has text: @bruno desthuilliers: I just now found out the answer.Thank you.
score: 0
comment on: http://stackoverflow.com/q/52623935
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92416647
type: QuestionComment
has text: Why are you putting `()` around the command line option?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52745701

http://stackoverflow.com/q/52665981
has comment: http://stackoverflow.com/comment/92261923
tagged with: python
has comment: http://stackoverflow.com/comment/92262028
has comment: http://stackoverflow.com/comment/92261705
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52666533
has body: I am currently working on a bigger project in python and am trying to establish structure using OOP principles. I have a parent class that contains a lot of attributes aswell as several child classes that has to utilize the attributes from the parent class. However I am having some trouble retrieving attributes from the parent class from the child class. As a simplified example this is what I want to accomplish: class A: def __init__(self, firstname): self.__firstname = firstname @property def firstname(self): return self.__firstname class B(A): def __init__(self, lastname): self.__lastname = lastname A.__init__(self) @property def lastname(self): return self.__lastname parent = A('somefirstname') child = B(parent, 'somelastname') print(child.firstname) print(child.lastname) I get the following error when executing: Traceback (most recent call last): File "classplay.py", line 23, in &lt;module&gt; child = B(parent, 'somelastname') TypeError: __init__() takes 2 positional arguments but 3 were given
type: Question
has comment: http://stackoverflow.com/comment/92262114
has title: Inheritance: Attribute from parent class
has comment: http://stackoverflow.com/comment/92261823
tagged with: inheritance
tagged with: class
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52666799
accepted answer: http://stackoverflow.com/a/52666799
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92262648
possible better answer: http://stackoverflow.com/a/52666123
has comment: http://stackoverflow.com/comment/92261738
has answer: http://stackoverflow.com/a/52666123
favorite count: 0

http://stackoverflow.com/comment/92220514
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52644046
has text: This would entirely depend on what you mean by nearest. Are these points in space or do you want the tuple with the most terms in common. What would (12, 1, 8, 41) be closer to?
score: 4

plot
tags question: http://stackoverflow.com/q/52729730
tags question: http://stackoverflow.com/q/52703805
tags question: http://stackoverflow.com/q/52668309
tags question: http://stackoverflow.com/q/52601258
tags question: http://stackoverflow.com/q/52600652
tags question: http://stackoverflow.com/q/52691383
tags question: http://stackoverflow.com/q/52638835
tags question: http://stackoverflow.com/q/52699989
tags question: http://stackoverflow.com/q/52657859
tag name: plot
tags question: http://stackoverflow.com/q/52706635
tags question: http://stackoverflow.com/q/52698947
tags question: http://stackoverflow.com/q/52610966
tags question: http://stackoverflow.com/q/52652572
tags question: http://stackoverflow.com/q/52693507
tags question: http://stackoverflow.com/q/52670273
tags question: http://stackoverflow.com/q/52614090
tags question: http://stackoverflow.com/q/52729459
type: Tag
tags question: http://stackoverflow.com/q/52708759
tags question: http://stackoverflow.com/q/52736245
tags question: http://stackoverflow.com/q/52627777
tags question: http://stackoverflow.com/q/52615206
tags question: http://stackoverflow.com/q/52732472
tags question: http://stackoverflow.com/q/52646026
tags question: http://stackoverflow.com/q/52728248
tags question: http://stackoverflow.com/q/52744545
tags question: http://stackoverflow.com/q/52729169
tags question: http://stackoverflow.com/q/52653734

http://stackoverflow.com/comment/92401008
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52738194
has text: kind off this but does it stores 1,2,3,4 in a,b,c,d? and then 5,6,7,8 in next iteration?

http://stackoverflow.com/q/52679304
has answer: http://stackoverflow.com/a/52679340
linked to: http://stackoverflow.com/q/2921847
has answer: http://stackoverflow.com/a/52679364
has comment: http://stackoverflow.com/comment/92287297
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Getting rid of Parentheses of Dict and unwanted words[Python]
favorite count: 0
has body: As working on a program using Dict in Python, I am getting a format other than required: the code is as follows: a = {1:2,2:3,3:4,4:8} print(a.values()) getting an output: dict_values([2, 3, 4, 8]) here in the output, there is no requirement of "dict_values" and "{ [ ] }", How to remove these wanted things? Actually, I have tried striping but I am thinking of some professional functions to use.
type: Question
accepted answer: http://stackoverflow.com/a/52679364
answer count: 2
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/92287255
upvote count: 2
possible better answer: http://stackoverflow.com/a/52679340

http://stackoverflow.com/a/52601286
type: AcceptedAnswer
downvote count: 0
has body: Your question answer is change your code to: size_opts = json.loads(response.read().decode('utf-8'))['available_sizes'] Change at 2018-10-02 22:55 : I view your source code and found Response 503 , the reason why you got 503 is that request did not contain cookies: req = urllib.request.Request(url, headers=headers) you have update your headers. headers.update({"Cookie":cookie_value}) req = urllib.request.Request(url, headers=headers) # !!!! you need a headers include cookies !!!!
accepted answer of: http://stackoverflow.com/q/52599727
has comment: http://stackoverflow.com/comment/92156896
answers question: http://stackoverflow.com/q/52599727
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92142663
has comment: http://stackoverflow.com/comment/92141761

http://stackoverflow.com/comment/92413948
type: AnswerComment
has text: Thank you very much. I can't tell you how much this helped. PLUS! the Bonus!! Thank you.
comment on: http://stackoverflow.com/a/52744199
type: Comment
score: 0

http://stackoverflow.com/q/52696365
has comment: http://stackoverflow.com/comment/92319137
upvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Input an item and gets its REGEX in python
has comment: http://stackoverflow.com/comment/92319329
has body: I'm trying to make a stand alone application using Python and Tkinter. My work is to get all similar looking product IDs from a excel sheet using Python. I got similar looking products for a particular company XYZ. The code goes like this IDs = df1['A'].str.extract(r'\b(\d{8}s\d{2})\b' , expand = False).dropna().tolist() This helps extract all items which have "8 Number followed by s followed by 2 more numbers" like 01234567s12 or 98765432s23 But i want to do something opposite that is input the product ID and get its regex. The product ID can be anything say ABC123456 or C234-D456 So is there a code which can help me get the regex ?
score: -3
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92319871
downvote count: 3
has answer: http://stackoverflow.com/a/52778257
type: Question
possible better answer: http://stackoverflow.com/a/52697019
has answer: http://stackoverflow.com/a/52697019
accepted answer: http://stackoverflow.com/a/52778257
has comment: http://stackoverflow.com/comment/92319282
has comment: http://stackoverflow.com/comment/92319184
answer count: 2

http://stackoverflow.com/comment/92164985
has text: with a large lower bound too then.
type: AnswerComment
comment on: http://stackoverflow.com/a/52615139
type: Comment
score: 0

http://stackoverflow.com/a/52626180
upvote count: 1
has comment: http://stackoverflow.com/comment/92185818
downvote count: 0
answers question: http://stackoverflow.com/q/52626031
has comment: http://stackoverflow.com/comment/92186344
has comment: http://stackoverflow.com/comment/92186272
type: Answer
has comment: http://stackoverflow.com/comment/92185574
has comment: http://stackoverflow.com/comment/92185999
has comment: http://stackoverflow.com/comment/92185969
score: 1
has body: You can define the definition inside an __ init __ method . Something like this : class WordItem(object): ... def __init__(self, first_name, last_name): ... self.full_name = f'{first_name}_{last_name}' ... &gt;&gt;&gt; word_item = WordItem('abc','xyz') &gt;&gt;&gt; assert word_item.full_name == 'abc_xyz'
has comment: http://stackoverflow.com/comment/92185548

http://stackoverflow.com/q/52746740
has body: I am making a game scoring calculator that needs to be able to prompt a user for the number of players, and then ask for each players information, storing it for each round of scoring. The problem I have currently is how to write out a user input prompt that creates the number of Player objects given and then assigns each newly created object its own callable variable (preferably it would print the entered player name). I have tried to use input that creates an input loop based on the given number but it only asks for input without storing anything. Here is my Player class: class Player: def __init__(self, name, inca, power, power_mask, short, medium, long): self.name = name self.inca = inca self.power = power self.power_mask = power_mask self.short = short self.medium = medium self.long = long Would it be best to somehow write a def that creates a class object with all of parameters I need it stored under? If so how would I write this out?
type: Question
has comment: http://stackoverflow.com/comment/92420911
has title: Creating and storing a set # of class objects from user input
score: 0
has answer: http://stackoverflow.com/a/52748605
answer count: 1
has comment: http://stackoverflow.com/comment/92418117
tagged with: user-input
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52748605

http://stackoverflow.com/comment/92115367
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52590280
has text: Does the status (and lat./lon.) _have to_ differ as implied in your code?
type: Comment

macos
tags question: http://stackoverflow.com/q/52617381
tags question: http://stackoverflow.com/q/52680044
tags question: http://stackoverflow.com/q/52663976
tags question: http://stackoverflow.com/q/52735795
tags question: http://stackoverflow.com/q/52614207
tags question: http://stackoverflow.com/q/52682261
tags question: http://stackoverflow.com/q/52728417
tags question: http://stackoverflow.com/q/52634552
tags question: http://stackoverflow.com/q/52673733
tags question: http://stackoverflow.com/q/52637561
tags question: http://stackoverflow.com/q/52684552
tags question: http://stackoverflow.com/q/52692513
tags question: http://stackoverflow.com/q/52728792
type: Tag
tags question: http://stackoverflow.com/q/52714889
tags question: http://stackoverflow.com/q/52706769
tag name: macos
tags question: http://stackoverflow.com/q/52618482
tags question: http://stackoverflow.com/q/52601003
tags question: http://stackoverflow.com/q/52713154

http://stackoverflow.com/comment/92146293
type: QuestionComment
has text: So there is no need for indexation. If yes, then how to do so?
type: Comment
comment on: http://stackoverflow.com/q/52603939
score: 0

http://stackoverflow.com/comment/131711569
comment on: http://stackoverflow.com/q/52727207
has text: I know this is 4 years old, but type is a reserved word.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52622829
upvote count: 2
has body: You do not invoke ps with the -x flag. The -x flag is required to list all processes, even those which do not share the terminal with the ps command invocation or do not have a terminal at all.
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52621902
answers question: http://stackoverflow.com/q/52621902

http://stackoverflow.com/a/52739081
score: 1
type: Answer
upvote count: 1
has body: You're overriding the fragment function with a for loop variable, so fragment becomes a non-callable object in the next iteration of the outer loop. You should rename the fragment variable to something else: for frag in frags: sendp(l2/frag, iface=iface)
answers question: http://stackoverflow.com/q/52736851
accepted answer of: http://stackoverflow.com/q/52736851
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/52725568
answer count: 3
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52727904
type: AnsweredQuestion
score: 41
downvote count: 0
has body: So I have a dictionary: {'a': {'b': {'c': 'd', 'e': 'f'}}} I need to create a dictionary as follows: {'c':'d', 'e','f'} It can go deeper up to any level but I should always get the key value pair at the maximum depth. So I wrote a function: def boil_down_array(key, data): if type(data) == dict: for key, item in data.items(): boil_down_array(key, item) else: yield {key:data} Now the problem is, once it goes in recursion, the yield is lost. How do I yield that dictionary again? All I get is a generator which is not what I want.
has title: How to Yield in a recursive function in Python
type: Question
accepted answer: http://stackoverflow.com/a/52725662
possible better answer: http://stackoverflow.com/a/52725668
has answer: http://stackoverflow.com/a/52725668
has comment: http://stackoverflow.com/comment/92376576
has answer: http://stackoverflow.com/a/52725662
upvote count: 41

http://stackoverflow.com/a/52682745
downvote count: 0
has body: If the list elements are hashable, you can use .setdefault to build an inverse mapping like so: &gt;&gt;&gt; sample_dict = {"1": ['a','b','c'], "2": ['d','e','f'], "3": ['g','h','a']} &gt;&gt;&gt; aux = {} &gt;&gt;&gt; for k, v in sample_dict.items(): ... for i in v: ... aux.setdefault(i, []).append(k) ... &gt;&gt;&gt; [[v, k] for k, v in aux.items() if len(v) &gt; 1] [[['1', '3'], 'a']]
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52682678

http://stackoverflow.com/q/52647531
has title: how to order the stacked bar using plotnine
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/52976874
type: Question
answer count: 1
downvote count: 0
has body: I have the following dataframe import pandas as pd from plotnine import * df = pd.DataFrame({ 'variable': ['gender', 'gender', 'age', 'age', 'age', 'income', 'income', 'income', 'income'], 'category': ['Female', 'Male', '1-24', '25-54', '55+', 'Lo', 'Lo-Med', 'Med', 'High'], 'value': [60, 40, 50, 30, 20, 10, 25, 25, 40], }) df['variable'] = pd.Categorical(df['variable'], categories=['gender', 'age', 'income']) An I am using the following code to get the stacked bar plot (ggplot(df, aes(x='variable', y='value', fill='category')) + geom_col() ) The above code was taken from here How can I change the order in each of the categories. E.g. I want the age 1-24 to be at the bottom of the age stacked bar
tagged with: pandas
favorite count: 0
tagged with: plotnine
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/92167236
type: QuestionComment
has text: @Aran-Fey I agree. Why would you want to do this in the first place? This screams X-Y problem to me.
score: 0
comment on: http://stackoverflow.com/q/52616489
type: Comment

http://stackoverflow.com/comment/92141239
has text: So in other words, you don't want to take any sublists that are contained in any previously seen list? If so, what about order and repeated elements?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52603251

http://stackoverflow.com/a/52637624
type: Answer
answers question: http://stackoverflow.com/q/52637488
upvote count: 1
has comment: http://stackoverflow.com/comment/92208277
score: 1
has body: Can use enumerate and string format here: paths = {'file_paths': ['/file/path/one', '/file/path/two'], 'file_count': 2} text_baseline = ('''This is the {num} file and the file path is path: {path} ''') with open('myfile.txt','w') as f: for i, path in enumerate(paths['file_paths'], 1): f.write(text_baseline.format(num=i, path=path))
downvote count: 0

http://stackoverflow.com/a/52716460
has comment: http://stackoverflow.com/comment/92403894
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92403155
has comment: http://stackoverflow.com/comment/92688124
answers question: http://stackoverflow.com/q/52711895
has comment: http://stackoverflow.com/comment/92464960
type: Answer
has comment: http://stackoverflow.com/comment/92464254
score: 2
accepted answer of: http://stackoverflow.com/q/52711895
upvote count: 2
has comment: http://stackoverflow.com/comment/92367032
has body: As far as I can tell, you can only do it using a hack. The issue comes from the call to: if sampled_values is None: sampled_values = candidate_sampling_ops.log_uniform_candidate_sampler( true_classes=labels, num_true=num_true, num_sampled=num_sampled, unique=True, range_max=num_classes, seed=seed) which outputs an object of this type: LogUniformCandidateSampler( sampled_candidates=&lt;tf.Tensor 'LogUniformCandidateSampler:0' shape=(128,) dtype=int64&gt;, true_expected_count=&lt;tf.Tensor 'LogUniformCandidateSampler:1' shape=(64, 1) dtype=float32&gt;, sampled_expected_count=&lt;tf.Tensor 'LogUniformCandidateSampler:2' shape=(128,) dtype=float32&gt; ) The hack would be to generate yourself the LogUniformCandidateSampler, to cast its result as tf.float16 and pass it to tf.nn.sampled_softmax_loss. # Redefine it as the tensorflow one is not exposed. LogUniformCandidateSampler = namedtuple("namedtuple", ["sampled_candidates", "true_expected_count", "sampled_expected_count"]) sampled_values = tf.nn.log_uniform_candidate_sampler( true_classes=tf.cast(train_labels, tf.int64), num_sampled=num_sampled, num_true=1, unique=True, range_max=vocabulary_size, seed=None) sampled_value_16 = LogUniformCandidateSampler( sampled_values.sampled_candidates, tf.cast(sampled_values.true_expected_count, tf.float16), tf.cast(sampled_values.sampled_expected_count, tf.float16)) sam_sof_los = tf.nn.sampled_softmax_loss( weights=softmax_weights, biases=softmax_biases, inputs=averaged_embeds, labels=train_labels, num_sampled=num_sampled, num_classes=vocabulary_size, sampled_values=sampled_value_16) But this is really a hack and it might have unexpected consequences (an expected one would be that the tf.cast operation is not differentiable).
has comment: http://stackoverflow.com/comment/92734483
has comment: http://stackoverflow.com/comment/92679996

http://stackoverflow.com/comment/92289430
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52680331
type: QuestionComment
has text: @-gyx-hh thanks alot

http://stackoverflow.com/comment/92311327
type: Comment
type: QuestionComment
score: 0
has text: ok. first off, thank you all for your help. I'm adding another edit with a function. It doesn't get me everything I need but I think it's getting me closer. Can you explain why it prints five times when I run it?
comment on: http://stackoverflow.com/q/52691083

http://stackoverflow.com/comment/92375985
has text: @Kevinhowbrook Yes, but what would you do with the data? I don't believe that you'll just be "There, sorted! :-)" and go do something else once you do have the list of values... :)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52714845

http://stackoverflow.com/a/52733223
answers question: http://stackoverflow.com/q/52731903
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52731903
has body: For multiple customers you can use groupby. Continuing with @ScottBoston's answer: df_range = df.apply(lambda r: pd.Series( pd.date_range(start=r.start_date, end=r.end_date, freq='M') .values), axis=1) df_range.groupby('cust_no').apply(lambda x: x.stack().unique().shape[0])

http://stackoverflow.com/q/52663306
has comment: http://stackoverflow.com/comment/92256790
has body: I have the following dataframe import pandas as pd from plotnine import * df = pd.DataFrame({ 'variable': ['gender', 'gender', 'age', 'age', 'age', 'income', 'income', 'income', 'income'], 'category': ['Female', 'Male', '1-24', '25-54', '55+', 'Lo', 'Lo-Med', 'Med', 'High'], 'value': [60, 40, 50, 30, 20, 10, 25, 25, 40], }) df['variable'] = pd.Categorical(df['variable'], categories=['gender', 'age', 'income']) An I am using the following code to get the stacked bar plot (ggplot(df, aes(x='variable', y='value', fill='category')) + geom_col() ) The above code was taken from here How can I put labels, ( in this case the values ), in the middle of each category at each bar ?
has title: How to put labels in a stacked bar using plotnine
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/30228069
score: 0
tagged with: python
tagged with: plotnine
tagged with: python-3.x
linked to: http://stackoverflow.com/q/6644997
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92546792
has answer: http://stackoverflow.com/a/54337530

http://stackoverflow.com/q/52689010
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/66861004
favorite count: 0
has answer: http://stackoverflow.com/a/52689290
downvote count: 2
has comment: http://stackoverflow.com/comment/92305390
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/35364601
possible better answer: http://stackoverflow.com/a/66861004
has comment: http://stackoverflow.com/comment/92305503
has body: My pandas Data frame df could produce result as below: grouped = df[(df['X'] == 'venture') &amp; (df['company_code'].isin(['TDS','XYZ','UVW']))].groupby(['company_code','sector'])['X_sector'].count() The output of this is as follows: company_code sector TDS Meta 404 Electrical 333 Mechanical 533 Agri 453 XYZ Sports 331 Electrical 354 Movies 375 Manufacturing 355 UVW Sports 505 Robotics 345 Movies 56 Health 3263 Manufacturing 456 Others 524 Name: X_sector, dtype: int64 What I want to get is the top three sectors within the company codes. What is the way to do it?
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/92305178
has comment: http://stackoverflow.com/comment/92305137
type: Question
accepted answer: http://stackoverflow.com/a/52689290
answer count: 2
has title: pandas - how to extract top three rows from the dataframe provided

http://stackoverflow.com/q/52644215
has answer: http://stackoverflow.com/a/52644796
accepted answer: http://stackoverflow.com/a/52644796
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
has title: JPype won't compile properly when run the code twice
downvote count: 0
score: 1
tagged with: jpype
type: Question
has body: my code: jarLocation = "C:/Users/LahiruGunawardhana/Desktop/New folder/info/infodynamics.jar" # Start the JVM (add the "-Xmx" option with say 1024M if you get crashes due to not enough memory space) jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=" + jarLocation,"-Xmx256m") teCalcClass = jpype.JPackage("infodynamics.measures.discrete").TransferEntropyCalculatorDiscrete teCalc = teCalcClass(2,1) teCalc.initialise() noOfEdges=0 for i in range(0,N-1): for j in range(i+1,N): # print(i,"--&gt;",j) if(nodes_connectivity(j,i) | nodes_connectivity(i,j)): sss = [int(i) for i in SsourceArray] ddd = [int(i) for i in DdestArray] teCalc.addObservations(sss, ddd) e=teCalc.computeAverageLocalOfObservations() jpype.shutdownJVM() I'm getting values only once for this code. when i run this code a second time I'm getting an error saying: _jpype.startup(jvm, tuple(args), True) OSError: JVM is already started Somehow, when i restart the python console for each step it gives values.
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/92261407
score: 0
type: Comment
type: QuestionComment
has text: @RYN How large can the data be? If it is "only" a few million, you still could make a shuffled list of the indexes and pop from that list of indexes (and then retrieve that data element from disk or whereever).
comment on: http://stackoverflow.com/q/52662200

http://stackoverflow.com/q/52735593
has body: I have a 2-d gridded files which represents the land use catalogues for the place of interest. I also have some lat/lon based point distributed in this area. from netCDF4 import Dataset ## 2-d gridded files nc_file = "./geo_em.d02.nc" geo = Dataset(nc_file, 'r') lu = geo.variables["LU_INDEX"][0,:,:] lat = geo.variables["XLAT_M"][0,:] lon = geo.variables["XLONG_M"][0,:] ## point files point = pd.read_csv("./point_data.csv") plt.pcolormesh(lon,lat,lu) plt.scatter(point_data.lon,cf_fire_data.lat, color ='r') I want to extract the values of the 2-d gridded field which those points belong, but I found it is difficult to define a simple function to solve that. Is there any efficient method to achieve it? Any advices would be appreciated. PS I have uploaded my files here 1. nc_file 2. point_file
has answer: http://stackoverflow.com/a/52737588
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: geospatial
tagged with: python
has title: Extracting the value of 2-d gridded field by scatter points in Python
downvote count: 0
score: 1
tagged with: netcdf
tagged with: gis
tagged with: grid
type: Question

http://stackoverflow.com/comment/92249371
type: QuestionComment
comment on: http://stackoverflow.com/q/52659521
has text: `iterfibo` is way too fast to time like this.
score: 7
type: Comment

http://stackoverflow.com/a/52638526
has comment: http://stackoverflow.com/comment/92209962
has comment: http://stackoverflow.com/comment/92210096
upvote count: 3
type: AcceptedAnswer
downvote count: 1
has body: You're modifying the list as you're iterating over it. Do a list comprehension instead: [i for i in a if not (i &lt; 30 or i &gt; 200)]
has comment: http://stackoverflow.com/comment/92210020
has comment: http://stackoverflow.com/comment/92209989
has comment: http://stackoverflow.com/comment/92209828
type: Answer
has comment: http://stackoverflow.com/comment/92209906
accepted answer of: http://stackoverflow.com/q/52638508
has comment: http://stackoverflow.com/comment/92209957
has comment: http://stackoverflow.com/comment/92210110
score: 2
has comment: http://stackoverflow.com/comment/92210037
answers question: http://stackoverflow.com/q/52638508
has comment: http://stackoverflow.com/comment/92209943
has comment: http://stackoverflow.com/comment/92209927
has comment: http://stackoverflow.com/comment/92209941
has comment: http://stackoverflow.com/comment/92209922

http://stackoverflow.com/q/52691993
has title: When i split a list in a for loop to make it readable, it loses all but the last line when i try to use it outside of the loop
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92311061
has answer: http://stackoverflow.com/a/52692122
has answer: http://stackoverflow.com/a/52692099
type: Question
has answer: http://stackoverflow.com/a/52692073
has body: When I do this: DataList = open("database.csv").readlines() for x in DataList: x.split(",") print(x) print(x) The first print(x) produces all of the lines in the document, nicely placed in a list. Then somehow all but the last line in the list are lost when performing the second print. It's really bugging me and I can't figure out a way to split the text from the document into an easily readable list. Can anyone help? edit: Since people were asking for extra data and I STILL can't get it to work, here's some extra code: varBox = StringVar() varBox.set("Click To Change") Option = OptionMenu(self, varBox, data) Option.grid( sticky=W) I need each line of the list to show as one option in this menu, i currently can't figure out how, even after all the help.
score: 0
has comment: http://stackoverflow.com/comment/92311038
answer count: 3

http://stackoverflow.com/comment/92345771
comment on: http://stackoverflow.com/q/52706723
score: 0
type: Comment
has text: "It's probably stuck in an infinite loop"... Is this something that can happen?
type: QuestionComment

http://stackoverflow.com/q/52619731
has title: Posterior from joint normal prior distribution
downvote count: 0
tagged with: bayesian
has comment: http://stackoverflow.com/comment/92320322
has comment: http://stackoverflow.com/comment/92298722
tagged with: log-likelihood
has answer: http://stackoverflow.com/a/52759127
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: normal-distribution
score: 2
has answer: http://stackoverflow.com/a/52673988
has body: I have some basic questions about gaussian inference. I have following data: (Log) dose, Number of animals, Number of deaths -0.86, 5, 0 -0.30, 5, 1 -0.05, 5, 3 0.73, 5, 5 EDIT: I'm assuming a simple regression model for the dose response logit(θ) = α + βx where logit(θ) = log(θ / (1-θ)). θ stands for a probability of death given dose x. I want to create a joint normal prior distribution on (α,β), with α ∼ N(0,22),β ∼ N(10,102), and corr(α,β) = 0.5 and then calculate the posterior density in a grid of points around the prior (α: 0 ± 4, β: 10 ± 20). First, I have created joint normal prior distribution following: import numpy as np from scipy import stats x = np.array([-0.86, -0.30, -0.05, 0.73]) n = np.array([5, 5, 5, 5]) y = np.array([0, 1, 3, 5]) prior = stats.multivariate_normal([0, 10], [[0.5, 0], [0, 0.5]]) Is this right? Second, how do I calculate posterior density in a grid?
type: Question
answer count: 2

http://stackoverflow.com/a/55370394
score: 1
has body: Please check kernel.json file, check if the path to the Python executable is correct for example my kernel.json looks like this, in my case the Python binary is located at C:/Users/Vinod/Anaconda/envs/env_name/python Check the path in your case { "argv": [ "C:/Users/Vinod/Anaconda/envs/env_name/python", "-m", "ipykernel_launcher", "-f", "{connection_file}" ], "display_name": "Python 3", "language": "python" } Note: env_name refers to the anaconda environment you are using
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52622358
downvote count: 0

http://stackoverflow.com/comment/92295340
has text: @NedBatchelder well I'm being schooled then. Why is the computation locked to one theoretical core?
comment on: http://stackoverflow.com/q/52683554
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92362875
comment on: http://stackoverflow.com/a/52718466
score: 0
type: AnswerComment
has text: Can you test this and tell? I have updated the answer
type: Comment

http://stackoverflow.com/comment/92415600
has text: When creating a title, try and describe the problem you have, not the fact that you have a problem.
type: QuestionComment
comment on: http://stackoverflow.com/q/52742364
type: Comment
score: 1

http://stackoverflow.com/q/52709367
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92345630
type: AnsweredQuestion
tagged with: django-views
downvote count: 0
score: 1
has title: Filtering Results Using `get_context_data` in a ListView
type: Question
has comment: http://stackoverflow.com/comment/92345145
upvote count: 1
has comment: http://stackoverflow.com/comment/92345038
has body: In my ListView, I want to return the entire list of objects from my Publication model and return the total from my Budget model to include in the ListView with each title and the associated total. My Models: Publication App class Publication(models.Model): title = models.CharField(...) Budget App class Budget(models.Model): total = models.DecimalField(...) publication = models.ForeignKey(Publication, ...) Views: Publication App class PublicationListView(ListView): context_object_name = 'publications' model = Publication def get_context_data(self, **kwargs): context = super(PublicationListView, self).get_context_data(**kwargs) context['publication'] = self.get_queryset() context['budget'] = Budget.objects.all() return context Template: Publication App {% for pub in publications %} {{ pub.title }} {% for obj in budget %} {{obj}} {% endfor %} {% endfor %} In my template, the results I am receiving look something like this: publication 1 1000 2000 3000 publication 2 1000 2000 3000 publication 3 1000 2000 3000 But what I need is: publication 1 1000 publication 2 2000 publication 3 3000 I understand why I am returning all budget objects in each row, but I am not sure how to only display the correct budget with the associated publication. Is using get_context_data() the best option for this?
has comment: http://stackoverflow.com/comment/92345645
has answer: http://stackoverflow.com/a/52712545
accepted answer: http://stackoverflow.com/a/52712545
answer count: 1

http://stackoverflow.com/comment/92167578
score: 0
type: Comment
type: QuestionComment
has text: I have to get rid of the files, the SSD is getting saturated in a single run of the program
comment on: http://stackoverflow.com/q/52614688

http://stackoverflow.com/a/52668776
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52666877
answers question: http://stackoverflow.com/q/52666877
score: 2
has comment: http://stackoverflow.com/comment/92399696
has comment: http://stackoverflow.com/comment/92398934
type: AcceptedAnswer
downvote count: 0
has body: Pygame programs are usually structured similarly to the following example. First of all, initialize everything and load the images and other resources (do that only once ahead of the main loop), then, in the main while loop, handle the events, update the game and blit everything. Finally, call pygame.display.flip() or pygame.display.update() to make all changes visible and clock.tick(fps) to limit the frame rate. import pygame pygame.init() screen = pygame.display.set_mode((1000, 600)) # Constants (use uppercase letters to signal that these shouldn't be modified). BLACK = pygame.color.Color("black") WHITE = pygame.color.Color("white") GAME_LAYER = pygame.Surface((600, 600)) GAME_LAYER.fill(WHITE) # convert() returns a new surface, so you have to assign it to a variable. DRAGON_IMG = pygame.image.load("Green Dragon.gif").convert() def main(screen): clock = pygame.time.Clock() # Variables x = 0 y = 0 while True: # Handle events. for event in pygame.event.get(): if event.type == pygame.QUIT: return # Game logic. x += 1 # Clear the screen and blit everything. screen.fill(BLACK) screen.blit(GAME_LAYER, (10, 0)) screen.blit(DRAGON_IMG, (x, y)) pygame.display.flip() clock.tick(60) if __name__ == '__main__': main(screen) pygame.quit() If you want to blit onto a background surface instead of the screen/display and it's unicolored, you can just fill the background surface each frame with the fill method, then blit the dragon and finally blit the background onto the screen: game_layer.fill(WHITE) game_layer.blit(DRAGON_IMG, (x, y)) screen.blit(game_layer, (10, 0)) Or if your background surface is an actual image, you can create a copy each frame and then blit onto this copy: game_layer_copy = GAME_LAYER.copy() game_layer_copy.blit(DRAGON_IMG, (x, y)) screen.blit(game_layer_copy, (10, 0))
type: Answer

http://stackoverflow.com/comment/94349710
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52734736
score: 0
has text: I posted an answer, hope help you up

http://stackoverflow.com/q/52743101
tagged with: python
has body: I am trying to make a horizontal bar plot, where the bars represent subsequent time intervals. This is my approach so far: import matplotlib.pyplot as plt import numpy as np date1 = np.datetime64('2014-12-31') date2 = np.datetime64('2014-10-30') fig = plt.figure( figsize=(12,8) ) ax1 = fig.add_subplot( 111 ) # make horizontal bar plot ax1.barh( 1., width=(date1-date2), height=.3, left=date1, align='center' ) plt.show() Matplotlib does not like this, though. This is the error message I get: TypeError: ufunc add cannot use operands with types dtype('float64') and dtype('&lt;m8[D]') Sounds like matplotlib is unhappy about the time-interval being used as the bar's width. Any hint how to make matplotlib happy again? I am using numpy 1.15.1 and matplotlib 2.2.3.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52743592
tagged with: matplotlib
upvote count: 1
type: Question
tagged with: numpy
downvote count: 0
answer count: 1
has title: Using time intervals with numpy datetime64 type in matplolib's bar-plot
has answer: http://stackoverflow.com/a/52743592
score: 1
favorite count: 0

http://stackoverflow.com/a/52595004
has comment: http://stackoverflow.com/comment/92125132
answers question: http://stackoverflow.com/q/52594959
downvote count: 0
has body: First, to remove the trailing .0 ensure that data is int: df = df.astype(int) Then you can do: df['cable_block'].astype(str) + '/' + df['pair'].astype(str) 0 1/10 1 1/11 2 3/123 3 3/222 dtype: object Another option to ensure a correct formatting could be: df.apply(lambda x: "%d/%d" %(x['cable_block'], x['pair']), axis=1) 0 1/10 1 1/11 2 3/123 3 3/222 dtype: object
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92125326
has comment: http://stackoverflow.com/comment/92124905
upvote count: 3
has comment: http://stackoverflow.com/comment/92125727
has comment: http://stackoverflow.com/comment/92125574
type: Answer
has comment: http://stackoverflow.com/comment/92125218
accepted answer of: http://stackoverflow.com/q/52594959
has comment: http://stackoverflow.com/comment/92125471

http://stackoverflow.com/comment/92161141
score: 0
type: Comment
has text: How exactly is a "duplicate" defined?
type: QuestionComment
comment on: http://stackoverflow.com/q/52613320

http://stackoverflow.com/q/52617523
upvote count: 2
has title: How to speed up requests module while scraping?
tagged with: multithreading
answer count: 2
tagged with: web-scraping
tagged with: python
tagged with: python-requests
has body: Firstly, I'm not asking this question because I cannot find an answer, but because I cannot understand the answers that I've found. It's very easy for people to answer a question thinking, that "I answered your question, if you don't understand it it's your own fault", so now I need some help in understanding, or just in simplifying the process. I have a list of about 300,000 urls that I am visiting using pythons requests module. the time it takes to get/load the url is quite painful which I believe is because of the amount of content located at the url. I'm probably at 15-20 seconds per request. I'm trying to think of any way that I can greatly reduce this amount of time. My first thought was whether or not I could sort of disable/filter out images and anything else that I know ahead of time I wont be needing using requests. I'm not sure how to implement that or if it can even be done. My second idea is to send "batch requests," which looks to me like sending multiple requests simultaneously. I'm really not sure if this is actually faster, I haven't been able to get an accurate response of my request since I can't get my bit of code to work. My assumption is that I can send X requests in one shot, get X responses in return, and just process each one individually. What I've attempted to use as a solution of this is below. def getpage(list_urls): for url in list_urls: r = requests.get(url) dostuffwithresponse() for file in list_files: list_links = open(file).readlines() pool = multiprocessing.Pool(processes = 10) pool_outputs = pool.map(getpage(), list_links) pool.close() pool.join() print('*') print(pool_outputs) Between reducing the size of my response, if possible, and by sending multiple requests. It is my goal to shorten my 15 second+ wait time to 5 seconds and under (or as good as I can get it). Does anyone have a good suggestion on a simpler, more direct way to go about this?
has answer: http://stackoverflow.com/a/52627338
has comment: http://stackoverflow.com/comment/92169664
has comment: http://stackoverflow.com/comment/92169389
downvote count: 1
has answer: http://stackoverflow.com/a/52655951
accepted answer: http://stackoverflow.com/a/52627338
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52655951
score: 1
favorite count: 0

http://stackoverflow.com/q/52590564
has comment: http://stackoverflow.com/comment/92116137
score: 2
has answer: http://stackoverflow.com/a/52590625
has comment: http://stackoverflow.com/comment/92115849
downvote count: 0
has body: Given the example dictionary: LANGUAGE_TO_ISO = { "en": "en", "eng": "en", "english": "en", "es": "es", "spanish": "es", ... } And a given example strings: book_title = "The Dark Tower - english" book_title = "The Dark Tower - eng" book_title = "The Dark Tower 2 - english 2nd edition" Is there a Python function I'm unaware of that would permit to search if a string contains any of the dictionary keys then return the corresponding values, without having to loop in the ISO dictionary? This way, I could extract the ISO language from the many different ways a language could have been written. If someone knows of a less dirty way of doing this, please share :) UPDATE: As Willem mentioned, forgot to specify that "english", "eng", "spanish" etc would be separated by words. Either a dot, comma, hyphen, space, ...
favorite count: 0
has comment: http://stackoverflow.com/comment/92125360
has title: Python check if string contains any of a dictionary's keys
tagged with: python
answer count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52590821
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52590688
type: Question
has answer: http://stackoverflow.com/a/52590846
has comment: http://stackoverflow.com/comment/92115966

http://stackoverflow.com/q/52726991
score: 0
has body: I'm developing a program with IBM Watson Speech to Text and currently using Python 2.7. Here's a stub of some code for development: class MyRecognizeCallback(RecognizeCallback): def __init__(self): RecognizeCallback.__init__(self) def on_data(self, data): pass def on_error(self, error): pass def on_inactivity_timeout(self, error): pass speech_to_text = SpeechToTextV1(username='*goes here*', password='*goes here*') speech_to_text.set_detailed_response(True) f = '/home/user/file.wav' rate, data = wavfile.read(f) work = data.tolist() with open(f, 'rb') as audio_file: # Get IBM Watson analytics currentModel = "en-US_NarrowbandModel" if rate &lt;= 8000 else "en-US_BroadbandModel" x = "" print(" - " + f) try: # Callback info myRecognizeCallback = MyRecognizeCallback() # X represents the responce from Watson audio_source = AudioSource(audio_file) my_result = speech_to_text.recognize_using_websocket( audio_source, content_type='audio/wav', timestamps=True, recognize_callback=myRecognizeCallback, model=currentModel, inactivity_timeout=-1, max_alternatives=0) x = json.loads(json.dumps(my_result, indent=2), object_hook=lambda d: n namedtuple('X', d.keys())(*d.values())) What I'm expecting to be returned is a JSON object with the results of the file given the above parameters. What instead I'm recieving is an error that looks like this: Error received: 'NoneType' object has no attribute 'connected' That's the entire traceback - no other errors than that. However, when I try to access the JSON object in further code, I get this error: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/watson_developer_cloud/websocket/recognize_listener.py", line 96, in run chunk = self.audio_source.input.read(ONE_KB) ValueError: I/O operation on closed file Did I forget something or put something in the wrong place? Edit: My original code had an error in it that I fixed myself. Regardless, I'm still getting the original error. Here's the update: my_result = speech_to_text.…
tagged with: python
has answer: http://stackoverflow.com/a/52727463
tagged with: ibm-watson
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52727463
tagged with: http://stackoverflow.com/tag/json
has title: Python - IBM Watson Speech to Text 'NoneType' object has no attribute 'get_result'
type: Question
answer count: 1
tagged with: websocket

python-3.6
tags question: http://stackoverflow.com/q/52616702
tags question: http://stackoverflow.com/q/52684961
tags question: http://stackoverflow.com/q/52656025
tags question: http://stackoverflow.com/q/52652755
tags question: http://stackoverflow.com/q/52716922
tags question: http://stackoverflow.com/q/52654005
tags question: http://stackoverflow.com/q/52690293
tags question: http://stackoverflow.com/q/52611946
type: Tag
tags question: http://stackoverflow.com/q/52665487
tags question: http://stackoverflow.com/q/52713100
tags question: http://stackoverflow.com/q/52663518
tags question: http://stackoverflow.com/q/52626031
tags question: http://stackoverflow.com/q/52600459
tags question: http://stackoverflow.com/q/52598073
tags question: http://stackoverflow.com/q/52642700
tag name: python-3.6
tags question: http://stackoverflow.com/q/52633391
tags question: http://stackoverflow.com/q/52643010
tags question: http://stackoverflow.com/q/52635868
tags question: http://stackoverflow.com/q/52625544
tags question: http://stackoverflow.com/q/52695976
tags question: http://stackoverflow.com/q/52626467
tags question: http://stackoverflow.com/q/52691386
tags question: http://stackoverflow.com/q/52660176
tags question: http://stackoverflow.com/q/52617078

http://stackoverflow.com/comment/92208222
score: 0
type: Comment
has text: hmm. I tried your suggestion and I still get the same behavior as above.
type: AnswerComment
comment on: http://stackoverflow.com/a/52636907

http://stackoverflow.com/q/52606704
answer count: 2
has body: Here is my calculated field: half_pension_days_value = fields.Integer(string='Day value', copy=False, compute='convert_bin_dec') Here is my function: @api.multi def convert_bin_dec(self): if self.half_pension: print "Je suis dans la fonction convert" self.half_pension_days_value = 5 Encountered problem : As soon as I launch this function thanks to the state of my boolean half_pension, my print starts looping. I guess the problem is at this line -> self.half_pension_days_value = 5. But why ? EDIT : In order @api.model def create(self, vals): record = super(ResPartnerSchool, self).create(vals) record.convert_bin_dec() return record @api.multi def write(self, vals): result = super(ResPartnerSchool, self).write(vals) self.convert_bin_dec() return result Here my error -> RuntimeError: maximum recursion depth exceeded while calling a Python object Thank you
accepted answer: http://stackoverflow.com/a/52792933
downvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52675906
type: AnsweredQuestion
has title: Odoo V10 - Calculated field
has answer: http://stackoverflow.com/a/52675906
upvote count: 1
has answer: http://stackoverflow.com/a/52792933
type: Question
tagged with: odoo
score: 1

http://stackoverflow.com/comment/92389146
type: QuestionComment
type: Comment
has text: Shouldn't `"test3 4"` also be present in the desired output?
score: 1
comment on: http://stackoverflow.com/q/52732062

http://stackoverflow.com/q/52675187
has comment: http://stackoverflow.com/comment/92279795
has comment: http://stackoverflow.com/comment/92279801
has body: I'm trying to get python to sum a column from a csv file that I imported. The column includes both positive and negative numbers. Every time I run my script, the output I get is 0 (zero). I'm a noob at python so if you could point me in a direction, I would appreciate it. I'm guessing I'm asking my code to calculate the wrong cells, but the numerous variations I've tried have all resulted in the same output.
has comment: http://stackoverflow.com/comment/92279798
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92279827
type: Question
answer count: 1
has title: Getting python to answer "The total net amount of "Profit/Losses" over the entire period"
has answer: http://stackoverflow.com/a/52675223
score: 0

http://stackoverflow.com/q/52603515
score: 2
upvote count: 2
tagged with: opencv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52603770
has body: Before asking this question I searched the site for a similar problem for the last 2 days but I couldn't find the one specific to me. I have an IP camera whose IP address, username, etc. I have been given full access to. I can actually open the stream and watch it live by writing the IP into VLC Player &gt;&gt; Open Network Stream &gt;&gt; Network. But what I want is to be able to watch the same live stream with python. Here's my code: import urllib.request import cv2 import numpy url = 'rtsp://10.10.111.200/profile2/media.smp' while True: resp = urllib.request.urlopen(url) b_array = bytearray(resp.read()) img_np = numpy.array(b_array, dtype=numpy.uint8) img = cv2.imdecode(img_np, -1) cv2.imshow('test', img) if cv2.waitkey(10) == ord('q'): exit(0) When I run this code, it gives me the following error: urllib.error.URLError: . Then I figured that maybe I should change rtsp to http in url, but when I do, it gives me the following error, cv2.error: OpenCV(3.4.3) D:\Build\OpenCV\opencv-3.4.3\modules\imgcodecs\src\loadsave.cpp:737: error: (-215:Assertion failed) !buf.empty() &amp;&amp; buf.isContinuous() in function 'cv::imdecode_' in the line img = cv2.imdecode(img_np, -1) which I think is because there's no data coming from the (very likely wrong since I changed to http) source. I'm on Windows 10 64bit.
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52603770
has title: Problem streaming from IP camera with python openCV

http://stackoverflow.com/a/52657344
score: 28
has comment: http://stackoverflow.com/comment/92280380
type: Answer
has body: What's the dtype of temps. I can reproduce your warning and error with a string dtype: In [26]: temps = np.array([1,2,'string',0]) In [27]: temps Out[27]: array(['1', '2', 'string', '0'], dtype='&lt;U21') In [28]: temps==-99.9 /usr/local/bin/ipython3:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison #!/usr/bin/python3 Out[28]: False In [29]: np.isnan(temps) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-29-2ff7754ed926&gt; in &lt;module&gt;() ----&gt; 1 np.isnan(temps) TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' First, comparing strings with the number gives this future warning. Second, testing for nan produces the error. Note that given the dtype, the nan assignment assigns a string value, not a float (np.nan is a float). In [30]: temps[-1] = np.nan In [31]: temps Out[31]: array(['1', '2', 'string', 'nan'], dtype='&lt;U21')
downvote count: 0
upvote count: 28
has comment: http://stackoverflow.com/comment/92280490
has comment: http://stackoverflow.com/comment/92246395
accepted answer of: http://stackoverflow.com/q/52657223
answers question: http://stackoverflow.com/q/52657223
type: AcceptedAnswer

http://stackoverflow.com/a/52676120
has comment: http://stackoverflow.com/comment/92281527
downvote count: 0
score: 1
has body: You need to catch socket.timeout exception, check example below. import urllib2 import socket class MyException(Exception): pass try: urllib2.urlopen("http://example.com", timeout = 1) except socket.timeout, e: # For Python 2.7 raise MyException("There was an error: %r" % e) I strongly recommend using Requests library for making requests, it will make your life easier.
type: Answer
answers question: http://stackoverflow.com/q/52676059
upvote count: 1
has comment: http://stackoverflow.com/comment/92281977
has comment: http://stackoverflow.com/comment/92281758

http://stackoverflow.com/comment/92171064
score: 0
type: Comment
has text: thank you the results I am getting make much more sense now.
comment on: http://stackoverflow.com/a/52618363
type: AnswerComment

http://stackoverflow.com/a/52651442
answers question: http://stackoverflow.com/q/52650646
has comment: http://stackoverflow.com/comment/92239349
has comment: http://stackoverflow.com/comment/92236443
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92236182
has comment: http://stackoverflow.com/comment/92236562
upvote count: 2
has comment: http://stackoverflow.com/comment/92235747
has comment: http://stackoverflow.com/comment/92236341
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/96365098
has comment: http://stackoverflow.com/comment/92240179
accepted answer of: http://stackoverflow.com/q/52650646
has comment: http://stackoverflow.com/comment/92239744
has body: So, once you solve the str/int comparison, with something like int(row['parking_space'][:2]), it looks like this has been solved in this question. Using a not-accepted answer from that question: def highlight(row): if int(row.parking_space[:2]) &lt;= 25: return ['background-color: green']*3 elif int(row.parking_space[:2]) &gt;=26 and int(row.parking_space[:2]) &lt;=50: return ['background-color:yellow']*3 else: return ['background-color:red']*3 Then, to save the styled dataframe, you assign a variable as below df_styled=df.style.apply(highlight, axis=1) df_styled is now a &lt;pandas.io.formats.style.Styler objectthat generates a string of self-contained CSS and HTML. If you then call df_styler.render() you get the HTML ready to be saved as plaintext and rendered by a browser: &lt;style type="text/css" &gt; #T_20b96880_c80e_11e8_a82d_a0afbd198380row0_col0 { background-color: yellow; ...

http://stackoverflow.com/comment/92255855
has text: Typically it means you `PYTHONPATH` needs to be set so that it contains the directory where your project starts.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52662839
type: QuestionComment

http://stackoverflow.com/a/52717903
answers question: http://stackoverflow.com/q/52717837
accepted answer of: http://stackoverflow.com/q/52717837
type: Answer
has comment: http://stackoverflow.com/comment/92362587
has comment: http://stackoverflow.com/comment/92361432
upvote count: 1
has comment: http://stackoverflow.com/comment/92361635
has body: You are using the wrong format. '24 October 2018' uses format="%d %B %Y". The format specifiers are listed here. edit: -Demo- &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({'date':['24 October 2018', '23 April 2018', '18 January 2018']}) &gt;&gt;&gt; df.date = pd.to_datetime(df['date'], format="%d %B %Y") &gt;&gt;&gt; &gt;&gt;&gt; df date 0 2018-10-24 1 2018-04-23 2 2018-01-18 &gt;&gt;&gt; &gt;&gt;&gt; df['date'][0] Timestamp('2018-10-24 00:00:00') &gt;&gt;&gt; df['date'][0].month 10 edit 2: second question &gt;&gt;&gt; df['status'] = ['complete', 'complete', 'requested'] &gt;&gt;&gt; df date status 0 2018-10-24 complete 1 2018-04-23 complete 2 2018-01-18 requested &gt;&gt;&gt; &gt;&gt;&gt; df[df['status'] != 'complete'] date status 2 2018-01-18 requested
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92361297
score: 1

http://stackoverflow.com/q/52682678
accepted answer: http://stackoverflow.com/a/52682754
has answer: http://stackoverflow.com/a/52683052
has comment: http://stackoverflow.com/comment/92293813
type: Question
upvote count: 4
has body: Say I have the following dictionary. &gt;&gt; sample_dict = {"1": ['a','b','c'], "2": ['d','e','f'], "3": ['g','h','a']} I would like to find a way that would look at the values of each of the keys and return whether or not the value lists have the a duplicate variable inside. For example it would output: &gt;&gt; [["1","3"] , ['a']] I've looked at a few of the posts here and tried to use and/or change them to accomplish this, however none of what I have found has worked as intended. They would work if it was as follows: &gt;&gt; sample_dict = {"1": ['a','b','c'], "2": ['d','e','f'], "3": ['a','b','c']} but not if only a single value within the list was the same.
has answer: http://stackoverflow.com/a/52682745
favorite count: 0
has answer: http://stackoverflow.com/a/52682754
possible better answer: http://stackoverflow.com/a/52682745
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/52682748
score: 2
tagged with: list
downvote count: 2
has title: Python Dictionary using Lists as Values, find other Keys with same values
has comment: http://stackoverflow.com/comment/92293471
type: AnsweredQuestion

http://stackoverflow.com/q/52663062
has body: I got this error and I cant resolve this error. I guess the error is related to optimizing module and caused by type of input vector. But I cant resolve it!!! Please give me a solution. cv2 version is 3.1.0 python 3.5 below is my code import cv2 assert cv2.__version__[0] == '3', 'The fisheye module requires opencv version &gt;= 3.0.0' import numpy as np import os CHECKERBOARD = (6,9) subpix_criteria = (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1) calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC+cv2.fisheye.CALIB_CHECK_COND+cv2.fisheye.CALIB_FIX_SKEW objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32) objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2) _img_shape = None objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. images = glob.glob('*.jpg') pict_dir = './pics/chess_boads_2/fish_eye/' images = [ pict_dir + f for f in os.listdir(pict_dir) if "JPG" in f][:1] for fname in images: img = cv2.imread(fname) img = cv2.resize(img, (500,500)) if _img_shape == None: _img_shape = img.shape[:2] else: assert _img_shape == img.shape[:2], "All images must share the same size." gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH+cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE) print("-&gt;",ret) # If found, add object points, image points (after refining them) if ret == True: objpoints.append(objp) corners = cv2.cornerSubPix(gray,corners,(3,3),(-1,-1),subpix_criteria) imgpoints.append(corners) img = cv2.drawChessboardCorners(img, (6,9), corners,ret) cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows() N_OK = len(objpoints) K = np.zeros((3, 3)) D = np.zeros((4, 1)) D = np.zeros(4) rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)] tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)] rms, _, _, _, _ = \ cv2.fisheye.cali…
has comment: http://stackoverflow.com/comment/92259143
tagged with: calibration
has comment: http://stackoverflow.com/comment/92289053
has title: arithm_op Error in Fisheye Calibration of OpenCV python Bindings
answer count: 0
score: 0
type: UnansweredQuestion
tagged with: python
tagged with: fisheye
tagged with: opencv
has comment: http://stackoverflow.com/comment/92393397
type: Question

http://stackoverflow.com/comment/92155304
type: Comment
has text: you can loop through the elements! you just have to put them in a variable
comment on: http://stackoverflow.com/a/52609404
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92266053
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52667951
has text: @Wen, Hmm, that doesn't work for me though on 0.19 (sry, old version). OK, I figured it out, it needs `inplace=False`.
type: Comment

http://stackoverflow.com/q/52659814
score: 2
upvote count: 2
has body: I'm making a text-based rpg game in Python as a self-project. I have a class called Character inside the file char.py and a player object is created from it inside the file mapAndclasses.py . For the fight sequence, which I put in a separate file, I need to obtain the Character object from mapAndclasses.py . However, I have no idea how to use objects globally. Is it possible to do so? thank you ;-;!! Char.py #Char.py class character: def __init__(self,name,job,level,exp,curHp,maxHp,mana,strength,defence,magic,baseCrit,coordsX,coordsY): self.name = name self.job = job self.level = int(level) self.exp = float(exp) self.curHp = int(curHp) self.maxHp = int(maxHp) self.mana = int(mana) self.strength = int(strength) self.defence = int(defence) self.magic = int(magic) self.baseCrit = int(baseCrit) self.coordsX = int(coordsX) self.coordsY = int(coordsY) def getCharacterInfo(self): print("Name:", self.name, "\t\tLevel:", self.level) print("Job:", self.job, "\t\tExperience:", self.exp) print("HP:",self.curHp, "/", self.maxHp) print("Mana:", self.mana) print("Str:",self.strength) print("Def:", self.mana) print("Magic:", self.mana) print("Base Crit:", self.baseCrit) mapAndclasses.py # Load player def loadPlayer(): saveArray = [] with open("savefile.txt") as f: for line in f: var,val = line.strip().split("=") saveArray.append(val) f.close(); global inventory inventory = Inventory.load() global player # player = name, job, level, exp, curhp, maxhp, mana, strength, defence, magic, baseCrit, x, y player = character(saveArray[0],saveArray[1],saveArray[2],saveArray[3], saveArray[4],saveArray[5],saveArray[6],saveArray[7], saveArray[8],saveArray[9],saveArray[10], saveArray[11], saveArray[12]) # playerCoords = [row,column] # player always starts from the left global playerCoords playerCoords = [player.getCoordsX(), player.getCoordsY()] print("\nWelcome back " + saveArray[0])
type: Question
has comment: http://stackoverflow.com/comment/92250030
has answer: http://stackoverflow.com/a/52660539
has comment: http://stackoverflow.com/comment/92249857
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92280326
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52690611
has title: How to use objects in python globally?
type: UnansweredQuestion
tagged with: python

bottle
tags question: http://stackoverflow.com/q/52655948
type: Tag
tag name: bottle
tags question: http://stackoverflow.com/q/52635595
tags question: http://stackoverflow.com/q/52744071
tags question: http://stackoverflow.com/q/52715471

http://stackoverflow.com/q/52684122
tagged with: unicode-escapes
has comment: http://stackoverflow.com/comment/92296706
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52684438
has comment: http://stackoverflow.com/comment/92296729
has title: Normal string with "xe2x80x93" "-" char
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92296711
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92296664
has body: I have a problem with strings in python3. my var g is a normal string. But in it there is an annoying "xe2x80x93", because it comes from a web parser. I would like to convert this to the fitting character "-". content = str(urllib.request.urlopen(site, timeout=10).read()) g = content.split('&lt;h1 itemprop="name"')[1].split('&lt;/span&gt;&lt;/h1&gt;')[0].split('&lt;span&gt;')[1].replace("\\", "") print(type(g)) --&gt; string print(g) --&gt; "Flash xe2x80x93 der rote Blitz" print(g.encode('latin-1').decode('utf-8')) --&gt; AttributeError: 'str' object has no attribute 'decode' print(repr(g.decode('unicode-escape'))) --&gt; AttributeError: 'str' object has no attribute 'decode' print(g.encode('ascii','replace')) --&gt; b'Flash xe2x80x93 der rote Blitz' print(bytes(g, "utf-8").decode()) --&gt; "Flash xe2x80x93 der rote Blitz" print(bytes(g, "utf-8").decode("unicode_escape")) --&gt; "Flash â der rote Blitz" How can it works? I dont get any further.
accepted answer: http://stackoverflow.com/a/52684438
type: Question
has comment: http://stackoverflow.com/comment/92296699
answer count: 1
downvote count: 0
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/92296692

http://stackoverflow.com/q/52638033
has title: Duplicated being added to list Python
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52638128
score: 1
has comment: http://stackoverflow.com/comment/92209229
type: Question
has body: I have class MySet that I want to return the elements in both seta and setb. However, it returns that element twice. class MySet: def __init__(self, elements): self.elements=elements def intersection(self, other_set): new_set = list(self.elements) for j in other_set: if j in self.elements: new_set.append(j) for h in self.elements: if h not in other_set: new_set.remove(h) new_set.sort() return new_set So if seta=MySet([1,2,3]) and setb=MySet([1,5,6]), setc=seta.intersection(setb.elements), doing print(setc) should give [1] but instead gives [1,1]. How can I fix this? Also, is there anyway to do setc=seta.intersection(setb), without the .elements? Thank you.
downvote count: 0
has comment: http://stackoverflow.com/comment/92208978
has comment: http://stackoverflow.com/comment/92208979
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52700642
favorite count: 0
type: UnansweredQuestion
has body: I'm a C++ novice but I have a C++ file that I'm trying to create a Python module from to access a specific function run in C++. I'm trying to use Boost Python in order to do this, but I'm only interested in being able to access the get_equities() function, defined within the file. test.cpp: #include "omp/EquityCalculator.h" #include &lt;iostream&gt; #include &lt;boost/python.hpp&gt; using namespace omp; using namespace std; // Function prototype (declaration) vector&lt;double&gt; get_equities(vector&lt;string&gt; args); int main(int argc, char *argv[]) { vector&lt;string&gt; args(argv, argv + argc); vector&lt;double&gt; equities; equities = get_equities(args); }; vector&lt;double&gt; get_equities(vector&lt;string&gt; args) { int argc = args.size(); string board_string = args[1]; EquityCalculator eq; vector&lt;CardRange&gt; ranges; for( int i = 2; i &lt; argc; i++ ) { ranges.push_back(args[i]); }; uint64_t board = CardRange::getCardMask(board_string); eq.start(ranges, board); cout &lt;&lt; "running" &lt;&lt; endl; eq.wait(); vector&lt;double&gt; result; auto r = eq.getResults(); // 2 to 4; 2 to 3 //todo: for( int i = 2; i &lt; argc; i++ ) { result.push_back(r.equity[i - 2]); } cout &lt;&lt; result[0] &lt;&lt; endl; return result; } BOOST_PYTHON_MODULE(cpp_equity) { using namespace boost::python; def("get_equities", get_equities); } This refers to a separate class EquityCalculator (which refers to a number of other classes via recursive includes). Following the tutorial, I was hoping that I would only have to declare this function, however when trying to use a setup.py I get some errors: In file included from test.cpp:1:0: omp/EquityCalculator.h:76:21: error: ‘std::function’ has not been declared std::function&lt;void(const Results&amp;)&gt; callback = nullptr, ^~~~~~~~ omp/EquityCalculator.h:76:29: error: expected ‘,’ or ‘...’ before ‘&lt;’ token std::function&lt;void(const Results&amp;)&gt; callback = nullptr, ^ omp/EquityCalculator.h:202:10: error: ‘function’ in na…
tagged with: python
tagged with: c++
has comment: http://stackoverflow.com/comment/92329304
downvote count: 0
answer count: 0
score: 1
type: Question
tagged with: boost-python
upvote count: 1
has comment: http://stackoverflow.com/comment/92327668
has title: Using Boost Python to access a specific function which references other classes

http://stackoverflow.com/comment/92391916
type: QuestionComment
has text: The first part of the script collects all the links for the rear haz. avoidance cam (RHAZ) and puts them into url format. I then want to open each link and download the pictures on those pages.
comment on: http://stackoverflow.com/q/52712472
score: 0
type: Comment

http://stackoverflow.com/comment/92346035
comment on: http://stackoverflow.com/q/52709762
has text: Depending on what's actually parsing the code, there won't be a stack trace, since the error occurs during parsing, not execution.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52609521
answers question: http://stackoverflow.com/q/52609285
type: Answer
upvote count: 15
score: 14
has body: It is reasonable to give encoding parameter every time you open a file. Use this: import json with open("./Files/CD_Data.json", encoding="utf8") as file: #item = input("Enter item name: ") reader = json.load(file) print(reader)
has comment: http://stackoverflow.com/comment/121261781
downvote count: 1

http://stackoverflow.com/comment/92291761
has text: Please post code for review. My guess is scoping on a variable is nullifying the value but impossible to determine without the code behind it. Thx.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52681646

http://stackoverflow.com/comment/92420702
type: QuestionComment
has text: Computer has 256 gb or RAM with 6tb hd and 20 cores xeon 2600v2 processor. We mostly use this computer for sequencing based tasks.
comment on: http://stackoverflow.com/q/52728432
score: 0
type: Comment

http://stackoverflow.com/comment/92366574
type: QuestionComment
comment on: http://stackoverflow.com/q/52719729
has text: Ubuntu is the base image. It's not an easy change to use Alpine because I have to build a lot of massive libraries that are not available in our configuration through a package manager. That being said, it's still possible to use, I'll just have to spend the time to rebuild all the dependencies.
score: 0
type: Comment

http://stackoverflow.com/a/52665125
upvote count: 2
answers question: http://stackoverflow.com/q/52664372
has comment: http://stackoverflow.com/comment/92277571
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The function you have created calculates the total value of the lump sum over time, and as you have pointed out, you can call it twice (once with year and once with year - 1) and take the difference to get your answer. If you really want do this recursively in one go we need to think through the base cases: Year 0: At the beginning there is no interest return 0 Year 1: After the first year the change is just the initial amount times the interest rate return initial * rate Year 2+: From this year on, we make the same as last year, plus the interest on that interest return last_year + rate * last_year Or just: return last_year * (1 + rate) Now we can put it all together: def cpi_increase(year, initial, rate): if year == 0: return 0 if year == 1: return initial * rate return (1 + rate) * cpi_increase(year - 1, initial, rate) If we print this out we can see the values about match up: initial = 100000 rate = 0.05 for year in range(11): print('{year:&lt;5} {total:&lt;21} {cpi_increase}'.format( year=year, total=initial * (1 + rate) ** year, cpi_increase=cpi_increase(year, initial, rate) )) The values: 0 100000.0 0 1 105000.0 5000.0 2 110250.0 5250.0 3 115762.50000000001 5512.5 4 121550.62500000003 5788.125 5 127628.15625000003 6077.53125 6 134009.56406250005 6381.407812500001 7 140710.04226562506 6700.478203125001 8 147745.5443789063 7035.502113281251 9 155132.8215978516 7387.2772189453135 10 162889.4626777442 7756.64107989258 Thinking through our base cases also shows how to create the direct calculation. At year y we have applied the (1 + rate) multiplication y - 1 times and the base (initial * rate) once. This gives us: def cpi_increase_direct(year, initial, rate): if year &lt;= 0: return 0 return initial * rate * (1 + rate) ** (year - 1)
accepted answer of: http://stackoverflow.com/q/52664372
score: 2

http://stackoverflow.com/comment/92170959
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52618381
type: QuestionComment
has text: @jasonharper Didn't think it'll be so simple... thank you

http://stackoverflow.com/a/52607695
downvote count: 0
has body: You'll first need a way to order your depth column. I'd suggest creating another column to hold your depth values as numbers. Let's say we first create a function to convert your data, and call your dataframe "df". The function depends on how your values on the depth column are organized. If they're all in a regular pattern, you can try something else, but if your values are organized like in your example, this could do the trick: def _depth_index(x): if x=='1m': return 1.0 elif x=='5m': return 5.0 elif x =='90': return 90.0 elif x=='eu' or x== 'MLD': return 0.0 #Not sure what 'eu' or 'MLD' stands for... Might want to return something else. else: return 0.0 # Default value After that, apply your function to the new column in your dataframe: df['indexed_depth'] = df['depth'].apply(lambda x: _depth_index(x)) And just sort your values: sorted_df = df.sort_values(['stations', 'indexed_depth'], ascending=[True, True])
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/92149754
answers question: http://stackoverflow.com/q/52607608
accepted answer of: http://stackoverflow.com/q/52607608
has comment: http://stackoverflow.com/comment/92149660
type: AcceptedAnswer

http://stackoverflow.com/comment/92157149
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52611379
has text: Please include your expected result in your post.
score: 0

http://stackoverflow.com/q/52741580
tagged with: python
has title: Installing Python 3.7 on Freebsd 11 with ssl
type: Question
has comment: http://stackoverflow.com/comment/92409598
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/52742410
tagged with: freebsd
upvote count: 5
tagged with: openssl
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/53148376
type: UnansweredQuestion
has body: I am trying to install Python 3.7 on Freebsd 11.1 with ssl support. Attempt #1: The pre-built binary won't run due to libdl.so.1 not found pkg install python37 ... root@s0001:~ # python3.7 Shared object "libdl.so.1" not found, required by "python3.7" Attempt #2: I downloaded the python 3.7 source and attempted to build with defaults but ssl module not found ./configure make ... Python build finished successfully! The necessary bits to build these optional modules were not found: _gdbm _sqlite3 _ssl _tkinter spwd To find the necessary bits, look in setup.py in detect_modules() for the module's name. Attempt #3: I noticed there is source for openssl 1.1.1 inside the python tarball so I tried --with-openssl, but got compiler errors: ./configure --with-openssl=openssl-1.1.1 make openssl-1.1.1/include/openssl/bn.h:332:1: error: expected function body after function declarator DEPRECATEDIN_0_9_8(int ^ openssl-1.1.1/include/openssl/bn.h:403:1: error: expected function body after function declarator DEPRECATEDIN_0_9_8(int BN_get_params(int which)) /* 0, mul, 1 high, 2 low, 3 ^ In file included from /root/Python-3.7.0/Modules/_hashopenssl.c:23: In file included from openssl-1.1.1/include/openssl/evp.h:28: In file included from openssl-1.1.1/include/openssl/objects.h:15: It seems like installing Python with ssl support (I would think using the openssl that comes in the tarball) should be straightforward. What is the correct way to do this?

http://stackoverflow.com/comment/92288412
score: 0
type: AnswerComment
has text: That's nice. How would I have to do to get the folders a numerical sequence rather than a timestamp. For example, 0001, 0002, and so on?
type: Comment
comment on: http://stackoverflow.com/a/52679791

http://stackoverflow.com/q/52593080
has answer: http://stackoverflow.com/a/52594224
answer count: 3
has body: For example I type word = "aaBBaac" How would I get the output to be [2,2,3] This is what I already have: word = input() count = 0 for i in range(0,len(word)): if word[i-1].islower()==word[i].islower()==True: count+=1 print(count)
has comment: http://stackoverflow.com/comment/92120945
favorite count: 0
has title: How to count consecutive uppercase and lowercase letters?
upvote count: 2
possible better answer: http://stackoverflow.com/a/52593255
tagged with: python
has answer: http://stackoverflow.com/a/52593255
accepted answer: http://stackoverflow.com/a/52594224
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52593856
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/92121094
has comment: http://stackoverflow.com/comment/92120880
score: -1

http://stackoverflow.com/comment/92276015
has text: Thanks so much for the code sample. I got mine going before I saw it, but yours incorporates things that I have yet to put in... that I need. You rock!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52673016

http://stackoverflow.com/comment/92384775
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52729604
has text: Thank you. I am able to now run the server. However, this may be an entirely new question, but I get the error when I go to the page: `Can't open lib 'ODBC Driver 13 for SQL Server' : file not found`. Any help??

http://stackoverflow.com/a/52658868
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52658705
accepted answer of: http://stackoverflow.com/q/52658705
type: AcceptedAnswer
downvote count: 0
has body: Or use itertools (builtin package) and some list comprehensions (i recommend this way): import itertools t.sort(key=lambda x: x['r_gr']) a = [sum(int(item['a']) for item in group) for key, group in itertools.groupby(t, key=lambda x: x['r_gr'])] r_gr = sorted(set([i['r_gr'] for i in t]),key=[i['r_gr'] for i in t].index) e = [int(str(i)[0]) for i in [x['e'] for x in t]] print(a) print(r_gr) print(e) Output: [14, 0, 14] [1, 2, 3] [1, 2, 1, 1, 1, 2]
upvote count: 2

http://stackoverflow.com/comment/92198202
type: Comment
type: QuestionComment
has text: The error is because you have EURCAD twice in your variable `pairs`.
comment on: http://stackoverflow.com/q/52630256
score: 0

http://stackoverflow.com/q/52649823
upvote count: 1
type: UnansweredQuestion
tagged with: list-comprehension
has title: Separating nested for loops in list comprehensions
has comment: http://stackoverflow.com/comment/92231655
downvote count: 0
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/92231715
favorite count: 0
type: Question
has body: Starting from this dataframe import pandas as pd df2 = pd.DataFrame({'t': ['a', 'a', 'a', 'b', 'b', 'b'], 'x': [1.1, 2.2, 3.3, 1.1, 2.2, 3.3], 'y': [1.0, 2.0, 3.0, 2.0, 3.0, 4.0]}) it's possible to simplify these nested for loops: for t, df in df2.groupby('t'): print("t:", t) for d in df.to_dict(orient='records'): print({'x': d['x'], 'y': d['y']}) by separating the inner loop into a function: def handle(df): for d in df.to_dict(orient='records'): print({'x': d['x'], 'y': d['y']}) for t, df in df2.groupby('t'): print("t:", t) handle(df) How might I similarly separate a nested list comprehension : mydict = { t: [{'x': d['x'], 'y': d['y']} for d in df.to_dict(orient='records')] for t, df in df2.groupby(['t']) } into two separate loops? I'm asking the question with just two levels of nesting, yet with just two nested loops the need is hardly critical. The motivations are: By the time there are a few levels, the code becomes tough to read. Developing and testing smaller blocks guards against (present and future) mistakes at more than the outer level.
tagged with: python
has comment: http://stackoverflow.com/comment/92231869

http://stackoverflow.com/comment/92347645
score: 4
type: Comment
type: QuestionComment
has text: Your issue is that you’re doing all lines in one call to `is_triangle`. (Your `map` is also wrong: your `lambda` always returns `int` *itself*.)
comment on: http://stackoverflow.com/q/52710650

http://stackoverflow.com/comment/92177509
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52621902
type: Comment
has text: are you running this on remote hosts? you are not getting full output.

http://stackoverflow.com/a/58334167
upvote count: 17
downvote count: 0
type: Answer
has body: I have jupyter lab 1.1.4 installed on Ubuntu 18.04.3 LTS and am using a python 3 virtual env kernel and it works great. Just complete your notebook and then configure each cell using the "Notebook Tools" tab on the far left (as shown in screenshot). Then save and close the notebook and run below command to output the slides. Open the terminal and navigate to the recently saved .ipynb and run jupyter nbconvert Untitled2.ipynb --to slides For slides or say jupyter nbconvert Untitled2.ipynb --to pdf For a pdf Note: You might need to install the Tex package to perfrom pdf outputs. See the docs here or just run the below command to install it. sudo apt-get install texlive-xetex texlive-fonts-recommended texlive-generic-recommended Cheers
has comment: http://stackoverflow.com/comment/134771574
answers question: http://stackoverflow.com/q/52677085
score: 17

http://stackoverflow.com/comment/92411429
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52743006
has text: Not very helpful but for reference to anyone else looking, I compared this to just generating 3 random ints after fixing the seed value and doing that is about 30% slower than the hash method above.
score: 0

http://stackoverflow.com/q/52731664
has answer: http://stackoverflow.com/a/52731841
has answer: http://stackoverflow.com/a/52731771
linked to: http://stackoverflow.com/q/4843173
accepted answer: http://stackoverflow.com/a/52731771
answer count: 3
has title: How to test if any string is in a list?
has comment: http://stackoverflow.com/comment/92388490
tagged with: python
has comment: http://stackoverflow.com/comment/92389600
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92388483
has comment: http://stackoverflow.com/comment/92388471
has body: I'm trying to make an AI. The AI knows to say 'Hello' to 'hi' and to stop the program on 'bye', and if you say something it doesn't know it will ask you to define it. For example, if you say 'Hello' it will ask what that means. You type 'hi' and from then on when you say 'Hello' it will say 'Hello' back. I store everything in a list called knowledge. It works like this: knowledge = [[term, definition], [term, definition], [term, definition]] I am trying to add an edit function, where you type edit foo and it will ask for you to input a string, to change the definition of foo. However, I'm stuck. First, of course, I need to test if it already has a definition for foo. But I can't do that. I need to be able to do it regardless of the definition. In other languages, there is typeOf(). However type() doesn't seem to work. Here's what I have, but it doesn't work: if [term, type(str)] in knowledge: Can someone help?
type: Question
score: 0
possible better answer: http://stackoverflow.com/a/52731841
has answer: http://stackoverflow.com/a/52731944

http://stackoverflow.com/a/52694141
score: 0
accepted answer of: http://stackoverflow.com/q/52692513
type: AcceptedAnswer
has body: Well crud, I have fixed the problem but still don't know what caused it in the first place. This is what I did. First, because I have all sorts of other crap on my machine including other virtual machines and apache and stuff I decided to just reboot the machine. On reboot it still was not working so I started messing around with the IP address listed on the last line of the app.py file here is the app.py file for reference: from flask import Flask from redis import Redis, RedisError import os import socket # Connect to Redis redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2) app = Flask(__name__) @app.route("/") def hello(): try: visits = redis.incr("counter") except RedisError: visits = "cannot connect to Redis, counter disabled" html = " Hello {name}! " \ "Hostname: {hostname} " \ "Visits: {visits}" return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits) if __name__ == "__main__": app.run(host='0.0.0.0', port=80) I tried all sorts of things instead of 0.0.0.0 including localhost 127.0.0.1 1.2.3.4 I then thought, hmmm maybe i need to add a listing in the /etc/hosts file so i added this: 192.168.33.33 test.docker then cleared my dns cache and set the IP in the app.py file to: 192.168.33.33 Still not working. So in desperation I reset it back to 0.0.0.0 and tried one last time and for some dang reason now it's working. No idea why, and I would like to know exactly what i did to fix it still (if anyone has any insight)
type: Answer
answers question: http://stackoverflow.com/q/52692513

http://stackoverflow.com/a/52658659
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52658624
has body: How about using the os.path module? from os import path if path.exists(my_filepath): execute_my_program() You can add a sleep: from os import path from time import sleep def wait_and_process_file(filepath, wait_interval=5, max_time=3600): total_time = 0 while total_time &lt; max_time and not path.exists(filepath): sleep(wait_interval) total_time += wait_interval _finish_processing(filepath)

http://stackoverflow.com/comment/92292014
comment on: http://stackoverflow.com/q/52680956
score: 0
type: Comment
type: QuestionComment
has text: i'm not sure if I even use apache.. is it standard/included in django? If so i'm not sure how to restart it

http://stackoverflow.com/a/52677239
has comment: http://stackoverflow.com/comment/92283570
type: Answer
has comment: http://stackoverflow.com/comment/92283487
has body: Here's an example that you can use: l = text.replace(",","").replace(".","").split(" ") occurs = {} for word in l: occurs[word] = l.count(word) resultx = '' for word in occurs.keys() if occurs[word] &lt; 3: resultx += word + " " resultx = resultx[:-1] you can change 3 with what you think suited or based it on the average using : occurs.values()/len(occurs) Additional if you want it to be Case insensitive change the 1st line with : l = text.replace(",","").replace(".","").lower().split(" ")
has comment: http://stackoverflow.com/comment/92283474
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92283662
has comment: http://stackoverflow.com/comment/92283622
score: 0
answers question: http://stackoverflow.com/q/52677191

http://stackoverflow.com/comment/92228988
has text: @Yucaok i will do :))) thank you so much for ur intuition
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52647785

http://stackoverflow.com/a/54834895
type: AcceptedAnswer
has body: This issue was resolved a month ago. It turns out that for this particular web application, Selenium webdriver needed to have a direct link from the get-go; otherwise it would not "recognize" the page it was on. This web app is usually not linked to directly; you usually go through an intermediary page that has the link posted. I resolved this by directing Selenium to the web application directly instead of going through the intermediary page first and clicking on the web app link. I.e.: from selenium import webdriver import time driver = webdriver.Firefox() driver.get("[DIRECT LINK INSTEAD OF INTERMEDIARY PAGE LINK]") Hope this helps anyone with a similar issue in the future.
score: 0
accepted answer of: http://stackoverflow.com/q/52618687
type: Answer
answers question: http://stackoverflow.com/q/52618687

selenium-chromedriver
tags question: http://stackoverflow.com/q/52663724
tags question: http://stackoverflow.com/q/52679582
tags question: http://stackoverflow.com/q/52614592
tags question: http://stackoverflow.com/q/52683416
tags question: http://stackoverflow.com/q/52726572
tags question: http://stackoverflow.com/q/52604717
tags question: http://stackoverflow.com/q/52643556
tags question: http://stackoverflow.com/q/52676925
tags question: http://stackoverflow.com/q/52652684
tags question: http://stackoverflow.com/q/52680025
tags question: http://stackoverflow.com/q/52637338
tag name: selenium-chromedriver
tags question: http://stackoverflow.com/q/52663054
type: Tag
tags question: http://stackoverflow.com/q/52673190
tags question: http://stackoverflow.com/q/52635688

http://stackoverflow.com/comment/92352315
comment on: http://stackoverflow.com/a/52700149
has text: I am using different database like this in Django settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } }
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92206088
comment on: http://stackoverflow.com/q/52636309
type: QuestionComment
has text: Due to the `argparse` parsing approach it is hard, if not impossible, to do this. https://bugs.python.org/issue9334
score: 0
type: Comment

http://stackoverflow.com/a/52703961
has body: It's printing much of the data multiple times because the newtext variable, which you are printing after getting the text of each &lt;td&gt;&lt;/td&gt;, is just accumulating all the values. Easiest way to get this to work is probably to just move the line print(newtxt) outside of both for loops - that is, leave it totally unindented. You should then see a list of all the text, with that from each row on a new line, and that from each individual cell in a row separated by commas.
answers question: http://stackoverflow.com/q/52703694
score: 0
type: Answer

http://stackoverflow.com/comment/92331952
has text: Could you show us the output of `print(type(self.NmRqst.text))` before the failing `execute`? Thanks.
score: 1
comment on: http://stackoverflow.com/q/52702680
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52713100
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52742955
has comment: http://stackoverflow.com/comment/92370550
tagged with: python-3.6
has body: I'm attempting to create a temporary Excel file available for download via a Flask (v0.12) web application running on PythonAnywhere like so: from io import BytesIO from openpyxl import Workbook from flask import send_file from datetime import date # ... Flask app here # inside function/route serving Excel file buffer = BytesIO() wb = Workbook() ws = wb.active ws.title = "Sample" # populate sample data ws["A1"] = "some data" ws["A2"] = str(date.today()) # send file to requestor wb.save(buffer) buffer.seek(0) return send_file( buffer, as_attachment=True, attachment_filename="{}_workbook.xlsx".format(str(date.today())), mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) I'm getting this exception: SystemError: &lt;built-in function uwsgi_sendfile&gt; returned a result with an error set I can't figure out how to work around this. Full traceback: 2018-09-10 18:00:43,816: Error running WSGI application 2018-09-10 18:00:43,845: SystemError: &lt;built-in function uwsgi_sendfile&gt; returned a result with an error set 2018-09-10 18:00:43,846: File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1994, in __call__ 2018-09-10 18:00:43,846: return self.wsgi_app(environ, start_response) 2018-09-10 18:00:43,846: 2018-09-10 18:00:43,846: File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1985, in wsgi_app 2018-09-10 18:00:43,846: response = self.handle_exception(e) 2018-09-10 18:00:43,847: 2018-09-10 18:00:43,847: File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1540, in handle_exception 2018-09-10 18:00:43,847: reraise(exc_type, exc_value, tb) 2018-09-10 18:00:43,847: 2018-09-10 18:00:43,847: File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 33, in reraise 2018-09-10 18:00:43,847: raise value 2018-09-10 18:00:43,847: 2018-09-10 18:00:43,848: File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1982, in wsgi_app 2018-09-10 18:00:43,848: response = self.full_dispatch_request() 2018-…
answer count: 1
tagged with: flask
accepted answer: http://stackoverflow.com/a/52742955
favorite count: 0
has comment: http://stackoverflow.com/comment/92367097
has title: SystemError when attempting to create Excel spreadsheet for download from Flask app
tagged with: python
has comment: http://stackoverflow.com/comment/92389857
has comment: http://stackoverflow.com/comment/92389916
score: 2
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 3
has comment: http://stackoverflow.com/comment/92351944
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/92351844

http://stackoverflow.com/q/52602335
has answer: http://stackoverflow.com/a/52602357
has body: I just learned how to group a Pandas DataFrame with datetime index by dates. How can I count the number of specific values ('Passed' or 'Failed') on each day that is returned by the groupby? My goal is to calculate daily yield: yield = passed_count/(passed_count + failed_count). import pandas as pd import random data = [random.choice(['Passed','Failed']) for i in range(100)] times = pd.date_range('20180101',freq='3H',periods=100) df = pd.DataFrame({'A':data},index=times) group = df.groupby(pd.Grouper(freq='1D'))
type: Question
score: 0
tagged with: pandas
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Pandas count specific values in groupby results

http://stackoverflow.com/comment/92267702
comment on: http://stackoverflow.com/a/52668465
has text: I did exactly that (my directory also look exactly like that) but it still says "Unresolved reference" on both the "from" part and the "import" part. Is it different between using PyCharm and Python itself?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/129286960
type: Comment
comment on: http://stackoverflow.com/a/65240100
has text: `options.add_experimental_option("useAutomationExtension", False)` `options.add_experimental_option("excludeSwitches",["enable-automation"])` works and it is the part responsible for the test banner right..... Thank you.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52691027
type: Question
has comment: http://stackoverflow.com/comment/92309131
has comment: http://stackoverflow.com/comment/92309026
has comment: http://stackoverflow.com/comment/92309052
has answer: http://stackoverflow.com/a/52691081
answer count: 1
linked to: http://stackoverflow.com/q/8929284
has comment: http://stackoverflow.com/comment/92308993
accepted answer: http://stackoverflow.com/a/52691081
has comment: http://stackoverflow.com/comment/92309025
favorite count: 0
tagged with: python-3.x
has body: I have a list of dicts inserts that should be inserted into the database. Since some elements are already in the db db_entry_ids, I want to filter them out. Right now the code is pretty simple: [d for d in inserts if d["entry_id"] not in db_entry_ids] with len(inserts) = 35000 len(db_entry_ids) =280000 Python needs few minutes for that. I hope there is some simple way to make that more efficient. PS: d["entry_id"] is a string, as well as db_entry_ids, is a list of strings. So id might be a bit misleading.
tagged with: python
has title: Fastest way to filter list of dicts?
has comment: http://stackoverflow.com/comment/92309100
type: AnsweredQuestion
score: 2
tagged with: performance
upvote count: 3
duplicate of: http://stackoverflow.com/q/8929284
downvote count: 1

http://stackoverflow.com/a/52735636
has body: I've updated it as: pip install --upgrade prompt-toolkit==2.0.4 (old is 1.0.15） pip install --upgrade ipython==7.0.1 (old is 6.5.0） pip install --upgrade jupyter-console==6.0.0 (old is 5.2.0） However, the above problems are not solved, and the above information remains unchanged.
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52734739

http://stackoverflow.com/q/52747090
has body: So I am currently working on a Raspberry Pi Project. My Raspi is connected to my letterbox, so everytime someone opens it, a button is pushed. When the button is pushed, a script should detect this and send me an EMail, and write the current Time and Date in a .txt file. My script that I made a little bit by my self and with the help of the internet, works, but it randomly detects a GPIO input every 10-20 Minutes (the Wires that are connected to the button are very long and my Raspi is connected in a room that is full with cabels, this might be the Problem). But, I tried to do it with a script that I just found on the internet. Just copy it (well, at least the GPIO part). So this script works, but mine detects a random input. Another Problem (you'll see it in the script) that I had with an old script was, that I used a while loop, and it used 97% of my CPU. So I did another script that would work differently. It doesnt use 97% of my CPU, but it detects random Inputs. In the script that I copied from the internet also uses a while loop, but it doesnt take that much CPU. But why? I dont understand that either. This is my Script, that detects random Inputs: import RPi.GPIO as GPIO import smtplib import pytz from pytz import timezone import datetime from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setup(7,GPIO.IN,) def writeanemail(): smtpUser = '' smtpPass = '' toAdd = '' fromAdd = smtpUser subject = 'Du hast etwas in deinem Postfach' header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject print ("\n" + header) s = smtplib.SMTP('smtp.gmail.com',587) s.ehlo() s.starttls() s.ehlo() s.login(smtpUser, smtpPass) s.sendmail(fromAdd, toAdd, header) s.quit() def timelog(): now = datetime.datetime.now(timezone('Europe/Berlin')) file = open("/home/pi/ps/gpio.log","a") file.write("\n" + now.strftime("%Y-%m-%d--%a %H:%M:%S")) file.close() print ("\n" + now.strftime("%Y-%m-%d--%a %H:%M") + "\n" + "\n" + "Log wurde geschrieben") def main(): GPIO.wait_for…
has title: GPIO random input, Difference between scripts?
score: 1
favorite count: 0
type: Question
tagged with: gpio
tagged with: python
upvote count: 1
tagged with: raspberry-pi
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/92348774
type: Comment
comment on: http://stackoverflow.com/q/52711297
has text: You managed to print the values, what prevents you from printing the headers?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92328099
type: QuestionComment
comment on: http://stackoverflow.com/q/52700655
score: 0
type: Comment
has text: The error says your views file does not have an "index" function. Did you define one? (And don't post links to pictures of code, put the code here in the question.)

http://stackoverflow.com/comment/92117895
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52591542
has text: What is the function that is responsible for scanning?
score: 0

http://stackoverflow.com/a/76759215
answers question: http://stackoverflow.com/q/52640648
score: 0
type: Answer
has body: This was how I was able to do it in the most simple way possible. num_rows = int(input()) num_cols = int(input()) row = 1 col = 65 while row &lt;= num_rows: col = 65 while col &lt;= (num_cols + 64): print('{}{}'.format(row, chr(col)), end= ' ') col += 1 row += 1 print() By using chr() I was able to convert the int input (which zybooks doesn't let you alter) to get the ascii code for uppercase A. You have to use uppercase letters and you have to leave spaces at the end of each pair.

http://stackoverflow.com/comment/92338905
type: AnswerComment
type: Comment
has text: IIUC, if all of your dictionaries contain the same set of keys, then you can modify the first for loop to `for key in dict1.keys()`
comment on: http://stackoverflow.com/a/52705987
score: 0

http://stackoverflow.com/q/52740675
has comment: http://stackoverflow.com/comment/92406610
tagged with: python
has comment: http://stackoverflow.com/comment/92407286
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52740973
accepted answer: http://stackoverflow.com/a/52740973
type: Question
has body: I have a list of dictionary, where I need to calculate the exit time by adding time delta to the entry time. I then need to update the entry time of the next row with the exit time of the previous row, and add another delta to it, which then becomes the exit time. lst = [ {'entry_time': [datetime.time(8, 20)],'exit_time': [0]}, {'entry_time': [],'exit_time': []}, {'entry_time': [0],'exit_time': [0]}, {'entry_time': [],'exit_time': []} ] delta_lst = [datetime.timedelta(0, 53), datetime.timedelta(0, 32), datetime.timedelta(0, 32), datetime.timedelta(0, 32)] I have spend many days on this, but I feel that I am missing something for such a simultaneous operation. I dont know much about other data structures, but I should I be considering heap or queues or stack? Here's the code I have. for idx,l in enumerate(lst): for key,val in l.items(): if key == 'entry_time': try: entry_time = l[key][0] cal_ExitTime(entry_time,idx) l['exit_time'] = [exit_time] except: entry_time = lst[idx-1]['exit_time'][0] l['entry_time'] = [exit_time] cal_ExitTime(entry_time,idx) l['exit_time'] = [exit_time] There's a function cal_ExitTime which is written as such - def cal_ExitTime(entry_time,idx): converted_start_time = datetime.datetime.combine(datetime.date(1,1,1),entry_time) exit_time = (converted_start_time + delta_lst[idx]).time() return exit_time When I run my program, 1st dictionary entry in my list gets updated, and the rest of my entry_time and exit_time gets updated with the exit_time of my 1st row. It may seem that the entries of my dictionary of list is not consistent (ie empty list or 0 value), but the source of my data is as such. My expected code as follows - lst = [ {'entry_time': [datetime.time(8, 20)],'exit_time':[datetime.time(8, 20, 53)]}, {'entry_time': [datetime.time(8, 20,53)],'exit_time': [datetime.time(8, 21, 25)]}, {'entry_time': [datetime.time(8, 21, 25)],'exit_time': [datetime.time(8, 21, 57)]}, {'entry_time': [datetime.time(8, 21, 57)],'exit_time': [datetime.time(8, …
has title: Iterate over a list of dictionary and update values from previous row
score: 0
has comment: http://stackoverflow.com/comment/92406155
answer count: 1

http://stackoverflow.com/a/52730909
has comment: http://stackoverflow.com/comment/92406539
has comment: http://stackoverflow.com/comment/92404785
has comment: http://stackoverflow.com/comment/92387858
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92387425
answers question: http://stackoverflow.com/q/52730332
has comment: http://stackoverflow.com/comment/92387103
has body: This will work. Leave a comment if you need the output to be different. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait url = 'http://www.attheraces.com/racecard/Wolverhampton/6-October-2018/1715' driver = webdriver.Chrome() driver.get(url) driver.implicitly_wait(2) driver.find_element_by_xpath('//*[@id="racecard-tabs-1061960"]/div[1]/div/div[1]/ul/li[2]/a').click() WebDriverWait(driver, 5).until(expected_conditions.presence_of_element_located((By.XPATH, '//*[@id="tab-racecard-sectional-times"]/div/div[1]/div[1]/div[2]/div/button'))) # method 1 for horse in driver.find_elements_by_class_name('card-item'): horseName = horse.find_element_by_class_name('form-link').text times = horse.find_elements_by_class_name('sectionals-time') times = [time.text for time in times] print('{}: {}'.format(horseName, times)) print() # method 2 for horse in driver.find_elements_by_class_name('card-item'): for time in horse.find_elements_by_class_name('sectionals-time'): print(time.text) print() driver.close()
score: 0
accepted answer of: http://stackoverflow.com/q/52730332
has comment: http://stackoverflow.com/comment/92424155
type: Answer
has comment: http://stackoverflow.com/comment/92423006
has comment: http://stackoverflow.com/comment/92424686
has comment: http://stackoverflow.com/comment/92387922
has comment: http://stackoverflow.com/comment/92387076

http://stackoverflow.com/comment/92296285
comment on: http://stackoverflow.com/q/52684172
score: 0
has text: You can create a regex for each pattern within the list of tokens and then `|` them. If you have really many, then maybe whitelisting the good stuff helps you instead of blacklisting these tokens.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52680096
favorite count: 0
possible better answer: http://stackoverflow.com/a/52681117
type: Question
accepted answer: http://stackoverflow.com/a/52680125
answer count: 2
has answer: http://stackoverflow.com/a/52681117
tagged with: python
has body: Supposing I have a 2 x 2 x 100 ndarray called ahat and a 2 x 2 matrix called A. What is the most pythonic way to subtract the 2 x 2 matrix from along the dimension of size 100 without looping or reshaping? for k in range(ahat.shape[2]): ahat[:,:,k] = ahat[:,:, k] - A I tried using np.apply_over_axes but couldn't get it to work. More generally if I have two ndarrays of compatible shapes like in the example above, what is preferred way to operate along a particular dimension. For the example I might want to multiply every 2x2 matrix in ahat with A or I might want to apply np.linalg.inv along the dimension of size 100.
upvote count: 1
tagged with: numpy
has answer: http://stackoverflow.com/a/52680125
has title: Subtract matrix from ndarray along particular dimension without reshape
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/52689954
has comment: http://stackoverflow.com/comment/92306958
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 8
tagged with: python-asyncio
tagged with: python
has comment: http://stackoverflow.com/comment/92306918
tagged with: discord
type: AnsweredQuestion
score: 7
has comment: http://stackoverflow.com/comment/92306904
downvote count: 1
type: Question
tagged with: discord.py
has title: What it really is @client.event? discord.py
has body: A few days ago I became interested in programming discord bots a bit. In the syntax of these programs I noticed a lot of unintelligible issues that I can not find an answer to. That's why I am asking you for help in understanding them. All questions are based on this code: import discord import asyncio from discord.ext import commands botToken = '***' client = commands.Bot(command_prefix = '.') @client.event async def on_ready(): print('Bot is ready!') @client.event async def on_message(message): author = message.author if message.content =='Hello': await client.send_message(message.channel, 'Welcome again {}!'.format(author)) client.run(botToken) What is @client.event? I found that is a event handler, but how is it worki? Why is it needed to run program? Is it somehow connected to a asyncio?
has comment: http://stackoverflow.com/comment/92306752
has answer: http://stackoverflow.com/a/52690271
accepted answer: http://stackoverflow.com/a/52690271

http://stackoverflow.com/a/52661186
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/92253280
has comment: http://stackoverflow.com/comment/92253387
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52661127
has body: I believe you need transform size and then filter by boolean indexing: df = pd.concat([dfs]) df = df[df.groupby('appId')['appId'].transform('size') &gt;= 30] #alternative 1 #df = df[df.groupby('appId')['appId'].transform('size').ge(30)] #alternative 2 (slowier in large data) #df = df.groupby('appId').filter(lambda x: len(x) &gt;= 30) Another approach is filter dictionary: dfs = {k: v for k, v in dfs.items() if len(v) &gt;= 30} EDIT: timeseries = timeseries[timeseries.groupby('appId')['appId'].transform('size') &gt;= 30] dfs = dict(tuple(timeseries.groupby('appId')))
answers question: http://stackoverflow.com/q/52661127
type: Answer
has comment: http://stackoverflow.com/comment/92253478
has comment: http://stackoverflow.com/comment/92253264
has comment: http://stackoverflow.com/comment/92253796

http://stackoverflow.com/q/52656521
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: performing operations on blocks of data
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/92301612
has comment: http://stackoverflow.com/comment/92244176
tagged with: numpy
score: 0
tagged with: pandas
has body: I have this huge text file with data inside it that I want to reorder in a new format. *******unwanted headers******** results - 1 2 3 4 3 6 7 8 1 2 3 4 2 6 7 8 1 2 3 4 1 6 7 8 1 2 3 - - 1 2 3 4 3 6 7 8 2 2 3 4 2 6 7 8 1 2 3 - 2 2 3 4 3 6 7 8 1 2 3 4 2 6 7 8 1 2 3 1 2 3 - Input is in format: N, X, Y, E, T, x, y, z I want to do the following: Ignore header lines loop each block (one block is any successive lines with length = 8) sort T column from lowest to highest look at N column and check if there is 1 in the first line followed by 2 in the following line (applied only to the lines of length 8) get z, y, x, E of the two lines repeat steps 3, 4, and 5 for each block output should be in format: z1 y1 x1 E1 z2 y2 x2 E2 This means that my code should not report a result from the first two blocks because they do not fulfil the conditions I set, but the third block will report a result. Note: the data are floats, not integers. I have tried this code but it is not working: import fileinput for Line in fileinput.input(): Line = Line.split() if Line == '- ': continue if len(Line) == 8: 'apply the conditions' continue if len(Line) != 8: break

http://stackoverflow.com/a/52640696
has body: Try replacing the date_filter (self) method in the Test.py module. def date_filter(self): ## self.main = Ui_MainWindow.setupUi(self, MainWindow) # --- ## self.main.show() # --- date_text = str(date_select) print(date_select) ## #self.label.setText(date_text) # --- ui.label.setText(date_text) # +++
accepted answer of: http://stackoverflow.com/q/52636230
has comment: http://stackoverflow.com/comment/92227566
answers question: http://stackoverflow.com/q/52636230
has comment: http://stackoverflow.com/comment/92235665
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92235563
has comment: http://stackoverflow.com/comment/92235775

http://stackoverflow.com/a/52693856
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52684689
accepted answer of: http://stackoverflow.com/q/52684689
has comment: http://stackoverflow.com/comment/96182294
has body: BoxLayout does have an attribute named minimum_height. Which is automatically computed minimum height needed to contain all children. Therefore, you are not suppose to modify minimum_height in BoxLayout To prevent such modification, Kivy has made it as read only. That is the reason why you have no access to modify it. Best way to prove it is to open up boxlayout.py inside of your Kivy folder. minimum_height = NumericProperty(0) '''Automatically computed minimum height needed to contain all children. .. versionadded:: 1.10.0 :attr:`minimum_height` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. It is read only. '''
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/92200895
comment on: http://stackoverflow.com/a/52633715
score: 0
has text: @Newe That's really weird. Could you try `print(ctx.invoked_subcommand)` to see what that's being populated with?
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52742612
has title: How to print the stack trace of an exception object in Python?
favorite count: 0
tagged with: exception
tagged with: python
has answer: http://stackoverflow.com/a/52742770
upvote count: 34
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52742922
has comment: http://stackoverflow.com/comment/92410510
has answer: http://stackoverflow.com/a/52742922
downvote count: 1
linked to: http://stackoverflow.com/q/3702675
score: 33
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52742770
has body: How to print the stack trace of an exception object in Python? Note that the question is NOT about printing stack trace of LAST exception. Exception object may be saved at some distant point of time in the past.

http://stackoverflow.com/q/52695976
has body: I have expression correct find desire variables but I wish to only prints like second result and then third results and so on. Is there like better way doing this? Maybe adding to SQL database and recall it from it? The final goal to display these results within a windows and sources is RSS feed with first 2 result not desired so I hoping like range command where I can choose to select third results like [2]. str1 = open("source/news.xml") file_contents = str1.read() title=file_contents.find('&lt;item&gt;&lt;title&gt;(.+?)&lt;\/title&gt;') j = 2 while i &lt; 10: i = i+1 trending = Label(the_window2, text=title[j+1], font=('Arial', 12)) trending.grid(column = 1, row = i, padx = 2, columnspan=4) Or using xml.etree xmltext = ET.parse('source/old_news.xml') root = xmltext.getroot() for title in root: print(title.attrib) SQL Method: I can't seem to get SQL loop working as error: "TypeError: string indices must be integers" connection = connect(database = 'source/old_news.db') news = connection.cursor() str1 = open("source/old_news.xml") file_contents = str1.read() for item in file_contents['items']: title = item.title link = item.link description = item.description print (title) print (link) print (description) connection.execute("INSERT INTO ini (title, link, description) VALUES (%s, %s, %s)", (title, link, description)) print ('Succesfull!')
type: Question
has comment: http://stackoverflow.com/comment/92326571
tagged with: python-3.6
has title: Findall - certain range
score: 0
tagged with: findall
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/92350119
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52699466
has comment: http://stackoverflow.com/comment/92326413
favorite count: 0
has comment: http://stackoverflow.com/comment/92326663
has comment: http://stackoverflow.com/comment/92326717
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92326190
has body: I can't extract the correct result with using requests_html: &gt;&gt;&gt; from requests_html import HTMLSession &gt;&gt;&gt; session = HTMLSession() &gt;&gt;&gt; r = session.get('https://www.amazon.com/dp/B07569DYGN') &gt;&gt;&gt; r.html.find("#productDetails_detailBullets_sections1") [] I can find the id 'productDetails_detailBullets_sections1' in the source content: &gt;&gt;&gt; """&lt;table id="productDetails_detailBullets_sections1" class="a-keyvalue prodDetTable" role="presentation"&gt;""" in r.text True Actually, the issue similarly exist in PyQuery. Why can't requests_html find this element?
tagged with: pyquery
type: UnansweredQuestion
tagged with: python-requests-html
tagged with: python
has comment: http://stackoverflow.com/comment/92326887
has title: Can't extract the result as expected when using requests_html
score: 3
has comment: http://stackoverflow.com/comment/92326298
downvote count: 0
has comment: http://stackoverflow.com/comment/92326800
has comment: http://stackoverflow.com/comment/92325707
type: Question
has comment: http://stackoverflow.com/comment/92327001
has answer: http://stackoverflow.com/a/52700350
upvote count: 3
answer count: 1

http://stackoverflow.com/a/52633375
has body: You are importing CountVectorizer but referencing countVectorizer.
upvote count: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52632777
accepted answer of: http://stackoverflow.com/q/52632777
type: Answer
score: 3

discord
tags question: http://stackoverflow.com/q/52684112
tags question: http://stackoverflow.com/q/52712850
tags question: http://stackoverflow.com/q/52682463
tags question: http://stackoverflow.com/q/52741970
type: Tag
tags question: http://stackoverflow.com/q/52705105
tags question: http://stackoverflow.com/q/52593777
tags question: http://stackoverflow.com/q/52592965
tags question: http://stackoverflow.com/q/52699523
tags question: http://stackoverflow.com/q/52651672
tags question: http://stackoverflow.com/q/52680071
tags question: http://stackoverflow.com/q/52636911
tags question: http://stackoverflow.com/q/52681779
tags question: http://stackoverflow.com/q/52678790
tags question: http://stackoverflow.com/q/52667764
tags question: http://stackoverflow.com/q/52633366
tag name: discord
tags question: http://stackoverflow.com/q/52634448
tags question: http://stackoverflow.com/q/52683834
tags question: http://stackoverflow.com/q/52612693
tags question: http://stackoverflow.com/q/52738220
tags question: http://stackoverflow.com/q/52689954
tags question: http://stackoverflow.com/q/52701597
tags question: http://stackoverflow.com/q/52612358
tags question: http://stackoverflow.com/q/52676734

http://stackoverflow.com/comment/92125429
has text: @echtouka That is because in python setting a variable actually sets a reference to the variable. Variable names in python are references to the original. I would recommend you to read the answer in [this](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52594386
type: AnswerComment

http://stackoverflow.com/comment/92377590
type: AnswerComment
comment on: http://stackoverflow.com/a/52725100
type: Comment
has text: @G_M not discussing this furter, remove the sorting step and look at the results, they will not be the proper output, cheers
score: 0

http://stackoverflow.com/comment/92413244
comment on: http://stackoverflow.com/a/52736785
score: 4
has text: Not in the library itself. You must use something like `requests` to download images over http. It's just a few lines of code. https://stackoverflow.com/a/32859290/1977847
type: Comment
type: AnswerComment

http://stackoverflow.com/a/52625177
has body: It is not matching "key3" because the line is missing a quote and a semi-colon. Try pattern re.compile(r'^"(.*)"\s+=\s+"(.*)"?;?',re.MULTILINE) or re.compile(r'^"(.*)"\s+=\s+"(.*)$',re.MULTILINE) Ex: import re s = '''"key1" = "value1"; "key2" = "value2"; "key3" = "value3_line1 value3_line2 value3_line3"; "key4" = "value4";''' regex = re.compile(r'^"(.*)"\s+=\s+"(.*)"?;?',re.MULTILINE) matches = [m.groups() for m in regex.finditer(s)] for m in matches: print(m[0], '=&gt;', m[1]) Output: ('key1', '=&gt;', 'value1";') ('key2', '=&gt;', 'value2";') ('key3', '=&gt;', 'value3_line1') ('key4', '=&gt;', 'value4";')
answers question: http://stackoverflow.com/q/52624992
score: 0
type: Answer

http://stackoverflow.com/q/52605334
has answer: http://stackoverflow.com/a/52605513
downvote count: 0
answer count: 1
has body: I have the following input : Year Brand Model Value 2018 A a 1,00 2018 A b 2,00 2018 B a 3,00 2017 A b 4,00 2016 C b 5,00 I would like to add the missing combinaisons : for each year, I must have A, B and C for each Brand, I must have a and b The expected output is like that : Year Brand Model Value 2018 A a 1 2018 A b 2 2018 B a 3,00 2018 B b 2018 C a 2018 C b 2017 A a 2017 A b 4 2017 B a 2017 B b 2017 C a 2017 C b 2016 A a 2016 A b 2016 B a 2016 B b 2016 C a 2016 C b 5 How can I do that ?
favorite count: 0
tagged with: pandas
has title: Pandas Add missing row
tagged with: python
accepted answer: http://stackoverflow.com/a/52605513
upvote count: 2
type: AnsweredQuestion
type: Question
score: 2

http://stackoverflow.com/a/52713610
has body: You need to parse the string with the right format: from datetime import datetime input = "2018-10-09 20.00" # ^^^^^^^^^^^^^^^^-----⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄ d = datetime.strptime(input, "%Y-%m-%d %H.%M") # parse to datetime object result = d.strftime("%m/%d/%Y %H:%M:%S") # now convert to desired format #⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄-^^^^^^^^^^^^^^^^^ '10/09/2018 20:00:00'
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52713587
score: 1
accepted answer of: http://stackoverflow.com/q/52713587
type: AcceptedAnswer
downvote count: 0

pygobject
type: Tag
tags question: http://stackoverflow.com/q/52703513
tags question: http://stackoverflow.com/q/52724273
tag name: pygobject

http://stackoverflow.com/a/52600771
answers question: http://stackoverflow.com/q/52600752
downvote count: 0
type: AcceptedAnswer
has body: Add a checker for your code at the very end of yor file: if __name__=="__main__": vec1 = Vector(0, 0) vec2 = Vector(2,2) vec3 = vec1.add(vec2) print(vec1, vec2, vec3) #add other tests
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/52600752
score: 2

http://stackoverflow.com/a/52718290
has body: The amount of time [False for _ in range(128)] takes is fixed and therefore has a time complexity of O(1).
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52718194
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92156501
score: 0
has text: Possible duplicate of [How to animate the colorbar in matplotlib](https://stackoverflow.com/questions/39472017/how-to-animate-the-colorbar-in-matplotlib)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52610966

http://stackoverflow.com/comment/92359526
type: QuestionComment
has text: http://codereview.stackexchange.com contains a ton of examples of _working_ code. Look at them.
score: 0
comment on: http://stackoverflow.com/q/52716888
type: Comment

http://stackoverflow.com/comment/92324238
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52697707
has text: Well, probably a list of regexes will be accepted, try `d = {}`, `d["$regex"] = []`, `for word in s.split():`, `d["$regex"].append(re.compile(re.escape(word)))`. See https://ideone.com/EEDYF9
score: 0

http://stackoverflow.com/a/52744745
answers question: http://stackoverflow.com/q/52744591
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52744591
has body: the 'ten' or '10' in compareName part is not going to give you the results you want. It'll return 'ten' every time! instead, you need to check whether 'ten' is in compareName, and also check whether '10' is in compare name, and put the or between the two, like so: if 'blazer' in compareName and ('ten' in compareName or '10' in compareName):
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/52672304
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52672130
score: 1
has comment: http://stackoverflow.com/comment/92274444
downvote count: 0
has body: 1) remove quotation from weights 2) cast char as int, right after try 3) the remainder from division (modulo) is % btw

http://stackoverflow.com/comment/92231556
type: Comment
has text: `UseShellExecute` is a can of worms. `UseShellExecute` + script will not work on newer versions. See https://github.com/dotnet/corefx/issues/24704. In recent versions it does `xdg-open` instead of `bash -c` :( I would suggest calling out to `bash` manually, but I suspect we will run into OP's question (recursively!)
comment on: http://stackoverflow.com/a/52648888
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92420469
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52732020
has text: @tristanm. I am not sure you really have a problem here. If you do `x.thing_a`, you do *not* expect to see an error message saying "attribute blah_blah_blah not found". You should not be exposing implementation details and the user should not care *why* they can't access `thing_a`. In that sense, the existing error message is correct. If you really want a detailed exception, though, just don't raise an `AttributeError`.
type: AnswerComment

http://stackoverflow.com/comment/92117765
has text: @Gilles Gouaillardet Why and how would that help?
comment on: http://stackoverflow.com/q/52589839
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/77011615
answers question: http://stackoverflow.com/q/52682289
type: Answer
has body: The DisCoPy module is backed by formal research in DisCoCat. It uses NetworkX to implement hypergraphs. It also features a drawing module: https://docs.discopy.org/en/main/_modules/discopy/hypergraph.html
score: 0

http://stackoverflow.com/a/52600335
type: Answer
has body: It is important to understand what is happening where - your Pyramid app is basically a program which gets a text blob as its input (request) and returns another text blob as its output (response). When received by the browser, the response text blob is interpreted, in this case, as an HTML page, with all its script tags etc. The browser then executes the javascript which only has access to the DOM which is generated from that HTML blob. The fact that your Pyramid app used a Jinja2 template to generate that blob is irrelevant at that point. So now you can see that "vue.js in jinja2 template" is never actually happening - it's always "vue.js in HTML", and the only thing you need is to ensure your app outputs the correct HTML. This may be a bit problematic in this particular case because both jinja2 and vue.js use {{...}} as text interpolation syntax. If you view page source in your browser you'll see that the {{ title }} bit got processed by Jinja2 and vue.js never sees it. You're basically generating one template from another template with a similar syntax. I'm not super-familiar with either Jinja2 or vue.js, but I would try the following: Consider changing the templating library to something which syntax does not clash with vue.js. Maybe TAL or Mako. If you want to keep using Jinja2, you'll need some sort of function which outputs Vue.js markup from a Jinja template: def vue_markup(s): return '{{ ' + s + ' }}' which you would use in your template like this: {{ vue_markup('title') }}
score: 2
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52599124
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/52599124

http://stackoverflow.com/q/52721403
duplicate of: http://stackoverflow.com/q/42613581
answer count: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92368115
score: 0
tagged with: pandas
has title: Pandas Dataframe Sorting by Date Time
has body: whenever I run print(dfsamen.sort_values(['DateTime'])) my code works fine and the date is properly sorted and looks like this: 2018-08-31 00:00:02 2018-08-31 00:00:12 2018-08-31 00:00:22 2018-08-31 00:00:32 but when I do it this way (I want it this way so I can do calculations, i know i can write it to csv and then load it back in but that seems redundant) dfsamen.sort_values(by=['DateTime']) print(dfsamen) this is the output (like it is in the excel file) 2018-08-31 03:54:10 2018-08-31 03:54:20 2018-08-31 03:48:52 I also tried this: dfsamen.reset_index() dfsamen.set_index(['DateTime']) dfsamen.sort_index(inplace=True) which resulted in the same outcome.
favorite count: 0
linked to: http://stackoverflow.com/q/42613581
has comment: http://stackoverflow.com/comment/92367908
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92368082
tagged with: python

http://stackoverflow.com/a/62121270
type: Answer
has body: If you just print(character * count) of course you will get the right output but the goal is to create an operational function and then output by using the function import sys character= sys.argv[1] count= int(sys.argv[2]) def generateString(char, val): string = char * val return string print(generateString(character, count))
answers question: http://stackoverflow.com/q/52693573
score: 0

http://stackoverflow.com/comment/92240113
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52654302
type: Comment
has text: @PeterWood ran it with that, but same result. `p4.password` is set to `''` by default.

http://stackoverflow.com/a/52721502
answers question: http://stackoverflow.com/q/52717181
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92369804
type: Answer
upvote count: 4
downvote count: 0
has body: The problem is from the import. The proper way to do this is to do the following : from keras.applications import MobileNetV2 m = MobileNetV2(weights='imagenet', include_top=False)
accepted answer of: http://stackoverflow.com/q/52717181

http://stackoverflow.com/q/52716136
has body: I want to create a simple model using TF Estimator. Below is my code: num_epoch = 4 num_train = 186 num_test = 81 # 1 Define input function def input_function(x, y, is_train): dict_x = { "featurename" : x, } dataset = tf.data.Dataset.from_tensor_slices(( dict_x, y )) if is_train: dataset = dataset.shuffle(num_train, seed=113).repeat(num_epoch).batch(num_train) else: dataset = dataset.batch(num_test) return dataset def my_serving_input_fn2(): input_data = { "featurename" : tf.placeholder(tf.float32, [None, 15], name='inputtensors') } return tf.estimator.export.ServingInputReceiver(input_data, input_data) def main(argv): tf.set_random_seed(113) np.random.seed(113) run_config = tf.estimator.RunConfig(save_summary_steps=None, save_checkpoints_secs=None, tf_random_seed=113) # 2 Define feature columns feature_columns = [ tf.feature_column.numeric_column(key="featurename",shape=15), ] # 3 Define an estimator classifier = tf.estimator.DNNClassifier( feature_columns=feature_columns, hidden_units=[15, 15], n_classes=3, optimizer=tf.train.AdamOptimizer(), activation_fn=tf.nn.relu, model_dir = 'models/', config=run_config ) # Train the model classifier.train( input_fn=lambda:input_function(X_train, y_train, True) ) # Evaluate the model eval_result = classifier.evaluate( input_fn=lambda:input_function(X_test, y_test, False) ) print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result)) if __name__ == "__main__": os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' tf.app.run(main) I believe the model will be trained num_epoch times as num_epoch affect dataset's repeat(). I didn't define steps in estimator so it will be trained forever until input_fn generates the tf.errors.OutOfRange. But if I change num_epoch value it always gives the same result. For example, when I run this program with num_epoch=4 and num_epoch=400 the test set accuracy will be the same. Am I misunderstanding the training process here? or it's just a coincidence? I hope someone can help explain why this happene…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92365184
has title: Tensorflow estimator: Different epoch number gives the same result
has comment: http://stackoverflow.com/comment/92358107
has comment: http://stackoverflow.com/comment/92358297
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92370436
tagged with: tensorflow-estimator
has answer: http://stackoverflow.com/a/52716323
score: 0
answer count: 1

http://stackoverflow.com/comment/92169222
type: QuestionComment
comment on: http://stackoverflow.com/q/52617318
has text: And what comes out the other end when you run that code, and how does that compare to what you expect? Not trying to be mean, genuinely curious about what your code is doing. Do you mean to assign `img[i][j]` to `img[j][i]` in your loop?
score: 1
type: Comment

http://stackoverflow.com/q/52665950
has comment: http://stackoverflow.com/comment/92261584
favorite count: 0
has comment: http://stackoverflow.com/comment/92262710
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53607637
possible better answer: http://stackoverflow.com/a/52667531
score: 1
has title: How to copy virtualenv to another machine which doesn't have the same interpreter?
has answer: http://stackoverflow.com/a/52667531
upvote count: 1
has comment: http://stackoverflow.com/comment/94075835
type: Question
answer count: 2
has body: I have a virtualenv on my local machine and I would like to copy this virtualenv to a production machine which is the same platform but it does not have python3 and I cannot install it. Is it possible to copy the virtualenv and python3 interpreter to the production machine which doesn't have the same python version? I have tried relocatable for virtualenv and pip freezes. I copied the venv and changed active paths but it didn't help, it cannot run pip or python commands because it cannot find the interpreter.
accepted answer: http://stackoverflow.com/a/53607637
has comment: http://stackoverflow.com/comment/92261609
downvote count: 0
has comment: http://stackoverflow.com/comment/92262611
tagged with: virtualenv

http://stackoverflow.com/a/71731564
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52642976
downvote count: 0
has body: One option is with pivot_wider from pyjanitor, using the names_glue parameter to reshape the column names: # pip install pyjanitor import pandas as pd import janitor df.pivot_wider( index = 'foo', names_from = 'bar', values_from = ['baz', 'zoo'], names_glue = &quot;{bar}_{_value}&quot;) foo A_baz B_baz C_baz A_zoo B_zoo C_zoo 0 one 1 2 3 x y z 1 two 4 5 6 q w t in the names_glue string template, _value serves as a placeholder for values from values_from. Anything in the {} brackets should either be from names_from or _value to represent values_from.

http://stackoverflow.com/q/52728460
favorite count: 0
has comment: http://stackoverflow.com/comment/92383312
tagged with: modbus
accepted answer: http://stackoverflow.com/a/52729490
upvote count: 1
tagged with: pymodbus
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92382251
has title: pySerial Capturing a long response
score: 1
has comment: http://stackoverflow.com/comment/92382311
has body: Hi guys I'm working a on script that will get data from a host using the Data Communications Standard (Developed by: Data Communication Standard Committee Lens Processing Division of The Vision Council), by serial port and pass the data into ModBus Protocol for the device to perform it's operations. Since I don't fiscally have access to the host machine I'm trying to develop a secondary script to emulate the host. I am currently on the stage where I need to read a lot of information from the serial port and I get only part of the data. I was hoping to get the whole string sent on the send_job() function on my host emulator script. Guys also can any of you tell me if this would be a good approach? the only thing the machine is supposed to do is grab 2 values from the host response and assign them to two modbus holding registers. NOTE: the initialization function is hard coded because it will always be the same and the actual response data will not matter except for status. Also the job request is hard coded i only pass the job # that i get from a modbus holding register, the exact logic on how the host resolved this should not matter i only need to send the job number scanned from the device in this format. main script: def request_job_modbus(job): data = F'[06][1c]req=33[0d][0a]job={job}[0d][0a][1e][1d]'.encode('ascii') writer(data) def get_job_from_serial(): response = serial_client.read_all() resp = response.decode() return resp # TODO : SEND INIT SEQUENCE ONCE AND VERIFY IF REQUEST status=0 initiation_request() init_response_status = get_init_status() print('init method being active') print(get_init_status()) while True: # TODO: get job request data job_serial = get_job_from_serial() print(job_serial) host emulation script: def send_job(): job_response = '''[06][1c]ans=33[0d]job=30925[0d]status=0;"ok"[0d]do=l[0d]add=;2.50[0d]ar=1[0d] bcerin=;3.93[0d]bcerup=;-2.97[0d]crib=;64.00[0d]do=l[0d]ellh=;64.00[0d]engmask=;613l[0d] erdrin=;0.00[0d]erdrup=;10.00[0d]ernrin=;2…
has comment: http://stackoverflow.com/comment/92382526
type: Question
tagged with: pyserial
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92383651
has answer: http://stackoverflow.com/a/52729490
tagged with: python

http://stackoverflow.com/a/52675722
type: Answer
has body: Remove div from fields group and class="o_address_street" from your fields. This may give you expected result.
answers question: http://stackoverflow.com/q/52668609
score: 0

http://stackoverflow.com/q/52599298
tagged with: python-tesseract
has comment: http://stackoverflow.com/comment/92147960
answer count: 0
type: UnansweredQuestion
tagged with: tesseract
has body: We are trying to perform ocr on image with 2 characters and tesseract command returns incorrect output. Clearly expected result should be TV but we are getting AY. Result should have been S7 Ep7, but we are getting [Sa aes]. Which as you can see is not even close. Tesseract processed images look quite clear and it should be working on them but getting such inconsistent results on clear images is confusing. Any ideas on how we can achieve better result. For a similar image we start getting correct result. Example. Correct result image As you can see these are similar images with just few pixels up and down. But they give totally different results.
has comment: http://stackoverflow.com/comment/92193403
type: Question
tagged with: text-processing
score: 0
has title: Tesseract 4.0 OCR results inconsistent
tagged with: python
tagged with: ocr

http://stackoverflow.com/comment/92251840
type: AnswerComment
comment on: http://stackoverflow.com/a/52660430
type: Comment
has text: glad to help you bro, you can also give a thumbs up to the answer
score: 1

http://stackoverflow.com/comment/92293964
type: AnswerComment
type: Comment
has text: just to loop over the cursor instance,thanks
comment on: http://stackoverflow.com/a/52682407
score: 0

selenium-webdriver
tags question: http://stackoverflow.com/q/52712046
tags question: http://stackoverflow.com/q/52663054
tags question: http://stackoverflow.com/q/52668844
tags question: http://stackoverflow.com/q/52714921
tags question: http://stackoverflow.com/q/52663724
tags question: http://stackoverflow.com/q/52730340
tags question: http://stackoverflow.com/q/52598793
tags question: http://stackoverflow.com/q/52600364
tags question: http://stackoverflow.com/q/52623555
tags question: http://stackoverflow.com/q/52726784
tags question: http://stackoverflow.com/q/52699217
tags question: http://stackoverflow.com/q/52686968
tags question: http://stackoverflow.com/q/52588759
tags question: http://stackoverflow.com/q/52688693
tags question: http://stackoverflow.com/q/52693693
tags question: http://stackoverflow.com/q/52662818
tags question: http://stackoverflow.com/q/52679582
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/52618687
tags question: http://stackoverflow.com/q/52614592
tags question: http://stackoverflow.com/q/52675708
tags question: http://stackoverflow.com/q/52735631
tags question: http://stackoverflow.com/q/52626163
tags question: http://stackoverflow.com/q/52683416
tags question: http://stackoverflow.com/q/52667008
tags question: http://stackoverflow.com/q/52723591
tags question: http://stackoverflow.com/q/52604717
tags question: http://stackoverflow.com/q/52684555
tags question: http://stackoverflow.com/q/52668208
tags question: http://stackoverflow.com/q/52659115
tags question: http://stackoverflow.com/q/52680025
tags question: http://stackoverflow.com/q/52691203
type: Tag
tags question: http://stackoverflow.com/q/52669404
tags question: http://stackoverflow.com/q/52600350
tags question: http://stackoverflow.com/q/52603847
tags question: http://stackoverflow.com/q/52675659
tags question: http://stackoverflow.com/q/52636826

http://stackoverflow.com/a/52730944
type: Answer
score: 2
upvote count: 2
has body: You could do something along the line of this: &gt;&gt;&gt; dictionary = {'aaaa': [1,2,2,3], 'aa': [1,2,2,3], 'aaa': [2,2,2,2], 'a': [4,2,2,6]} &gt;&gt;&gt; arr = sorted(dictionary.items(), key=lambda x: (-x[1][3],-len(x[0]))) &gt;&gt;&gt; for k in arr: print(k) ('a', [4, 2, 2, 6]) ('aaaa', [1, 2, 2, 3]) ('aa', [1, 2, 2, 3]) ('aaa', [2, 2, 2, 2]) Note: sort by larger d first, then longer key first. To reverse the ordering, of any priorities, simply experimenting with removing/leaving - in the elements in the tupple in the lambda function.
has comment: http://stackoverflow.com/comment/92386960
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92387002
accepted answer of: http://stackoverflow.com/q/52730850
answers question: http://stackoverflow.com/q/52730850

http://stackoverflow.com/comment/92386477
type: Comment
type: QuestionComment
score: 0
has text: I dint notice there was an extra . in Adj Close column! Thanks for pointing it out. You can post your comment as an answer, I will accept it.
comment on: http://stackoverflow.com/q/52730526

http://stackoverflow.com/comment/92350008
score: 1
comment on: http://stackoverflow.com/a/52711966
type: AnswerComment
has text: Note that this will not remove underscores.
type: Comment

http://stackoverflow.com/q/52614786
upvote count: 3
has body: I want to implement a convolutional layer, with a different convolutional filter for each output location. Specifically, think of the case when the output is of 16*16*128 (W * H * C). Instead of having a 3*3*128 filter we have 16*16 filters; each with size 3*3*128. This would lead to huge amount of parameters, but it can the case be that each of the 3*3*128 filter may be the same except scaled by a different constant, and the constants can be learned through a side network. In this way the number of parameters won't be too much. The similar idea is briefly in Dynamic Filter Networks, but I cannot find an implementation of location specific filters. My question is, if we want a location specific convolutional filter how do I implement it in Tensorflow or Pytorch? Do I need to write my own operation or there is some smart way to use the functions provided? If I have to write an OP is there any trick that can easily achieve this idea? Any help is appreciated!
tagged with: tensorflow
type: Question
answer count: 2
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/66357164
favorite count: 0
has answer: http://stackoverflow.com/a/52623576
has title: How to implement a location specific convolutional filters in Tensorflow or Pytorch?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92164692
score: 3
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/92165000
tagged with: pytorch

dictionary
tags question: http://stackoverflow.com/q/52638926
tags question: http://stackoverflow.com/q/52632981
tags question: http://stackoverflow.com/q/52730200
tags question: http://stackoverflow.com/q/52661341
tags question: http://stackoverflow.com/q/52742767
tags question: http://stackoverflow.com/q/52671986
tags question: http://stackoverflow.com/q/52630158
tags question: http://stackoverflow.com/q/52659659
tags question: http://stackoverflow.com/q/52628596
tags question: http://stackoverflow.com/q/52661127
tags question: http://stackoverflow.com/q/52626430
tags question: http://stackoverflow.com/q/52720282
tags question: http://stackoverflow.com/q/52646004
tags question: http://stackoverflow.com/q/52689640
tags question: http://stackoverflow.com/q/52629221
tags question: http://stackoverflow.com/q/52659905
tags question: http://stackoverflow.com/q/52679355
tags question: http://stackoverflow.com/q/52692537
tags question: http://stackoverflow.com/q/52704241
tags question: http://stackoverflow.com/q/52658157
tags question: http://stackoverflow.com/q/52642538
tags question: http://stackoverflow.com/q/52709166
tags question: http://stackoverflow.com/q/52705870
tags question: http://stackoverflow.com/q/52703906
tags question: http://stackoverflow.com/q/52659023
tags question: http://stackoverflow.com/q/52689108
tags question: http://stackoverflow.com/q/52647395
tags question: http://stackoverflow.com/q/52735775
tags question: http://stackoverflow.com/q/52610357
tags question: http://stackoverflow.com/q/52668645
tags question: http://stackoverflow.com/q/52600888
tags question: http://stackoverflow.com/q/52724044
tags question: http://stackoverflow.com/q/52658795
tags question: http://stackoverflow.com/q/52711297
tags question: http://stackoverflow.com/q/52682678
tags question: http://stackoverflow.com/q/52637488
tags question: http://stackoverflow.com/q/52743305
tags question: http://stackoverflow.com/q/52591763
tags question: http://stackoverflow.com/q/52619030
tags question: http://stackoverflow.com/q/52601526
tags question: http://stackoverflow.com/q/52658116
tags question: http://stackoverflow.com/q/52618355
tags question: http://stackoverflow.com/q/52724557
tags question: http://stackoverflow.com/q/52678387
tags question: http://stackoverflow.com/q/52671422
tags question: http://stackoverflow.com/q/52663119
tag name: dictionary
tags question: http://stackoverflow.com/q/52665847
tags question: http://stackoverflow.com/q/52629063
tags question: http://stackoverflow.com/q/52690078
tags question: http://stackoverflow.com/q/52742125
tags question: http://stackoverflow.com/q/52646124
tags question: http://stackoverflow.com/q/52686767
tags question: http://stackoverflow.com/q/52735848
tags question: http://stackoverflow.com/q/52615888
tags question: http://stackoverflow.com/q/52650583
tags question: http://stackoverflow.com/q/52592140
tags question: http://stackoverflow.com/q/52636092
tags question: http://stackoverflow.com/q/52692866
tags question: http://stackoverflow.com/q/52656701
tags question: http://stackoverflow.com/q/52613540
tags question: http://stackoverflow.com/q/52691905
tags question: http://stackoverflow.com/q/52735995
tags question: http://stackoverflow.com/q/52616351
tags question: http://stackoverflow.com/q/52596921
tags question: http://stackoverflow.com/q/52672166
tags question: http://stackoverflow.com/q/52670591
tags question: http://stackoverflow.com/q/52643037
tags question: http://stackoverflow.com/q/52619942
tags question: http://stackoverflow.com/q/52724172
tags question: http://stackoverflow.com/q/52612435
tags question: http://stackoverflow.com/q/52649867
tags question: http://stackoverflow.com/q/52593764
tags question: http://stackoverflow.com/q/52704962
tags question: http://stackoverflow.com/q/52698363
tags question: http://stackoverflow.com/q/52634520
tags question: http://stackoverflow.com/q/52709390
tags question: http://stackoverflow.com/q/52644466
tags question: http://stackoverflow.com/q/52618197
tags question: http://stackoverflow.com/q/52631660

http://stackoverflow.com/comment/92245771
type: Comment
has text: I see what you mean and added some explanation to the answer. Hope that helps.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52656386

http://stackoverflow.com/q/52653483
tagged with: nested-lists
tagged with: python
accepted answer: http://stackoverflow.com/a/52653491
has title: Python prints memory addresses of nested lists rather than list contents
type: AnsweredQuestion
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52653491
tagged with: python-3.x
has body: This code, which I expect to print something along the lines of [[7, 4, 1], [8, 5, 2], [9, 6, 3]], instead prints this: [&lt;map object at 0x7f8c1f578e10&gt;, &lt;map object at 0x7f8c1f578ef0&gt;, &lt;map object at 0x7f8c1f578fd0&gt;] #!/usr/bin/env python3 def transpose(matrix): results = [None] * len(matrix) for subIndex in range(len(matrix)): results[subIndex] = map((lambda sub : sub[subIndex]), matrix) return results def rotateClockwise(matrix2): reversedmatrix = list(reversed(matrix2)) rotated = transpose(reversedmatrix) return rotated def main(): m = [[1,2,3],[4,5,6],[7,8,9]] output = rotateClockwise(m) return output if __name__ == "__main__": x = main() print(x) Why is this? How can I fix it?

http://stackoverflow.com/comment/92230482
has text: you are right, thought it wouldn't make much more difference. im quite new to python, my bad.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52632981

http://stackoverflow.com/q/52661209
has comment: http://stackoverflow.com/comment/92253055
tagged with: opencv
upvote count: 3
has answer: http://stackoverflow.com/a/52662491
downvote count: 1
has body: I'm trying to make web app using OpenCV, Flask, Face Recognition hosted on Heroku. On localhost, everything is working how it suppose to but on Heroku, I can't open client camera. I know I need javascript or WebSocket to achieve this. All that I could found with javascript is how to stream from the camera on the browser which is not good for me because I need to open the OpenCV frame for the face detection and recognition. Also, I was looking for WebSocket and flask-socket but they only send messages, not video. Here is my code: app.py '''Face Detection Login App ''' import random, string import face_recognition import cv2 import glob from flask import Flask, render_template, redirect, url_for app = Flask(__name__) @app.route('/') def index(): render_template('home.html') @app.route('/article') def article(): return render_template('article.html') @app.route('/registered') def registered(): return render_template('registered.html') @app.route('/reject') def reject(): return render_template('reject.html') @app.route('/login', methods=["GET", "POST"]) def login(): page_name = 'reject' video_capture = cv2.VideoCapture(0) # Load faces faces = 'faces/*.jpg*' face = glob.glob(faces) for fn in face: try_image = face_recognition.load_image_file(f'{fn}') print(f'{fn}') try_face_encoding = face_recognition.face_encodings(try_image) if not try_face_encoding: print("No face found on the image") return redirect(url_for(page_name)) try_face_encoding = try_face_encoding[0] # Array of faces known_face_encodings = [ try_face_encoding, ] face_locations = [] face_encodings = [] process_this_frame = True ret, frame = video_capture.read() # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:, :, ::-1] if process_this_frame: face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings( rgb_small_frame, face_locations) for fac…
tagged with: flask
linked to: http://stackoverflow.com/q/28285909
score: 2
has comment: http://stackoverflow.com/comment/92252694
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52662491
duplicate of: http://stackoverflow.com/q/28285909
favorite count: 0
type: Question
tagged with: python
has title: How to open camera on client side with OpenCV, Face Recognition, Flask, Python 3 and Heroku
answer count: 1

http://stackoverflow.com/q/52721139
has comment: http://stackoverflow.com/comment/92430968
favorite count: 0
type: Question
tagged with: python
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/92368295
has body: I am trying to get my images from the folder to an array and processing them one by one. But I want to do it in parallel. I tried to implement each image in a different process and execute but this does not seem to work my code: import numpy as np import os import cv2 from multiprocessing import Process import time file_path=[] path="C:/Users/User/Desktop/Dataset_Screens/picture_dataset_Small/" for root,dir,files in os.walk(path): for f in files: file_path.append(os.path.join(root,f)) path1="C:/Users/User/Desktop/Dataset_Screens/picture_dataset_Big/" for root1,dir1,files1 in os.walk(path1): for f1 in files: file_path.append(os.path.join(root1,f1)) print(len(file_path)) def get_image(inputfilepath): img_original= cv2.imread(inputfilepath) img_array=np.asarray(img_original) blur= cv2.pyrMeanShiftFiltering(img_original,21,49) gray_image= cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) ret,thresh= cv2.threshold(gray_image,70,255,cv2.THRESH_BINARY) _, contours,hierarchy =cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) countourimage=cv2.drawContours(img_original,contours,-1,0,3) largest_area=0 print('I am inside the loop') for i,c in enumerate(contours): contour_areas=cv2.contourArea(c) if(contour_areas&gt;largest_area): largest_area= contour_areas x_rect,y_rect,w_rect,h_rect=cv2.boundingRect(c) cropped=img_original[y_rect:y_rect+h_rect,x_rect:x_rect+w_rect] cv2.imwrite('C:/Users/User/Anaconda3/contourimage.jpg',cropped) t= time.time() if __name__ == '__main__': for i in range(4): p = Process(target=get_image, args=(file_path[i],)) p.start() print('Done in ', time.time()-t) print('We are DONEEEEEEE!!!!!!') I am using Spyder which does not seem to work either, so i ran on conda prompt and the outputs are shown below: The output in spyder: 132 Done in 0.022994279861450195 DONEEE!! The output in conda prompt: C:\Users\User\Anaconda3&gt;python examples.py 132 Done in 0.05248904228210449 DONEEE!! 132 Done in 0.0 DONEEE!! 132 Done in 0.0 DONEEE!! 132 Done in 0.0 DONEEE!…
upvote count: 2
has comment: http://stackoverflow.com/comment/92372978
tagged with: multithreading
linked to: http://stackoverflow.com/q/30237613
has title: Multiprocessing does not call the functions
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/92418160
type: UnansweredQuestion
tagged with: image
score: 2
answer count: 0
downvote count: 0

http://stackoverflow.com/q/52667854
type: AnsweredQuestion
has title: dependency issue when using pipenv
score: 1
accepted answer: http://stackoverflow.com/a/52672910
favorite count: 0
type: Question
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/92267054
has body: I'm a Python newbie and having a bit of trouble understanding dependencies, hoping someone can help. I'm using pipenv to set up a dev environment. Here is my pipenv file source url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] [dev-packages] pytest = "*" apache-airflow = "*" [requires] python_version = "2.7" When I issue pipenv install --dev this happens: $ pipenv install --dev Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Could not find a version that matches Flask-Login&lt;0.5,==0.2.11,>=0.3 Tried: 0.1.1, 0.1.2, 0.1.3, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.2.6, 0.2.7, 0.2.8, 0.2.9, 0.2.10, 0.2.11, 0.3.0, 0.3.1, 0.3.2, 0.4.0, 0.4.0, 0.4.1 I did what it suggested: pipenv install --dev --skip-lock which completed successfully: $ pipenv install --dev --skip-lock Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. Installing dependencies from Pipfile… ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 2/2 — 00:00:02 then pipenv graph | grep Flask-Login $ pipenv graph | grep Flask-Login - Flask-Login [required: &lt;0.5,>=0.3, installed: 0.2.11] At this point I'm a bit confused. I don't know why it might have installed Flask-Login 0.2.11 given there's (seemingly) nothing else in the dependency graph that requires Flask-Login. I'm confused. Help!
has answer: http://stackoverflow.com/a/52672910
tagged with: pipenv
downvote count: 0
has comment: http://stackoverflow.com/comment/92267185

http://stackoverflow.com/q/52598090
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52598295
downvote count: 0
linked to: http://stackoverflow.com/q/5036700
favorite count: 0
linked to: http://stackoverflow.com/q/52456063
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92130881
tagged with: python
has answer: http://stackoverflow.com/a/52598200
has comment: http://stackoverflow.com/comment/92206474
score: 2
upvote count: 2
has body: I want to create a for_loop that doesn't overwrite the exiting dataframe? for df in 2011, 2012, 2013: df = pd.pivot_table(df, index=["income"], columns=["area"], values=["id"], aggfunc='count') Right now the for loop above iterates over each of the existing dataframes. How can I make it so the for loop creates a bunch of new dataframes? 2011_pivot, 2012_pivot, 2013_pivot
type: Question
has answer: http://stackoverflow.com/a/52598166
linked to: http://stackoverflow.com/q/52502779
has title: How can I create a multiple new dataframes inside a for loop?
has comment: http://stackoverflow.com/comment/92130986
has comment: http://stackoverflow.com/comment/92131503

http://stackoverflow.com/comment/92289446
has text: I think of each column as a measurement where the rows are a time step ( e.g. a day ) and the columns are series like number of page views, amount spent on a type of product, number of clicks on links etc, In this case, the sample / observation ( axis 0) might be a customer. What is the other type you are imagining.
type: Comment
comment on: http://stackoverflow.com/q/52679712
type: QuestionComment
score: 0

http://stackoverflow.com/q/52606176
has comment: http://stackoverflow.com/comment/92146433
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52606227
accepted answer: http://stackoverflow.com/a/52606229
has comment: http://stackoverflow.com/comment/92146487
has comment: http://stackoverflow.com/comment/92148576
has title: How to find dictionaries in one list but not in another
has body: Say we have 2 lists of dictionaries L1 and L2. I want to have a list of dictionaries that are in L2 but not in L1. In my case, I have L1 is a subset of L2 so im not sure if that fact can be used to make any optimizations.
tagged with: python
tagged with: python-3.x
score: 0
tagged with: dictionary
has answer: http://stackoverflow.com/a/52606229
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/52606227

pytest
tags question: http://stackoverflow.com/q/52729749
tags question: http://stackoverflow.com/q/52626799
tags question: http://stackoverflow.com/q/52710854
tag name: pytest
tags question: http://stackoverflow.com/q/52692108
tags question: http://stackoverflow.com/q/52589912
tags question: http://stackoverflow.com/q/52636409
tags question: http://stackoverflow.com/q/52641521
tags question: http://stackoverflow.com/q/52678193
tags question: http://stackoverflow.com/q/52634113
tags question: http://stackoverflow.com/q/52713154
tags question: http://stackoverflow.com/q/52623555
tags question: http://stackoverflow.com/q/52605689
tags question: http://stackoverflow.com/q/52695727
tags question: http://stackoverflow.com/q/52615119
tags question: http://stackoverflow.com/q/52619099
tags question: http://stackoverflow.com/q/52702526
tags question: http://stackoverflow.com/q/52681322
tags question: http://stackoverflow.com/q/52645197
tags question: http://stackoverflow.com/q/52729792
type: Tag

http://stackoverflow.com/comment/92227906
has text: B 0 7 1 8 2 4 3 5 4 5 5 -4 So we can bin to 3 categories (4,5), (6,7), (8,9), leaving us with: B 0 2 1 3 2 1 3 1 4 1 5 -4
comment on: http://stackoverflow.com/q/52647454
score: 0
type: QuestionComment
type: Comment

visual-studio-code
tags question: http://stackoverflow.com/q/52680244
tags question: http://stackoverflow.com/q/52686426
tags question: http://stackoverflow.com/q/52674581
tags question: http://stackoverflow.com/q/52689629
tags question: http://stackoverflow.com/q/52729102
tags question: http://stackoverflow.com/q/52743265
tags question: http://stackoverflow.com/q/52730430
tags question: http://stackoverflow.com/q/52665718
tags question: http://stackoverflow.com/q/52615414
tags question: http://stackoverflow.com/q/52716788
tag name: visual-studio-code
type: Tag
tags question: http://stackoverflow.com/q/52607196
tags question: http://stackoverflow.com/q/52601198
tags question: http://stackoverflow.com/q/52612599
tags question: http://stackoverflow.com/q/52709268
tags question: http://stackoverflow.com/q/52726807

http://stackoverflow.com/comment/92255940
score: 0
type: QuestionComment
type: Comment
has text: the last sentence in the question: _I need to consume the variables stored in this Secret from a DAG in Airflow.(python)._
comment on: http://stackoverflow.com/q/52662514

http://stackoverflow.com/comment/92278751
type: Comment
comment on: http://stackoverflow.com/a/52674506
type: AnswerComment
has text: It sounds like you are reading some kind of input from a file or the command line for your email and name variables. Could you post the code you are using to do that
score: 0

list
tags question: http://stackoverflow.com/q/52657192
tags question: http://stackoverflow.com/q/52601778
tags question: http://stackoverflow.com/q/52599722
type: Tag
tags question: http://stackoverflow.com/q/52737997
tags question: http://stackoverflow.com/q/52625233
tags question: http://stackoverflow.com/q/52606753
tags question: http://stackoverflow.com/q/52692643
tags question: http://stackoverflow.com/q/52718330
tags question: http://stackoverflow.com/q/52738170
tags question: http://stackoverflow.com/q/52637131
tags question: http://stackoverflow.com/q/52736034
tags question: http://stackoverflow.com/q/52662184
tags question: http://stackoverflow.com/q/52649867
tags question: http://stackoverflow.com/q/52690406
tags question: http://stackoverflow.com/q/52640425
tags question: http://stackoverflow.com/q/52689841
tags question: http://stackoverflow.com/q/52667926
tags question: http://stackoverflow.com/q/52711122
tags question: http://stackoverflow.com/q/52595944
tags question: http://stackoverflow.com/q/52718264
tags question: http://stackoverflow.com/q/52709667
tags question: http://stackoverflow.com/q/52671807
tags question: http://stackoverflow.com/q/52697670
tags question: http://stackoverflow.com/q/52678242
tags question: http://stackoverflow.com/q/52735310
tags question: http://stackoverflow.com/q/52656253
tags question: http://stackoverflow.com/q/52636401
tags question: http://stackoverflow.com/q/52681396
tags question: http://stackoverflow.com/q/52730494
tags question: http://stackoverflow.com/q/52613936
tags question: http://stackoverflow.com/q/52613142
tags question: http://stackoverflow.com/q/52657785
tags question: http://stackoverflow.com/q/52680619
tags question: http://stackoverflow.com/q/52614223
tags question: http://stackoverflow.com/q/52703442
tags question: http://stackoverflow.com/q/52742114
tags question: http://stackoverflow.com/q/52742767
tags question: http://stackoverflow.com/q/52693307
tags question: http://stackoverflow.com/q/52688864
tags question: http://stackoverflow.com/q/52743888
tags question: http://stackoverflow.com/q/52607438
tags question: http://stackoverflow.com/q/52620995
tags question: http://stackoverflow.com/q/52716336
tags question: http://stackoverflow.com/q/52706853
tags question: http://stackoverflow.com/q/52626430
tags question: http://stackoverflow.com/q/52642712
tags question: http://stackoverflow.com/q/52731355
tags question: http://stackoverflow.com/q/52664315
tags question: http://stackoverflow.com/q/52604781
tags question: http://stackoverflow.com/q/52705809
tags question: http://stackoverflow.com/q/52589462
tags question: http://stackoverflow.com/q/52695227
tags question: http://stackoverflow.com/q/52675402
tags question: http://stackoverflow.com/q/52603251
tags question: http://stackoverflow.com/q/52744147
tags question: http://stackoverflow.com/q/52719305
tags question: http://stackoverflow.com/q/52706958
tags question: http://stackoverflow.com/q/52703902
tags question: http://stackoverflow.com/q/52733105
tags question: http://stackoverflow.com/q/52653278
tags question: http://stackoverflow.com/q/52703848
tag name: list
tags question: http://stackoverflow.com/q/52606176
tags question: http://stackoverflow.com/q/52648166
tags question: http://stackoverflow.com/q/52673780
tags question: http://stackoverflow.com/q/52657899
tags question: http://stackoverflow.com/q/52628068
tags question: http://stackoverflow.com/q/52723721
tags question: http://stackoverflow.com/q/52674598
tags question: http://stackoverflow.com/q/52617096
tags question: http://stackoverflow.com/q/52638157
tags question: http://stackoverflow.com/q/52723597
tags question: http://stackoverflow.com/q/52698078
tags question: http://stackoverflow.com/q/52629265
tags question: http://stackoverflow.com/q/52612318
tags question: http://stackoverflow.com/q/52597760
tags question: http://stackoverflow.com/q/52631029
tags question: http://stackoverflow.com/q/52601350
tags question: http://stackoverflow.com/q/52659659

librosa
tags question: http://stackoverflow.com/q/52661392
tag name: librosa
tags question: http://stackoverflow.com/q/52653371
type: Tag

http://stackoverflow.com/a/52714635
has comment: http://stackoverflow.com/comment/92355951
type: Answer
downvote count: 0
has body: I solved the issue. The problem was in the way my positive images were named. As indicated in this post http://answers.opencv.org/question/186072/bad-argument-in-function-cvreleasedata-how-to-fix-the-error/ I had to rename my positive images.
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52714189
accepted answer of: http://stackoverflow.com/q/52714189

http://stackoverflow.com/comment/92204753
type: Comment
has text: Hello, to help others understand your answer, consider including a short description of your code and how it solves the posted question.
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/52633853

http://stackoverflow.com/comment/92138287
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52601988
has text: I tried it on mac osx terminal and iterm. I could not reproduce your failure. I tried clicking, selecting text, and hammering on the keyboard.
score: 0

http://stackoverflow.com/a/52667957
accepted answer of: http://stackoverflow.com/q/52643184
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52643184
downvote count: 0
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92303398
has body: Matrix connections in your feedforward function are wrong #simple feed forward def feedforward(self): self.layer1 = sigmoid(np.dot(self.input, self.weights1) + self.bias1) self.layer2 = sigmoid(np.dot(self.layer1, self.weights2) + self.bias2) self.layer3 = sigmoid(np.dot(self.layer1, self.weights3) + self.bias3) self.output = sigmoid(np.dot(self.layer2, self.weights4) + self.bias4) must be #simple feed forward def feedforward(self): self.layer1 = sigmoid(np.dot(self.input, self.weights1) + self.bias1) self.layer2 = sigmoid(np.dot(self.layer1, self.weights2) + self.bias2) self.layer3 = sigmoid(np.dot(self.layer2, self.weights3) + self.bias3) self.output = sigmoid(np.dot(self.layer3, self.weights4) + self.bias4) I tried your code this way and it seems to work for me Here is how the prediction looks like By the way, not that it makes a big difference but theoretically, you should use a binary cross entropy cost function rather than MSE because your problem here is logistic regression. MSE may make it non-convex that would otherwise be convex.

http://stackoverflow.com/a/52629898
has comment: http://stackoverflow.com/comment/92194553
type: Answer
upvote count: 1
has body: # Split the sentence into Series df1 = pd.DataFrame(df.sentence.str.split(' ').tolist()) # Add category with as not been adding with the split df1['category'] = df['category'] # Melt the Series corresponding to the splited sentence df1 = pd.melt(df1, id_vars='category', value_vars=df1.columns[:-1].tolist()) # Groupby and count (reset_index will create a column nammed 0) df1 = df1.groupby(['category', 'value']).size().reset_index() # Keep the 10 largests numbers df1 = df1.nlargest(10, 0)
score: 1
answers question: http://stackoverflow.com/q/52629455
downvote count: 0

http://stackoverflow.com/q/52655924
favorite count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92251054
type: UnansweredQuestion
has body: I'm new to Python and I'm programming a simple psychology experiment. In a nutshell, I'm presenting participants with a series of randomized images and having them to press one key if they detect a face in a given image. One of my problems is that the program crashes when participant presses the key too fast - that is, I've noticed that the program logs responses even if the participant is pressing a key when there is no image present. Each image will only be present on the screen for 10 seconds. Participant usually takes ~0.5 second on average to make a response. Is there a key for me to program the experiment so that that Psychopy will only log key presses ONCE, AFTER image is presented on screen? I've pasted my code below. Thanks so much. StimList=['Face1.png','Face2.png',] StimList.extend(['Noise1.png','Noise2.png']) # randomize lists: numpy.random.shuffle(StimList) outstr="" for TrialNo in range(len(StimList)): # load our image: img=visual.ImageStim( win=win, image=StimList[TrialNo], ) # draw the fixation cross and wait for trial start: win.flip() time.sleep(1) # wait 1 second on fixation cross # start a trial: loop until a key has been pressed (or trial times out) FaceDetected=0 # same as false Responded=0 #revise timer=core.Clock() timer.reset() while (not Responded) and (timer.getTime()&lt;TimeOut): #remove not responded img.draw()# outside loop win.flip() #outside loop keys=event.getKeys(keyList=['y','Y', 'n','N'], modifiers=False, timeStamped=timer) if keys: if (keys[0][0]=='y') | (keys[0][0]=='Y'): FaceDetected=True Responded=True RT=keys[0][1] elif (keys[0][0]=='n') | (keys[0][0]=='N'): FaceDetected=False Responded=True RT=keys[0][1] outstr=outstr+str(TrialNo)+", "+ StimList[TrialNo] +", "+str(FaceDetected)+", "+str(RT)+"\n" print(outstr) # first open the file: outfile=open('tmpdata.csv', 'w') outfile.write(outstr) outfile.close() win.close()
upvote count: 1
tagged with: python
has title: How to only log valid key presses in simple Psychopy experiment
has answer: http://stackoverflow.com/a/52660755
score: 1
type: Question
downvote count: 0
tagged with: psychopy

http://stackoverflow.com/q/52598527
answer count: 1
has title: Why Python not returning True after connecting ElasticSearch Server
type: AnsweredQuestion
tagged with: function
has answer: http://stackoverflow.com/a/52726041
has body: I have connected to Elastic Search(ES) with below code, but its not returning True. http://localhost:9200/ is giving proper output name "0jDPVkL" cluster_name "elasticsearch" cluster_uuid "9PfIve-HSP-v7kU__DbGmQ" version number "6.4.1" build_flavor "default" build_type "zip" build_hash "e36acdb" build_date "2018-09-13T22:18:07.696808Z" build_snapshot false lucene_version "7.4.0" minimum_wire_compatibility_version "5.6.0" minimum_index_compatibility_version "5.0.0" tagline "You Know, for Search" The Python Code import logging def connect_elasticsearch(): _es = None _es = Elasticsearch([{'host': 'localhost', 'port': 9200}]) if _es.ping(): print('Yay Connect') else: print('Awww it could not connect!') return _es if __name__ == '__main__': logging.basicConfig(level=logging.ERROR) I am trying to execute from the URL http://blog.adnansiddiqi.me/getting-started-with-elasticsearch-in-python/
type: Question
tagged with: elasticsearch
tagged with: python
has comment: http://stackoverflow.com/comment/92142003
has comment: http://stackoverflow.com/comment/92179940
score: 0
accepted answer: http://stackoverflow.com/a/52726041

http://stackoverflow.com/comment/92291718
score: 0
has text: @Tomalak Yeah it's my first time using Stack overflow and I kind of messed up the indentation but overall thank you for the advice!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52681426

http://stackoverflow.com/comment/92412212
comment on: http://stackoverflow.com/a/52738055
type: Comment
score: 1
has text: Thank you for this idea. But it needs some addition: at first `image = image[:,:,newaxis]` and after that `image = image.repeat(3,2)` so this worked. Just using repeat throws an error `AxisError: axis 2 is out of bounds for array of dimension 2` Thx again.
type: AnswerComment

http://stackoverflow.com/comment/92207802
comment on: http://stackoverflow.com/a/52637385
has text: You were right I inferred the question and wasn't explicit. Thank you for reading between the lines. I edited my original post. Thanks again for the help.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52639392
has body: The answer of @aneroid is good, but would be very slow if other_set is large. Using set is one of the most scalable choices. The order will be ignored. def union(self, other_set): return list(set(self.elements).union(other_set)) If you want to keep the order, making a set object would be faster for very large other_set. def union(self, other_set): new_set = [i for i in self.elements] # which is actually a list set_obj = set(new_set) for j in other_set: if j not in set_obj: new_set.append(j) return new_set
answers question: http://stackoverflow.com/q/52637362
score: 0
type: Answer

http://stackoverflow.com/comment/92463780
type: Comment
type: QuestionComment
has text: https://download.cnet.com/PDF-to-Text/3001-18497_4-75415960.html
comment on: http://stackoverflow.com/q/52730667
score: 0

http://stackoverflow.com/comment/92295318
type: QuestionComment
has text: @RogérioDec You'll need to explicitly parallelize your computation, and use processes (not threads) to use more than one core.
comment on: http://stackoverflow.com/q/52683554
score: 0
type: Comment

http://stackoverflow.com/q/52620304
has body: Hello Stack community, I used an if or statement while asking an input from the user, if the user inputs a value outside of my if or statement then I display a message saying "Please enter a valid number from 1 to 500", that brings up another input request to the user. So I have accomplished 2/3 of my goal. I have denied the original input, I have re-asked it, however I cannot find a way to retain only the new value after re-asking the user. Instead my program holds onto the original user input which was outside of the needed parameters, then it also holds onto the new input after being re-asked and combines them into one value. This is on Python IDLE 3.6. The exact question: How do you erase the original input value from the user input, and only retain the new value after being re-asked? Here is my code: def main(): resultsA = int(input("Please enter how many seats you sold is section A:")) if resultsA &lt; 1 or resultsA &gt; 300: int(input("Please enter a valid number from 1 to 300:")) resultsB = int(input("Please enter how many seats you sold is section B:")) if resultsB &lt; 1 or resultsB &gt; 500: int(input("Please enter a valid number from 1 to 500:")) resultsC = int(input("Please enter how many seats you sold is section C:")) if resultsC &lt; 1 or resultsC &gt; 200: int(input("Please enter a valid number from 1 to 200:")) finalResultA = 20*resultsA finalResultsB = 15*resultsB finalResultsC = 10*resultsC trulyFinal = finalResultA + finalResultsB + finalResultsC print ("Congratulations, here is your total revenue from tickets: $",trulyFinal) Here is a screen shot of what is happening in the shell:
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/52620346
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52620560
possible better answer: http://stackoverflow.com/a/52620346
upvote count: 3
has answer: http://stackoverflow.com/a/52620479
tagged with: python
type: AnsweredQuestion
score: 3
has title: How do you deny an input, re ask it, and ONLY retain that value
accepted answer: http://stackoverflow.com/a/52620560
type: Question
downvote count: 0

http://stackoverflow.com/comment/134798848
comment on: http://stackoverflow.com/a/69532572
type: AnswerComment
type: Comment
has text: From where did you imported `QSignal`?
score: 0

http://stackoverflow.com/a/57768002
score: 7
answers question: http://stackoverflow.com/q/52727937
upvote count: 7
type: Answer
has body: Note: $ from plotly.plotly import iplot will work only till plotly v3.10.0 The plotly.plotly module has been deprecated in plotly v4.0. Check your version first: $ python3 -c 'import plotly; print(plotly.__version__)' # for Python 3 $ python -c 'import plotly; print(plotly.__version__)' # for Python 2 v4.0 onwards, the functionality has been split into two modes: online and offline. Online If you wish to have the figures rendered online, you will now need to import chart-studio and use from chart_studio.plotly import plot, iplot Offline If you want to render the images locally, you have multiple options: from plotly.offline import iplot # your code iplot(fig) or from plotly.subplots import make_subplots fig = make_subplots(# your args) # your code fig.show() or import plotly.io as pio # your code pio.show(fig) or import plotly.graph_objects as go fig = go.Figure(# your args) # your code fig.show() You can read up more on the renderers here.
downvote count: 0

http://stackoverflow.com/q/52598901
has answer: http://stackoverflow.com/a/52599179
tagged with: string
has title: Split words in string into nested lists of characters
accepted answer: http://stackoverflow.com/a/52598929
favorite count: 0
possible better answer: http://stackoverflow.com/a/52598917
tagged with: python
has answer: http://stackoverflow.com/a/52598939
answer count: 4
type: AnsweredQuestion
tagged with: list
has body: Can anyone help me with a list comprehension to split a string into a nested list of words and characters? i.e: mystring = "this is a string" Wanted ouput: [['t','h','i','s'],['i','s'],['a'],['s','t','r','i','n','g']] I've tried the following, but it doesnt split 'x' into nested list: mylist = [x.split() for x in mystring.split(' ')] print(mylist) [['this'],['is'],['a'],['string']]
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92132526
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/52598929
linked to: http://stackoverflow.com/q/10610158
has answer: http://stackoverflow.com/a/52598917
downvote count: 0

http://stackoverflow.com/q/52644521
has body: Problem: I would like to get (7,5,3) =&gt; 000001110000010100000011 =&gt; 460035 also the converse, i.e., 460035 =&gt; 000001110000010100000011 =&gt; (7,5,3) Here is the the program I have tried: L=(7,5,3) # here L may vary each time. a=0 for i in range(3): a=bin(a &lt;&lt; 8) ^ bin(L[i]) print a But It gives error TypeError: unsupported operand type(s) for ^: 'str' and 'str' How can I do this?
has comment: http://stackoverflow.com/comment/92221278
type: AnsweredQuestion
has title: How to convert a tuple of bytes to an integer and back?
has comment: http://stackoverflow.com/comment/92221232
has answer: http://stackoverflow.com/a/52650723
has comment: http://stackoverflow.com/comment/92221657
has comment: http://stackoverflow.com/comment/92221563
type: Question
tagged with: decimal
answer count: 2
possible better answer: http://stackoverflow.com/a/52645153
downvote count: 0
has answer: http://stackoverflow.com/a/52645153
score: 1
tagged with: string
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/92221471
has comment: http://stackoverflow.com/comment/92221342
accepted answer: http://stackoverflow.com/a/52650723
has comment: http://stackoverflow.com/comment/92221560
tagged with: python
has comment: http://stackoverflow.com/comment/92221182
has comment: http://stackoverflow.com/comment/92221957
tagged with: binary
upvote count: 1

http://stackoverflow.com/comment/123362654
has text: Thanks for this interesting dive into the profiler. I think the solution is presented here: https://stackoverflow.com/questions/43328378/python-ldap-macos-valueerror-option-error
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52617381
type: Comment

http://stackoverflow.com/q/52589263
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92113310
tagged with: python
type: AnsweredQuestion
tagged with: yolo
has answer: http://stackoverflow.com/a/52589389
accepted answer: http://stackoverflow.com/a/52589389
type: Question
has body: I am trying to create a project on real time vehicle classification using yolo model. When I am trying to annotate the vehicle images this error pops up: Traceback (most recent call last): File "train.py", line 5, in &lt;module&gt; from generate_xml import write_xml ImportError: No module named 'generate_xml' Source which I've used to train can be found here.
score: -1
tagged with: importerror
has title: ImportError: No module named 'generate_xml'
downvote count: 2

http://stackoverflow.com/q/52720467
has comment: http://stackoverflow.com/comment/92366180
has title: Maximum between an array and a number
tagged with: python
has comment: http://stackoverflow.com/comment/92377842
has comment: http://stackoverflow.com/comment/92366696
has comment: http://stackoverflow.com/comment/92366268
type: AnsweredQuestion
has body: When using: import numpy as np A = np.array([1,2,-3,-1, 0,3,-1]) print [max(A[j], 0) for j in range(len(A))] we get [1, 2, 0, 0, 0, 3, 0], as desired. How to get the same directly with a numpy function, such as np.max? print max(A, 0) # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() print np.max(A, 0) # 3 print np.max(A, 0, axis=0) # argument axis not working print np.amax(A, 0) # 3
has comment: http://stackoverflow.com/comment/92366800
type: Question
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/92366085
has comment: http://stackoverflow.com/comment/92380855
score: 0
has comment: http://stackoverflow.com/comment/92366004
duplicate of: http://stackoverflow.com/q/46558114
has comment: http://stackoverflow.com/comment/92366357
has comment: http://stackoverflow.com/comment/92366953
tagged with: max
has answer: http://stackoverflow.com/a/52720550
accepted answer: http://stackoverflow.com/a/52720550
answer count: 1
has comment: http://stackoverflow.com/comment/92378288
has comment: http://stackoverflow.com/comment/92366393
linked to: http://stackoverflow.com/q/46558114

http://stackoverflow.com/comment/92242052
comment on: http://stackoverflow.com/q/52655162
score: 0
type: Comment
type: QuestionComment
has text: RDF is xml - using regexes to search XML is very fragile and generally a bad idea, and given it is so easy to use the ElementTree built in library you should bite the bullet and parse it properly - there are plenty of examples. Searching is much easier as the parsed content knows about the hierarchy, tags and attributes.

performance
tags question: http://stackoverflow.com/q/52731563
tags question: http://stackoverflow.com/q/52736681
tags question: http://stackoverflow.com/q/52693136
tags question: http://stackoverflow.com/q/52650583
tags question: http://stackoverflow.com/q/52686127
tags question: http://stackoverflow.com/q/52743342
tags question: http://stackoverflow.com/q/52733512
tags question: http://stackoverflow.com/q/52664433
tags question: http://stackoverflow.com/q/52691027
tags question: http://stackoverflow.com/q/52687833
tags question: http://stackoverflow.com/q/52703465
tags question: http://stackoverflow.com/q/52640065
tags question: http://stackoverflow.com/q/52693311
tags question: http://stackoverflow.com/q/52740724
tags question: http://stackoverflow.com/q/52649815
tags question: http://stackoverflow.com/q/52625864
tags question: http://stackoverflow.com/q/52693081
tags question: http://stackoverflow.com/q/52611557
tags question: http://stackoverflow.com/q/52664979
tags question: http://stackoverflow.com/q/52593518
tags question: http://stackoverflow.com/q/52636289
tags question: http://stackoverflow.com/q/52631291
tag name: performance
tags question: http://stackoverflow.com/q/52612874
tags question: http://stackoverflow.com/q/52631588
type: Tag
tags question: http://stackoverflow.com/q/52687039
tags question: http://stackoverflow.com/q/52673285
tags question: http://stackoverflow.com/q/52683554
tags question: http://stackoverflow.com/q/52675373

http://stackoverflow.com/q/52610357
has comment: http://stackoverflow.com/comment/92162823
has comment: http://stackoverflow.com/comment/92155069
upvote count: 1
has comment: http://stackoverflow.com/comment/92155115
has title: Dictionary mutability issue while adding new key and value to the dictionary in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92156870
has comment: http://stackoverflow.com/comment/92160190
has comment: http://stackoverflow.com/comment/92163224
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92156022
favorite count: 0
type: Question
has body: I'm trying to find the longest increasing subsequence from the python list i'm passing. The final dictionary structure should look something like this: Expected structure subsequence_dict={ 0:[15], 1:[15,27], 2:[14],3:[15,27,38],4:[14,26],5:[15,27,38,55],6:[15,27,38,46],7:[15, 27, 38, 55, 65, 85]} Output: {0: [15, 27, 38, 55, 65, 85], 1: [15, 27, 38, 55, 65, 85], 2: [14, 26, 46], 3: [15, 27, 38, 55, 65, 85], 4: [14, 26, 46], 5: [15, 27, 38, 55, 65, 85], 6: [14, 26, 46], 7: [15, 27, 38, 55, 65, 85], 8: [15, 27, 38, 55, 65, 85]} As looking at the key 0 in my output it looks there is some mutability issue. For every value of i in the main function there should be a new key in the dict which has value as list coming from longest_subsequence function. from copy import deepcopy def longest_subsequence(dict_elent,subsequence_dict): """ :param dict_elent: Dictionary element to which the longest list last element to be compared :param subsequence_dict: :return: List """ x=subsequence_dict.values() sorted_list = sorted(x, reverse=True) flag=False for sublist in sorted_list: if sublist[-1]&lt;dict_elent: sublist.append(dict_elent) flag=True break if flag==True: return sublist else: return [dict_elent] def main(d,subsequence_dict): for i in range(len(d)): if i==0 : subsequence_dict[i]=[d[i]] else: subsequence_dict.update({i: longest_subsequence(d[i],subsequence_dict)}) if __name__ == '__main__': d=[15,27,14,38,26,55,46,65,85] subsequence_dict={} main(d,subsequence_dict) print(subsequence_dict)
has comment: http://stackoverflow.com/comment/92155190
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/92174531

http://stackoverflow.com/q/52724641
has body: I want to find a better way to get my result. I use a regex pattern to match all text of the form (DD+ some text DDDD some other text) if and only if it is not preceded of non-fixed width lookbehind terms. How can I include these terms inside of my REGEX pattern ? aa = pd.DataFrame({"test": ["45 python 00222 sometext", "python white 45 regex 00 222 somewhere", "php noise 45 python 65000 sm", "otherword 45 python 50000 sm"]}) pattern = re.compile("(((\d+)\s?([^\W\d_]+)\s?)?(\d{2}\s?\d{3})\s?(\w.+))") aa["result"] = aa["test"].apply(lambda x: pattern.search(x)[0] if pattern.search(x) else None) lookbehind = ['python', 'php'] aa.apply(lambda x: "" if any(look in x["test"].replace(x["result"], "") for look in lookbehind) else x["result"], axis=1) The output is what I expected 0 45 python 00222 sometext 1 2 3 45 python 50000 sm
has comment: http://stackoverflow.com/comment/92374934
accepted answer: http://stackoverflow.com/a/52727818
favorite count: 0
has comment: http://stackoverflow.com/comment/92374799
upvote count: 2
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/92380628
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92374807
has title: Python Regex Negative Lookbehind Match without Fixed width
has comment: http://stackoverflow.com/comment/92374974
type: Question
has answer: http://stackoverflow.com/a/52727818
has answer: http://stackoverflow.com/a/52728406
has comment: http://stackoverflow.com/comment/92375078
answer count: 2
linked to: http://stackoverflow.com/q/24987403
downvote count: 0
possible better answer: http://stackoverflow.com/a/52728406
has comment: http://stackoverflow.com/comment/92375038
has comment: http://stackoverflow.com/comment/92375057

http://stackoverflow.com/q/52596008
tagged with: multithreading
has answer: http://stackoverflow.com/a/52600680
has comment: http://stackoverflow.com/comment/92130729
downvote count: 1
tagged with: parallel-processing
has title: Python: Combine Lists from different files in parallel or multithreaded
has body: This is my first question here. I started learning python a few days ago and i have a problem. I made some python files that each of them runs a for loop and appends the results to a list. So each file has its own list. For example file1.py produces list1, and file2.py produces list2 etc... My goal, is to combine all these lists together, so i am making a separate "main.py" file and import the list names and then combine them together like this: from file1 import list1 from file2 import list2 from file3 import list3 combined_lists = [*list1, *list2, *list3] and that is working fine as expected. But the problem is that this method is very slow, because it is importing the lists one by one in serial in the order i have them imported. For example, when i run it, it is importing first the list1 and when the list1 is completed it starts the list2 and then the list3 etc.. and finally combines them together. So, because i have 400 lists on 400 different files, this is taking a very long time. Is there any way to import and combine all the lists together in parallel? Like with multi-threading or any other method? Note, that i don't care about the order of the items in the combined list.
linked to: http://stackoverflow.com/q/33107019
linked to: http://stackoverflow.com/q/2068645
score: -1
has comment: http://stackoverflow.com/comment/92145394
type: Question
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92127262
tagged with: python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92146321
type: UnansweredQuestion

http://stackoverflow.com/q/52617206
accepted answer: http://stackoverflow.com/a/52618309
tagged with: python-unittest
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/92168691
has body: in the case of unit testing a wrapper library, testing the wrapper without depending/exercising the upstream library is a goal; In a known case, all calls to the upstream library can be mocked and that's what I've done, but I've been frustrated by changes to the wrapper that introduce more calls to the upstream library being missed by the mock tools; How can I best fail any test that tries to use a given namespace? My idea currently is to change all the unittest methods to have a monkey patch like @unittest.mock.patch('wrapper_namespace.upsteam_namespace') and reply the upstream library with a mock that can be asserted untouched; I'm hoping for an option that works globally, so that I don't have to add a monkeypatch to every test method, though this level of granularity is acceptable; but also don't have to perform the assertion that the mock was never used in the test methods (or make a decorator to do all that either) prohibits access to the upstream library from any part of the software (e.g, Wrapper calls B calls Upstream, B's call to upstream might not be caught)
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52618309
has title: unittest blacklist namespace and fail any attempt to reference it
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: isolation

http://stackoverflow.com/comment/92308735
has text: ok, got it. Is your gtrend.csv simply a copy of the multiTimeline.csv from the web site? Also, presumably you have some import statements for pandas and numpy. Assuming the data file works out-of-the-box, I'll try to get back to you shortly.
comment on: http://stackoverflow.com/q/52690632
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92265050
comment on: http://stackoverflow.com/q/52665338
has text: I use the calculation for R-squared (R2) as "R2 = 1.0 - (absolute_error_variance / dependent_data_variance)" and use the numpy array var() method, so in my code this becomes "R2 = 1.0 - (abs_err.var() / dep_data.var())"
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92223877
comment on: http://stackoverflow.com/a/52636811
type: AnswerComment
score: 1
type: Comment
has text: Is the JSON exactly what you have above?

http://stackoverflow.com/comment/92176055
has text: Thanks `jezrael`, this is exactly what I want.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52621123
type: QuestionComment

http://stackoverflow.com/comment/92266643
type: Comment
has text: Unless explicitly required, it's not a good practice to use `global`. I don't recommend using it anywhere.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52668292

http://stackoverflow.com/a/52710439
answers question: http://stackoverflow.com/q/52710315
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92347261
has body: Maybe something like: def direction(right_length, left_length): diff = left_length - right_length return int(abs(diff) / diff) if diff else 0 print(direction(5, 10)) # 1 print(direction(10, 5)) # -1 print(direction(1, 1)) # 0
accepted answer of: http://stackoverflow.com/q/52710315
has comment: http://stackoverflow.com/comment/92347855

http://stackoverflow.com/a/52672169
answers question: http://stackoverflow.com/q/52664583
score: 1
upvote count: 1
has body: The latest numpy (1.15) has added a take_along_axis function: In [36]: np.take_along_axis(a, b[:,None], 1) Out[36]: array([[2], [8], [9]]) It uses a helper function to construct an indexing tuple: In [37]: np.lib.shape_base._make_along_axis_idx((3,4), b[:,None], 1) Out[37]: (array([[0], [1], [2]]), array([[1], [3], [0]])) Prior to this, I (and others) would have recommended: In [38]: a[np.arange(3), b] Out[38]: array([2, 8, 9]) which is essentially the same thing (except for an added dimension). As take_along_axis docs show this was designed to take things like the results of argsort along an axis. for the higher dimension case: In [39]: a1 = np.array([[[ 1, 2, 3], ...: [ 4, 5, 6]], ...: [[ 7, 8, 9], ...: [10,11,12]]]) ...: b1 = np.array([[0,2], ...: [1,2]]) In [40]: a1.shape Out[40]: (2, 2, 3) In [41]: b1.shape Out[41]: (2, 2) In [42]: np.take_along_axis(a1, b1[...,None], -1) Out[42]: array([[[ 1], [ 6]], [[ 8], [12]]]) In [45]: np.lib.shape_base._make_along_axis_idx(a1.shape, b1[...,None], 2) Out[45]: (array([[[0]], [[1]]]), array([[[0], [1]]]), array([[[0], [2]], [[1], [2]]])) In [46]: [i.shape for i in _] Out[46]: [(2, 1, 1), (1, 2, 1), (2, 2, 1)] Again, the equivalent do-it-yourself indexing: In [48]: a1[np.arange(2)[:,None], np.arange(2)[None,:], b1] Out[48]: array([[ 1, 6], [ 8, 12]]) Once you understand array broadcasting and how it applies to indexing, the concepts here are not difficult. But the take_along_axis may make applying them easier. It is in a sense an extension of np.ix_. In [50]: np.ix_(np.arange(2), np.arange(2), np.arange(3)) Out[50]: (array([[[0]], [[1]]]), array([[[0], [1]]]), array([[[0, 1, 2]]])) In [51]: [i.shape for i in _] Out[51]: [(2, 1, 1), (1, 2, 1), (1, 1, 3)] In [55]: a1[(*np.ix_(np.arange(2), np.arange(2)),b1)] Out[55]: array([[ 1, 6], [ 8, 12]])
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52664583
type: Answer

http://stackoverflow.com/comment/92311578
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52692256
has text: @slider yeah but also I don't think SO was made for step by step online guidance in a comment box, it was getting ridiculous the amount of comments that were leading here but unconstructed, what good is a question with a 30 comment solution

http://stackoverflow.com/a/52735475
answers question: http://stackoverflow.com/q/52734472
score: 0
has body: you can use pretrained word embedding glove, you can use glove.6B.50d.txt, which you can download from the http://nlp.stanford.edu/data/glove.6B.zip , use 50d def read_glove_vecs(glove_file): with open(glove_file,'r',encoding='UTF-8') as f: words = set() word_to_vec_map = {} for line in f: line = line.strip().split() curr_word = line[0] words.add(curr_word) word_to_vec_map[curr_word] = np.array(line[1:], dtype=np.float64) i = 1 words_to_index = {} index_to_words = {} for w in sorted(words): words_to_index[w] = I index_to_words[i] = w i = i + 1 return words_to_index, index_to_words, word_to_vec_map Now call the above function, which will return word_to_index, index_to_word, word_to_vec_map = read_glove_vecs('data/glove.6B.50d.txt') Now create word embedding from these pretrained word vocab_len = len(word_to_index) emb_dim = 50 # the above word vector are trained for 50 dim emb_matrix = np.zeros((vocab_len, emb_dim)) for word, index in word_to_index.items(): emb_matrix[index,:] = word_to_vec_map[word] embedding_layer = Embedding(vocab_len, emb_dim, trainable = False) embedding_layer.build((None,)) embedding_layer.set_weights([emb_matrix]) Now use this, embedding layer in your model, which will improve your accuracy
type: Answer

http://stackoverflow.com/a/52720440
answers question: http://stackoverflow.com/q/52719780
type: Answer
score: 1
upvote count: 1
has body: From the Python 3 docs; do_GET() The request is mapped to a local file by interpreting the request as a path relative to the current working directory. If the request was mapped to a directory, the directory is checked for a file named index.html or index.htm (in that order). If found, the file’s contents are returned; otherwise a directory listing is generated by calling the list_directory() method. So because you do not have a index.html file (or any other file configured to act as the home page) the server lists the root directory contents instead. Simple solution would be to name your html file index.html and place it in the server's root directory and follow a step-by-step guide to setting up a simple Python web server such as this. Hope that helps.
downvote count: 0

http://stackoverflow.com/q/52651159
type: Question
has comment: http://stackoverflow.com/comment/92236267
score: 0
tagged with: sql
answer count: 1
has answer: http://stackoverflow.com/a/52660253
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I'm new to django. I'm trying to create a custom user model but everytime I try to migrate I get a strange error. Maybe you can help me. Here are my files: models.py: from django.db import models from django.contrib.auth.models import User from datetime import date, datetime class User(models.Model): username = models.CharField(max_length=31, unique=True) first_name = models.CharField(max_length=31, unique=True) last_name = models.CharField(max_length=31, unique=True) password = models.CharField(max_length=1023) email = models.CharField(max_length=255, unique=True, primary_key=True) typeOfPerson = models.CharField(max_length=15, default="G") birth_date = models.DateField() registration_date = models.DateTimeField( #default=str(date.today()) + " " + str(datetime.now()) auto_now_add=True ) ip_address = models.CharField(max_length=31, blank=True) classNumber = models.CharField(max_length=2, blank=True) shortName = models.CharField(max_length=3, blank=True) rank = models.CharField(max_length=15, default="Normal") forms.py: from django import forms from .models import User from django.contrib.auth.hashers import make_password class SignUpForm(forms.ModelForm): typeOfPerson = forms.ChoiceField(label="Was bist du?", required=True, choices=( ("S", "Schüler"), ("L", "Lehrer"), ("E", "Elternteil"), ("G", "Gast"), ), widget=forms.Select(attrs={ "id": "select", })) username = forms.CharField(max_length=31, min_length=3, required=True, widget=forms.TextInput(attrs={ "placeholder": "Benutzername", "id": "username", })) first_name = forms.CharField(max_length=31, min_length=3, required=True, widget=forms.TextInput(attrs={ "placeholder": "Vorname", "id": "name", })) last_name = forms.CharField(max_length=31, min_length=2, required=True, widget=forms.TextInput(attrs={ "placeholder": "Nachname", "id": "surname", })) email = forms.EmailField(max_length=255, min_length=6, required=True, widget=forms.TextInput(attrs={ "placeholder": "E-Mail", "id": "email", })) birth_date = forms.DateFi…
accepted answer: http://stackoverflow.com/a/52660253
has title: Django - Migration doesn't work and strange error
has comment: http://stackoverflow.com/comment/92234447
tagged with: authentication

http://stackoverflow.com/q/52715141
has comment: http://stackoverflow.com/comment/92714865
tagged with: docker
answer count: 1
has comment: http://stackoverflow.com/comment/92356046
accepted answer: http://stackoverflow.com/a/53634769
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: go-ethereum
tagged with: python
has comment: http://stackoverflow.com/comment/92371833
has comment: http://stackoverflow.com/comment/92381109
score: 2
has title: How to make a Docker container talk to geth on local host
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92384977
has answer: http://stackoverflow.com/a/53634769
tagged with: web3py
type: Question
downvote count: 0
has body: I have a simple python script using web3 Dockerized and I'm trying to connect to geth.ipc on local host and I can't seem to connect to it. Is there a way to do it? Python: from web3 import Web3 web3 = Web3(Web3.IPCProvider("/Ethereum/geth.ipc")) print(f'IPC connected: {web3.isConnected()}') # want to return True And I'm mounting my $HOME/Library/Ethereum/geth.ipc -> /Ethereum/geth.ipc

http://stackoverflow.com/a/52594703
answers question: http://stackoverflow.com/q/52594304
score: 0
has body: This is the long but simple solution count = -1 # Count where in the loop we are switch = 1 # Switch between 0 and 1 start = 1 # Switch which varibale we start the line with for i in range(8): print() count += 1 start = switch for j in range(8): if j != count: if switch == 0: print("1 ", end='') #end= means dont print a new line character switch = 1 else: print("0 ", end='') switch = 0 if j == count: if start == 1: switch = 0 else: switch = 1 break #Break loop as we have printed as many characters as we want print() # Print to end the line
type: Answer

http://stackoverflow.com/a/52629745
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/92199743
answers question: http://stackoverflow.com/q/52629423
has body: It's work for list comprehension but you should to rewrite your list comprehension [print(f) for r in featList for f in r] If you want to run [print(str(f)) for f in [r for r in featList]] than you could implement __repr__ in Feature: def __repr__(self) -&gt; str: return 'f' Hope it will help you :)

encoding
tags question: http://stackoverflow.com/q/52717750
tags question: http://stackoverflow.com/q/52595809
tags question: http://stackoverflow.com/q/52649213
type: Tag
tag name: encoding

http://stackoverflow.com/comment/92146573
type: AnswerComment
has text: @PaulPanzer More like a programmer is the wrong tool for creating metaphors.
comment on: http://stackoverflow.com/a/52605202
type: Comment
score: 24

http://stackoverflow.com/comment/93513062
has text: I got the same error , I reinstalled cuda 9 and cudnn and it got resolved.
comment on: http://stackoverflow.com/q/52643866
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52734352
score: 0
answer count: 1
has title: how to implement flask restful with class inheritance
tagged with: flask
favorite count: 0
has body: I want to create a little project that exists: base class - animal Dog and Cat that inherit from Animal and add for each class full rest using Flask what is the easy way to do that?
tagged with: python
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52734479
type: Question
tagged with: flask-restful
upvote count: 2

http://stackoverflow.com/a/52602745
has comment: http://stackoverflow.com/comment/92159688
has body: Try this pattern (?=[^\s]{0,2}D)(?=[^\s]{0,2}E)... It first assures, that what follows is a word (string of characters, except white spaces, achieved with nagetiva character class [^\s]) containing D and E. For each letter there is separate positive lookahead: (?=[^\s]{0,2}D) for D, (?=[^\s]{0,2}E) for E. If those are satisfied, then match three characters with .... Demo
score: 0
has comment: http://stackoverflow.com/comment/92139637
has comment: http://stackoverflow.com/comment/92139576
has comment: http://stackoverflow.com/comment/92139680
answers question: http://stackoverflow.com/q/52601558
type: Answer
has comment: http://stackoverflow.com/comment/92139585

http://stackoverflow.com/a/52808374
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52681196
has body: While looking through the source code, I found this class. I think the notebook doesn't auto authenticate when you call KaggleApi(), hence you need to call the authenticate function on the API to connect to the Kaggle API. Try: api = KaggleApi() api.authenticate() I was able to connect and download the samples after this call.
has comment: http://stackoverflow.com/comment/92537911
downvote count: 0

http://stackoverflow.com/q/52726475
tagged with: python-3.x
has body: I want to play with the OpenAI gyms in a notebook, with the gym being rendered inline. Here's a basic example: import matplotlib.pyplot as plt import gym from IPython import display %matplotlib inline env = gym.make('CartPole-v0') env.reset() for i in range(25): plt.imshow(env.render(mode='rgb_array')) display.display(plt.gcf()) display.clear_output(wait=True) env.step(env.action_space.sample()) # take a random action env.close() This works, and I get see the gym in the notebook: But! it also opens an interactive window that shows precisely the same thing. I don't want this window to be open:
tagged with: reinforcement-learning
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/126130459
answer count: 4
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/92381842
tagged with: openai-gym
has comment: http://stackoverflow.com/comment/92382020
has title: Display OpenAI gym in Jupyter notebook only
upvote count: 23
type: Question
has answer: http://stackoverflow.com/a/62849678
has answer: http://stackoverflow.com/a/54149118
has comment: http://stackoverflow.com/comment/92381982
linked to: http://stackoverflow.com/q/40195740
has comment: http://stackoverflow.com/comment/92382085
has answer: http://stackoverflow.com/a/78565130
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/72450538
score: 23

http://stackoverflow.com/q/52698369
has comment: http://stackoverflow.com/comment/92323938
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/92324191
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92323565
type: Question
has body: viewset code class UserTitleViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = UserTitleMod.objects.all() serializer_class = UserTitleSerializer def update(self, request, *args, **kwargs): return "ok" def perform_update(self, serializer): return "ok" settings.py CORS_ALLOW_METHODS = [ 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ] I have tried many times but it's still not working. Thank you for your reply.
has title: django viewset extends mixins.UpdateModelMixin but postman updates model by patch method returns ' detail: Method PATCH not allowed'
has comment: http://stackoverflow.com/comment/92323631
has comment: http://stackoverflow.com/comment/92323361
has comment: http://stackoverflow.com/comment/92323626
has comment: http://stackoverflow.com/comment/92324181
has comment: http://stackoverflow.com/comment/92324089
has comment: http://stackoverflow.com/comment/92323527
has comment: http://stackoverflow.com/comment/92323901
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92323778

http://stackoverflow.com/q/52649989
type: Question
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/52650059
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/52650059
type: AnsweredQuestion
has title: Pandas: Reducing multi-index to highest available level
tagged with: multi-index
has body: I have the following type of a dataframe, values which are grouped by 3 different categories A,B,C: import pandas as pd A = ['A1', 'A2', 'A3', 'A2', 'A1'] B = ['B3', 'B2', 'B2', 'B1', 'B3'] C = ['C2', 'C2', 'C3', 'C1', 'C3'] value = ['6','2','3','3','5'] df = pd.DataFrame({'categA': A,'categB': B, 'categC': C, 'value': value}) df Which looks like: categA categB categC value 0 A1 B3 C2 6 1 A2 B2 C2 2 2 A3 B2 C3 3 3 A2 B1 C1 3 4 A1 B3 C3 5 Now, when I want to unstack this df by the C category, .unstack() returns some multi-indexed dataframe with 'value' at the first level and my categories of interest C1, C2 &amp; C3 at the second level: df = df.set_index(['categA','categB','categC']).unstack('categC') df Output: value categC C1 C2 C3 categA categB A1 B3 NaN 6 5 A2 B1 3 NaN NaN B2 NaN 2 NaN A3 B2 NaN NaN 3 Is there a quick and clean way to get rid of the multi-index by reducing it to the highest available level? This is what I'd like to have as output: categA categB C1 C2 C3 A1 B3 NaN 6 5 A2 B1 3 NaN NaN B2 NaN 2 NaN A3 B2 NaN NaN 3 Many thanks in advance! Edit: print(df.reset_index()) gives: categA categB value categC C1 C2 C3 0 A1 B3 NaN 6 5 1 A2 B1 3 NaN NaN 2 A2 B2 NaN 2 NaN 3 A3 B2 NaN NaN 3

http://stackoverflow.com/comment/92274931
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52672529
has text: Could you please post more information. A [mcve] or your full code would help, but given what you have posted, it is hard to tell what is going on.
score: 0

http://stackoverflow.com/a/52638911
has body: You could use formatted printing and unpack the passwordnumber tuple print('{}{}{}{}{}'.format(passwordletter, *passwordnumber) # nigc5496
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52635869

http://stackoverflow.com/comment/92214503
has text: @TimBiegeleisen I want to create a dictionary from the above lines with key being "establishmentCause" and its corresponding value being "mo-Signalling" and so on for Freq, Physical Cell ID etc
comment on: http://stackoverflow.com/q/52640941
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52621243
type: Answer
score: 2
has body: Change the greedy method 1st substring regex to the only word character : L = [{0: 'x==1', 1: 'y==2', 2: 'z!=1'}, {0: 'x==1', 1: 'y&lt;=3', 2: 'z&gt;1'}] L = [[re.findall(r'(\w)([&lt;&gt;=!]+)(.*)', v)[0] for k, v in x.items()] for x in L] [[(y[0],ops[y[1]],y[2]) for y in x] for x in L] [[('x', &lt;function _operator.eq&gt;, '1'), ('y', &lt;function _operator.eq&gt;, '2'), ('z', &lt;function _operator.ne&gt;, '1')], [('x', &lt;function _operator.eq&gt;, '1'), ('y', &lt;function _operator.le&gt;, '3'), ('z', &lt;function _operator.gt&gt;, '1')]] Or as per jezrael suggestion from comments (1 line list comprehesion): L = [[[(z[0], ops[z[1]], z[2]) for z in re.findall(r'(\w)([&lt;&gt;=!]+)(.*)', v)][0] for k, v in x.items()] for x in L] Or we don't need keys so using values directly: L = [[[(z[0], ops[z[1]], z[2]) for z in re.findall(r'(\w)([&lt;&gt;=!]+)(.*)', v)][0] for v in x.values()] for x in L]
downvote count: 0
answers question: http://stackoverflow.com/q/52620865
upvote count: 2
has comment: http://stackoverflow.com/comment/92176257
has comment: http://stackoverflow.com/comment/92176303

http://stackoverflow.com/comment/92150571
has text: Good! Be aware that `SYS_ADMIN` for containers is a security risk, the container gains a lot of power. If you find a less permissive capability, it would be better. Try `--cap-add ALL --cap-drop SYS_ADMIN` to check whether another capability would work, too. You can also try `--security-opt seccomp=unconfined`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52593833

http://stackoverflow.com/comment/92212904
has text: `print("the number im trying to type is" + str(number) + ". ")` or use `str.format()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52640287

http://stackoverflow.com/q/52611109
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52614353
tagged with: python
has body: I need to implement multithreading to a Python job. I have a dictionary and each key in that dictionary (out of about 40) is a timestamped pandas dataframe. Most of the dataframes have 100,000+ rows. Their timestamps are strings in "%Y-%m-%d %H:%M:%S" format. To convert the timestamped strings I use the following function: def to_dt(df): df['timestamp'] = df['timestamp'].map(lambda n: pd.to_datetime(n, format='%Y-%m-%d %H:%M:%S')) return df So I would like to put each process to_dt(df) in a separate thread. How can I do that? To simplify let's consider we have the following setup: def to_dt(df): df['timestamp'] = df['timestamp'].map(lambda n: pd.to_datetime(n, format='%Y-%m-%d %H:%M:%S')) return df # empty dictionary d_test = {} # dataframe with single string timestamp column df = pd.DataFrame(columns=['st_dt']) # populate dataframe with 1000 timestamp rows for i in range(1000): df.loc[len(df)] = ['2018-10-02 10:00:00'] # add 20 instances of the dataframe to the dictionary with keys in format "a0" to 'a19' for i in range(20): d_test['a'+str(i)] = df Now how can we make each iteration of for i in range(20): to_dt(d_test['a'+str(i)]) to run in a separate thread?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52614353
has comment: http://stackoverflow.com/comment/92156998
tagged with: multithreading
has comment: http://stackoverflow.com/comment/92157563
tagged with: string-to-datetime
type: Question
possible better answer: http://stackoverflow.com/a/52612840
has answer: http://stackoverflow.com/a/52612840
score: 0
has title: Python Multithreading Implementation of to_datetime Function

http://stackoverflow.com/a/52671957
score: 0
type: Answer
has body: There are two issues: You refer to stringnumber instead of strnumber. You are misusing str.split, which takes as an argument a delimiter. This function is not necessary. So you can use: a, b, c, d = (strnumber[i:i+1] for i in range(0, len(strnumber), 1)) However, note that strings are themselves iterable, so you can unpack directly: a, b, c, d = strnumber Or, if you need integers: a, b, c, d = map(int, strnumber) Alternatively, you can use mathematical operations and obviate the need for conversion between str and int: from math import log10 d, c, b, a = (number // 10**i % 10 for i in range(int(log10(number))+1)) Notice we reverse the assignment order to reflect our calculation.
answers question: http://stackoverflow.com/q/52671829

http://stackoverflow.com/a/52723783
downvote count: 0
has body: Rewriting in terms of exp instead of cos is more helpful: expr.rewrite(exp).simplify() returns -cos(2*N)/2 + 1/2 which is visibly equivalent to sin(N)**2. Clean it up with expr.rewrite(exp).simplify().trigsimp() getting sin(N)**2 Old answer, might still be of value: You probably meant N to be real, so let's declare it as such. Given a mix of complex exponentials and trigonometric functions, it will probably help to separate the real and imaginary parts with as_real_imag(). A direct application does not do much beyond putting re(...) and im(...), so rewriting in exponentials and expanding the squares/products is advisable first: N = symbols('N', real=True) expr = (exp(2*I*N) - 1)**2/((exp(2*I*N) - 1)**2 - 4*exp(2*I*N)*cos(N)**2) result = [a.trigsimp() for a in expr.rewrite(cos).expand().as_real_imag()] Result: [sin(N)**2, 0], meaning the real and imaginary parts of the expression. It can be recombined into a single expression with result[0] + I*result[1].
accepted answer of: http://stackoverflow.com/q/52722676
type: Answer
answers question: http://stackoverflow.com/q/52722676
has comment: http://stackoverflow.com/comment/92373550
score: 4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/52682592
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52678376
has body: If you want your QR picture to get identified, rotated and scaled correctly you need the following task : (you needs the combination of two techniques) First step: detect the x,y coordinates of the 4 corners of each QR code. The Python library zbar is useful for this : print(symbol.location) gives the coordinates. Second step: now a deskewing / perspective correction / "homography" is needed. Here is how to do it with Python + OpenCV.

http://stackoverflow.com/comment/92117822
has text: I am using jupyter notebook
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52591338
type: Comment

http://stackoverflow.com/comment/92133222
comment on: http://stackoverflow.com/q/52599176
score: 0
has text: If you want to use a slider for a date range you'll need to define a date for your start point and your end point, then calculate the percentage between those two points your target is and apply that to your slider. Sliders require a start and end and, technically, time has neither.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92307679
type: QuestionComment
has text: How many times does your objective function get called per optimization? Show us, with timings, that overhead dominates the time.
type: Comment
comment on: http://stackoverflow.com/q/52690110
score: 0

http://stackoverflow.com/comment/92351524
type: QuestionComment
has text: Sha256 depends on the c++ library, but I have this c library on my computer.
comment on: http://stackoverflow.com/q/52712687
score: 0
type: Comment

http://stackoverflow.com/q/52593584
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92122015
has comment: http://stackoverflow.com/comment/92122153
has answer: http://stackoverflow.com/a/52607448
favorite count: 0
has body: I am first time trying out python unit tests referring to this article. I have PyDev plugin installed in my Eclipse. My test_hello.py looks like this: import unittest class TestHello(unittest.TestCase): def test_abc(self): print("Test!!!") result = True self.assertEqual(result, True, "ohno") When I Right click on source &gt; Run As &gt; Python unit-test, it outputs: Finding files... done. Importing test modules ... PYTHONPATH not found for file: D:\workspaces\python-ws\test\test_h done. ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Also in PyUnit tab, it doesnt show anything: What I am missing here? Update Adding more details: My project: PyDev package explorer
has comment: http://stackoverflow.com/comment/133647235
has comment: http://stackoverflow.com/comment/92122118
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92122543
tagged with: python
has comment: http://stackoverflow.com/comment/92122198
upvote count: 1
has comment: http://stackoverflow.com/comment/92122279
type: Question
has title: Python unit tests are not running at all
tagged with: pydev
score: 1
tagged with: python-unittest
linked to: http://stackoverflow.com/q/25387374
tagged with: eclipse
has comment: http://stackoverflow.com/comment/92122214
has comment: http://stackoverflow.com/comment/92122769
has comment: http://stackoverflow.com/comment/92122582
has comment: http://stackoverflow.com/comment/92122402

http://stackoverflow.com/a/52742505
has comment: http://stackoverflow.com/comment/92410114
downvote count: 0
has comment: http://stackoverflow.com/comment/92409865
answers question: http://stackoverflow.com/q/52742118
type: Answer
has comment: http://stackoverflow.com/comment/92409995
upvote count: 3
score: 3
has body: By using pandas BDay df.day.update(df.loc[(df.category=='B')&amp;((df.day.dt.weekday.isin([5,6])|(df.day.isin(holidays )))),'day']-pd.tseries.offsets.BDay(1)) df Out[22]: category day 0 A 2018-10-10 1 B 2018-10-10 2 C 2018-10-12 3 B 2018-10-12 4 C 2018-10-14 5 A 2018-10-15

featuretools
tag name: featuretools
tags question: http://stackoverflow.com/q/52629549
type: Tag
tags question: http://stackoverflow.com/q/52673694

http://stackoverflow.com/comment/92146309
type: AnswerComment
comment on: http://stackoverflow.com/a/52605988
type: Comment
score: 1
has text: @JustinScofield, The question there is different. Here you **want** a copy. In that question, OP does not want a copy and therefore `copy()` is inappropriate.

http://stackoverflow.com/q/52633138
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92224571
tagged with: cell
downvote count: 0
favorite count: 0
tagged with: background-color
type: UnansweredQuestion
tagged with: python
has title: Change the background color of a cell in Tkinter?
has comment: http://stackoverflow.com/comment/92200395
linked to: http://stackoverflow.com/q/48358084
tagged with: tkinter
answer count: 0
score: 1
has body: I saw that I can change the background color of a row, but is it possible to change the background color of a cell? I need the color of the "busy" cell to be red. running looks like this: The code is it: from tkinter import * from tkinter.ttk import * import tkinter.messagebox class App(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.CreateUI() self.LoadTable() self.grid(sticky = (N,S,W,E)) parent.grid_rowconfigure(0, weight = 1) parent.grid_columnconfigure(0, weight = 1) def CreateUI(self): tv = Treeview(self) tv['columns'] = ('First', 'Second') tv.heading("#0", text=' ', anchor='w') tv.column("#0", anchor="w") tv.heading('First', text='First') tv.column('First', anchor='center', width=100) tv.heading('Second', text='Second') tv.column('Second', anchor='center', width=100) tv.grid(sticky = (N,S,W,E)) self.treeview = tv self.grid_rowconfigure(0, weight = 1) self.grid_columnconfigure(0, weight = 1) def LoadTable(self): agente1 = self.treeview.insert('', 'end', text="Agente1",) self.treeview.insert(agente1, 'end', text="Availability", values=('Busy', 'Insert')) def main(): root = Tk() App(root) root.mainloop() if __name__ == '__main__': main()

http://stackoverflow.com/q/52629888
answer count: 1
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
tagged with: web-scraping
downvote count: 0
type: UnansweredQuestion
has body: I am trying to collect a dataset with time series data of FIFA ultimate team players from futbin.com. I have found a script on GitHub https://github.com/darkyin87/futbin-scraper which is able to scrape the current price of a player given a list of players/ids: import requests import json domain = 'https://www.futbin.com' version = 19 page = 'playerPrices' player_ids = { 'Arturo Vidal': 181872, 'Pierre-Emerick Aubameyang': 188567, 'Robert Lewandowski': 188545, 'Jerome Boateng': 183907, 'Sergio Ramos': 155862, 'Antoine Griezmann': 194765, 'David Alaba': 197445, 'Paulo Dybala': 211110, 'Radja Nainggolan': 178518 } def fetch_prices(): ret_val = {} for name, id in player_ids.iteritems(): url = "%s/%s/%s?player=%s" % (domain, version, page, id) response = requests.get(url) data = response.json() ret_val[name] = data[str(id)]['prices']['ps']['LCPrice'] return ret_val if __name__ == "__main__": prices = fetch_prices() fetch_prices But the information I am looking for is not the current price but rather the price (specifically the PS price) history which is located on the bottom as I graph. https://www.futbin.com/19/player/143/Cristiano%20Ronaldo/ I tried a few things but I seem to be unable to parse/extract this information... could someone help me out or give me a hint? Thanks in advance
score: 3
has answer: http://stackoverflow.com/a/52654521
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: Web-scraping futbin.com
tagged with: python

http://stackoverflow.com/comment/92117302
type: Comment
comment on: http://stackoverflow.com/q/52590716
score: 0
type: QuestionComment
has text: Your doing something wrong in creating the dataframe. Say for example train_data is 404 rows and 13 columns - but your dataframe has 852 rows and 2 columns. can you paste your code on how you created the train_data dataframe?

http://stackoverflow.com/a/52681443
accepted answer of: http://stackoverflow.com/q/52681217
answers question: http://stackoverflow.com/q/52681217
has comment: http://stackoverflow.com/comment/92291485
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/92291274
has comment: http://stackoverflow.com/comment/92291237
score: 1
has comment: http://stackoverflow.com/comment/92291255
has comment: http://stackoverflow.com/comment/92291360
has comment: http://stackoverflow.com/comment/92291430
has body: @mkreiger1 comment is correct: debugging helps a lot in this cases. The problem is in the comparison m == i[0]: in the first iteration m is '-HVC1 ' while i[0] is '-HVC1'. Thus the comparison is always False. The solution is to strip the white spaces: lines = ['-HVC1 tank', 'Contains300gallons', '-HVC2 tank', 'Contains20gallonsofgasand220galonsofkero'] sequence = [] dic = {} for line in lines: if line.startswith('-'): tx = line.split('tank', 1)[0] else: gh = line[:-1] # THE FIX IS HERE: Strip the white spaces in ``tx`` dic[tx.strip()] = gh s = [['-HVC1', '0', '8'], ['-HVC1', '12', '18'], ['-HVC2', '9', '17']] for i in s: seq = [] for m, n in dic.items(): for j, k in enumerate(n): if (int(i[1]) &lt;= j &lt;= int(i[2])) and (m == i[0]): seq.append(k) sequence.append(seq) print(sequence) Output: [['C', 'o', 'n', 't', 'a', 'i', 'n', 's', '3'], ['a', 'l', 'l', 'o', 'n'], ['0', 'g', 'a', 'l', 'l', 'o', 'n', 's', 'o']]
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/117103643
type: QuestionComment
has text: I have got the same type of error, and after removing the null values or nan values, using `df.dropna(inplace=True)` , the above error , no longer exists.
score: 0
comment on: http://stackoverflow.com/q/52736900
type: Comment

http://stackoverflow.com/q/52680071
tagged with: python
tagged with: discord
accepted answer: http://stackoverflow.com/a/52681082
tagged with: python-3.x
has body: I am wanting to get the server ID from a JSON file which I am confused on how to do. Below is my current Python file import discord from discord.ext import commands import youtube_dl import json with open("configs/premium.json") as f: premium = json.load(f) def premium(bot, message): id = message.server.id return premium.get(id) class Play: def __init__(self, client): self.client = client @commands.command(pass_context=True) async def play(self, ctx): try: if ctx.message.server.id == premium: await self.client.say('Premium works') else: await self.client.say('Non-Premium Works!') except Exception as error: await self.client.say('{}'.format(error)) def setup(client): client.add_cog(Play(client)) JSON File {"serverID":"498054637245693952"}
has comment: http://stackoverflow.com/comment/92330561
type: Question
type: AnsweredQuestion
tagged with: discord.py
has comment: http://stackoverflow.com/comment/92288722
answer count: 1
score: 0
has title: Getting server ID's from JSON
has answer: http://stackoverflow.com/a/52681082

http://stackoverflow.com/q/52639457
type: Question
upvote count: 2
has body: Here is my models.py class Language(models.Model): language_id = models.BigAutoField(primary_key=True) language_name = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now=True) latest_build_on = models.DateTimeField(auto_now_add=True) latest_version = models.DecimalField(max_digits=5, decimal_places=2) company = models.OneToOneField('Company',on_delete=models.CASCADE,related_name='language') def __str__(self): return self.language_name class Frameworks(models.Model): framework_id = models.BigAutoField(primary_key=True) framework_name = models.CharField(max_length=255) framework_logo = models.FileField() created_on = models.DateTimeField(auto_now=True) latest_build_on = models.DateTimeField(auto_now_add=True) latest_version = models.DecimalField(max_digits=5, decimal_places=2) language = models.ForeignKey('Language',on_delete=models.CASCADE,related_name='frameworks') def __str__(self): return self.framework_name class Technologies(models.Model): technology_id = models.BigAutoField(primary_key=True) technology_name = models.CharField(max_length=255) description = models.TextField() language = models.ManyToManyField('Language',related_name='technology') def __str__(self): return self.technology_name Here is serializers.py class GetLanguageSerializer(serializers.ModelSerializer): technology = serializers.StringRelatedField(many=True) frameworks = serializers.StringRelatedField(many=True) class Meta: model = Language fields = ('language_name','created_on','latest_build_on','latest_version','company','technology','frameworks') depth = 1 class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ('language_name','created_on','latest_build_on','latest_version','company') class GetFrameworksSerializer(serializers.ModelSerializer): language = serializers.StringRelatedField() class Meta: model = Frameworks fields = '__all__' depth = 1 class FrameworksSerializer(serializers.ModelSerializer): class Meta: model = Framework…
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92212030
answer count: 1
has comment: http://stackoverflow.com/comment/92211950
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
has title: How to get count with foreign key in django rest framework
has answer: http://stackoverflow.com/a/52639831
accepted answer: http://stackoverflow.com/a/52639831

http://stackoverflow.com/q/52636882
has title: How to Check if a Matrix is in a List of Matrices Python
downvote count: 0
has body: This is the list of matrices; [matrix([[1, 0], [1, 0], [1, 0], [1, 0]]), matrix([[0, 0, 0, 0], [1, 1, 1, 1]]), matrix([[0, 1], [0, 1], [0, 1], [0, 1]]), matrix([[0, 0, 0, 0], [1, 1, 1, 1]]), matrix([[1, 1, 1, 1], [0, 0, 0, 0]])] and I want to check if a matrix is already inside the list example; a = matrix([[0, 0, 0, 1], [1, 1, 1, 0]]) So if a is in m then print True else print False
type: Question
tagged with: numpy
score: 5
tagged with: arrays
tagged with: matrix
answer count: 1
has answer: http://stackoverflow.com/a/52636978
accepted answer: http://stackoverflow.com/a/52636978
favorite count: 0
upvote count: 5
tagged with: python
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/92276605
has text: Thanks for the info. I am just reading similar issues on github and thinking what is the best solution for me.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52673236

http://stackoverflow.com/q/52652634
type: Question
has body: I have a class method that validates that a dictionary contains all of the keys that I expect it to by comparing the dictionary to a list. Currently, I have the set defined at the module level of my class, like so: expected_keys = { 'key1', 'key2', 'key3', 'key4', } class Spam(object): def __init__(self, config_dict): try: self.validate_configs(configs) except TypeError, ValueError: raise ... def validate_configs(self, config_dict): if not isinstance (config_dict, dict): raise TypeError('Config structure is not a dictionary.') if not expected_keys == config_dict.keys(): raise ValueError('Config dict does not have all necessary keys.') Is this the best (performance and practice-wise) way to do this? I plan on having possibly hundreds of these objects instantiated at a time, and I'm not sure if the current method will cause any performance hits. The real expected_keys set contains ~30 entries as well. I can get over how ugly it looks in my source file so long as I'm doing things correctly ("there should be one-- and preferably only one --obvious way to do it").
has title: Define list at module level or within class
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52653014
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92237092
tagged with: python-3.x
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/92238791
accepted answer: http://stackoverflow.com/a/52653014
has comment: http://stackoverflow.com/comment/92238657
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92237485
tagged with: oop

http://stackoverflow.com/q/52602835
has comment: http://stackoverflow.com/comment/92139762
accepted answer: http://stackoverflow.com/a/52602947
upvote count: 2
has comment: http://stackoverflow.com/comment/92139984
has body: studentNumber = len(age) - 1 age[studentNumber] = 0 house[studentNumber] = '' reactionTime[studentNumber] = 0 while True: try: age[studentNumber] = int(input("What is the age of the student: ")) except ValueError: age[studentNumber] = int(input("What is the age of the student: ")) if age[studentNumber] in range(12, 17): break house[studentNumber] = input("Which house is the student in (Saturn/Mars): ").lower() while house[studentNumber] not in {"saturn", "mars"}: house[studentNumber] = input("Which house is the student in (Saturn/Mars): ").lower() age.append(0) house.append('') reactionTime.append(0) print(age + " " + house + " " + reactionTime) I'm trying to validate the input as a string that is "saturn"or "mars", but I'm receiving the error TypeError: can only concatenate list (not "str") to list when I try to add it to my list The command line: What would you like to do: 1. Enter new information 2. House-based statsitics 3. Specific Criteria statistics Enter 1 2 or 3: 1 What is the age of the student: 12 Which house is the student in (Saturn/Mars): saturn Traceback (most recent call last): File "python", line 46, in &lt;module&gt; File "python", line 32, in newInfo TypeError: can only concatenate list (not "str") to list
answer count: 1
has comment: http://stackoverflow.com/comment/92139909
has comment: http://stackoverflow.com/comment/92140038
has comment: http://stackoverflow.com/comment/92139951
has comment: http://stackoverflow.com/comment/92139916
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52602947
tagged with: validation
downvote count: 0
has comment: http://stackoverflow.com/comment/92139904
has comment: http://stackoverflow.com/comment/92139925
has comment: http://stackoverflow.com/comment/92139852
favorite count: 0
has comment: http://stackoverflow.com/comment/92139892
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/92139931
tagged with: python
has title: Validating string input and concatenating it to a list
has comment: http://stackoverflow.com/comment/92139924

http://stackoverflow.com/comment/92367463
type: Comment
comment on: http://stackoverflow.com/a/52720748
score: 0
type: AnswerComment
has text: @NiladryKar: (a) is `update_date` the name of the field that stores this update timestamp; and (b) did you *rename* the context-variable, like `context['selectdate'] = ...` not `context['selectdate_list'] = ...`.

http://stackoverflow.com/q/52723383
linked to: http://stackoverflow.com/q/52690632
accepted answer: http://stackoverflow.com/a/52723550
has title: Difference between scipy periodogram and self implemented power spectral density
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I am trying to evaluate the frequency domain of several signals. For this I used the PSD implementation given in this answer. As a comparison I used the signal.periodogram function provided in scipy: from scipy.signal import tukey import scipy as sp f, Pxx_den = sp.signal.periodogram(a_gtrend_orig,12,window=tukey( len(a_gtrend_orig) )) However when I plot this next to the self-implemented PSD they look significantly different: As the same window function is used and the periodogram function should also use an FFT where does this difference coming from?
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52723550
upvote count: 2
answer count: 1
tagged with: scipy

http://stackoverflow.com/q/52675339
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52675380
type: Question
has answer: http://stackoverflow.com/a/52675346
upvote count: 5
tagged with: counter
has body: example = ['apple', 'pear', 'apple'] How can I get the below from the above result = [(apple ,2), (pear, 1)] I only know how to use Counter, but I'm not sure how to turn the results to the format above. The tuple command would not work: &gt;&gt;&gt; tuple(Counter(example)) ('apple', 'pear')
answer count: 2
score: 5
has title: How to turn Counter results to a list of tuples
linked to: http://stackoverflow.com/q/1296042
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: tuples
duplicate of: http://stackoverflow.com/q/1296042
type: UnansweredQuestion

jupyter
tags question: http://stackoverflow.com/q/52636795
tags question: http://stackoverflow.com/q/52695195
tags question: http://stackoverflow.com/q/52706238
type: Tag
tags question: http://stackoverflow.com/q/52622358
tags question: http://stackoverflow.com/q/52734050
tags question: http://stackoverflow.com/q/52705778
tags question: http://stackoverflow.com/q/52732449
tags question: http://stackoverflow.com/q/52597178
tags question: http://stackoverflow.com/q/52734739
tag name: jupyter
tags question: http://stackoverflow.com/q/52615414
tags question: http://stackoverflow.com/q/52602484
tags question: http://stackoverflow.com/q/52677085
tags question: http://stackoverflow.com/q/52716440
tags question: http://stackoverflow.com/q/52590291
tags question: http://stackoverflow.com/q/52681365
tags question: http://stackoverflow.com/q/52722400
tags question: http://stackoverflow.com/q/52676660
tags question: http://stackoverflow.com/q/52738709
tags question: http://stackoverflow.com/q/52653499

http://stackoverflow.com/a/52609472
answers question: http://stackoverflow.com/q/52608956
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92153335
has comment: http://stackoverflow.com/comment/92154326
type: Answer
accepted answer of: http://stackoverflow.com/q/52608956
has comment: http://stackoverflow.com/comment/92154287
score: 1
upvote count: 1
has body: This code is giving 14 entries, out of which first one and last one shouldnt be considered. Last one being javascript code. You just need to change the parser to a more lenient one, more can be found here https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser. page = requests.get("http://www.freejobalert.com/upsc-recruitment/16960/#Engg-Services2019") c = page.content soup=BeautifulSoup(c,"html5lib") tables=soup.find_all("table") for table in tables[1:-1]: print (table.text) If changing your parser shows you an error, install html5lib in your environment, like this pip3 install html5lib
has comment: http://stackoverflow.com/comment/92154514
has comment: http://stackoverflow.com/comment/92153990
has comment: http://stackoverflow.com/comment/92154464

http://stackoverflow.com/a/52651685
has body: First of all, you shouldn't use file as a variable name, it's a builtin in python, consider using f instead. Also notice that in the shutil.move line, I've changed your (os.path.join(file_dir,f) to (os.path.join(path1,f). file_dir is a list, not the name of the directory that you're looking for, that value is stored in your path1 variable. Altogether, it looks like this: import os import shutil path1 = '/home/user/Downloads' file_dir = os.listdir(path1) fpath = '/home/user/music' for f in file_dir: if f.endswith('.mp3'): shutil.move(os.path.join(path1,f), os.path.join(fpath, f))
answers question: http://stackoverflow.com/q/52651598
has comment: http://stackoverflow.com/comment/92235332
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52651598
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/comment/92300602
type: QuestionComment
has text: Wait, so the result would be an empty list? Please update your question with the desired output to avoid confusion.
comment on: http://stackoverflow.com/q/52686600
score: 0
type: Comment

http://stackoverflow.com/comment/92416320
score: 0
type: Comment
type: QuestionComment
has text: Please describe your query in terms of what you want to accomplish in the plainest language possible (e.g "I want all locations with at least one machine") etc. It makes it a lot easier to help.
comment on: http://stackoverflow.com/q/52745415

http://stackoverflow.com/comment/92361899
has text: Key phrase: "*another for loop right **after***". The two for-loops are separate, not nested.
comment on: http://stackoverflow.com/q/52718194
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52653805
score: 0
has comment: http://stackoverflow.com/comment/92239371
answer count: 1
has body: Im trying to get this code to find say 30 words before a specific word and 30 words after. then i want it to writ'e my output to a new file. i cant seem to figure out what i'm doing wrong as im pretty new to python. any suggestions are more than welcome. def extract_text(file_name, to_find): file_in = open('School.txt', 'r') all_lines = file_in.readlines() file_in.close() new_text = all_text.replace ('\n', '|') width = 30 to_find = 'boy' new_text = all_text.replace ('\n', '|') while new_text.find(to_find) != -1: start = all_text.find(to_find) begin = start - width end = start + len(to_find) + width print(new_text[begin:end]) out_put = new_text[begin:end] f = open("School_boy.txt","w") f.write(out_put) f.close()
tagged with: python-3.x
has title: output characters before and after a word then write to file
has answer: http://stackoverflow.com/a/52654062
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92239299
has comment: http://stackoverflow.com/comment/92239661
type: Question
has comment: http://stackoverflow.com/comment/92239461
has comment: http://stackoverflow.com/comment/92239333
has comment: http://stackoverflow.com/comment/92239579

memoization
type: Tag
tags question: http://stackoverflow.com/q/52745085
tag name: memoization

http://stackoverflow.com/comment/107794069
comment on: http://stackoverflow.com/a/53527569
score: 0
type: Comment
type: AnswerComment
has text: An example for a meta-class solution similar to what was suggested in the comments above can be found here https://stackoverflow.com/a/59649149/1629696

http://stackoverflow.com/q/52592613
has comment: http://stackoverflow.com/comment/92262863
type: Question
has comment: http://stackoverflow.com/comment/92263048
has comment: http://stackoverflow.com/comment/92263215
has comment: http://stackoverflow.com/comment/92303241
possible better answer: http://stackoverflow.com/a/52667107
has title: Can pythons lambda be used to change the inner working of another function?
has comment: http://stackoverflow.com/comment/92263764
downvote count: 0
has comment: http://stackoverflow.com/comment/92263383
has comment: http://stackoverflow.com/comment/92302737
has answer: http://stackoverflow.com/a/52688553
answer count: 3
has comment: http://stackoverflow.com/comment/92302706
has comment: http://stackoverflow.com/comment/92262842
has answer: http://stackoverflow.com/a/52684527
favorite count: 0
linked to: http://stackoverflow.com/q/1065433
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92263045
score: 6
tagged with: python
linked to: http://stackoverflow.com/q/16501
accepted answer: http://stackoverflow.com/a/52688553
tagged with: lambda
upvote count: 6
has comment: http://stackoverflow.com/comment/92303222
has comment: http://stackoverflow.com/comment/92263378
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92303324
has body: I have the following code snippet which i needed to (massively) speed up. As is, it's hugely inefficient. possible_combos.append([comb for comb in itertools.combinations_with_replacement(input_list, target_number_of_packages) if np.sum([j[1] for j in comb])==target_number_of_packages]) Disassembled: possible_combos is the output input_list is a list of tuples in the form ([...],number_of_packages) target_number_of_packages is the number of packages I need to reach. I can combine as many elements of the list "input_list" as I want (repetitions are allowed), but need to reach exactly target_number_of_packages when adding their "number_of_packages", else the combination is not valid. I was thinking about something like possible_combos.append([comb for comb in itertools.combinations_with_replacement(input_list, lambda x:x=...))) but wasn't able to fill the blank. My question is, is it at all possible to use lambda this way? I don't need an answer for how to deal with this specific usecase because I've solved it differently (with itertools product an a recursive generator function), but I'd still like to know, would there have been a solution? In short: Is it possible to use lambda to change a value inside another function on the fly? Minimal example for the problem: input_list=[1,2,3,4,5,6] #in minmal form target_number_of_packages=4 possible_combos should be [[1,1,1,1],[2,1,1],[2,2],[3,1],[4]] And I'm looking for something roughly equivalent to, but faster than, possible_combos=[comb for comb in itertools.combinations_with_replacement(input_list) if np.sum(comb)==target_number_of_packages] Just with the np.sum(comb)==target put in the itertools.combinations_with_replacement - if possible at all. I've changed the question because I solved the underlying problem differently, but part of it is still something I'd like to know about. As there where no answers, I think an edit is apropriate.
has answer: http://stackoverflow.com/a/52667107
has comment: http://stackoverflow.com/comment/92263505

http://stackoverflow.com/comment/92358845
type: QuestionComment
score: 0
has text: "Is there a way to install the updated version of pip?" - The answer is there already: `pip install --upgrade pip`
comment on: http://stackoverflow.com/q/52716189
type: Comment

http://stackoverflow.com/comment/92215549
comment on: http://stackoverflow.com/a/52641269
type: AnswerComment
type: Comment
score: 0
has text: i get error 'Member matching query does not exist.' even when im just sending name only in postman. if this wrong, what is the best solution for this case? i cant think of any solution for this. because my partner can achieve this with PHP CI, maybe this case can work with django too

http://stackoverflow.com/comment/92210873
comment on: http://stackoverflow.com/a/52620100
type: Comment
score: 0
type: AnswerComment
has text: Gives me the following error : 'One or more row labels was not found'

http://stackoverflow.com/q/52682332
has answer: http://stackoverflow.com/a/52682338
has title: What type is 'pass' in Python?
type: AnsweredQuestion
score: 1
downvote count: 3
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/100003
has body: The passstatement is usually a placeholder for future code and is used as a null operation. But why it's not defined a type in Python. Should't it belong to None type?
accepted answer: http://stackoverflow.com/a/52682338
favorite count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92292810

http://stackoverflow.com/q/52730200
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52750313
has comment: http://stackoverflow.com/comment/92387461
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52730310
downvote count: 1
has title: sorting a dictionary with nested list
type: Question
has comment: http://stackoverflow.com/comment/92385698
has body: I have a dictionary with nested lists. I need to sort by year, title and director, and print it as year: title director etc. The problem I am currently having (not into the sorting yet) is that when trying to print the lists from the key, for 2006 and 2011 where there are nested lists, it prints two separate 2006 and 2011's. My code: movie_dictionary = { '2005':'Munich','Steven Spielberg,', '2006':[['The Prestige','Christopher Nolan,'],['The Departed,','Martin Scorsese']], '2007':'Into the Wild,','Sean Penn', '2008':'The Dark Knight,','Christopher Nolan', '2009':'Mary and Max,','Adam Elliot', '2010':"The King's Speech,",'Tom Hooper', '2011':[ ['The Artist,','Michel Hazanavicius'], ['The Help,','Tate Taylor'] ], '2012':'Argo,','Ben Affleck', '2013':'12 Years a Slave,','Steve McQueen', '2014':'Birdman,','Alejandro G. Inarritu', '2015':'Spotlight,','Tom McCarthy', '2016':'The BFG,','Steven Spielberg' } # Prompt the user for a year year = input('Enter a year between 2005 and 2016:\n') # Displaying the title(s) and directors(s) from that year movie_display = movie_dictionary.get(year,'N/A') if movie_display == 'N/A': print('N/A') else: for movie in movie_display: print(movie[0],movie[1]) # Display menu print() print("MENU") print("Sort by:\n" "y - Year\n" "d - Director\n" "t - Movie title\n" "q - Quit\n") user_input = input('Choose an option:\n').lower().strip() if user_input == 'q': exit() elif user_input == 'y': for year, movie in sorted(movie_dictionary.items()): for movies, director in movie: print(year+':\n', str(movies), str(director)) elif user_input == 'd': print() elif user_input == 't': print() The output is: Enter a year between 2005 and 2016: The Artist, Michel Hazanavicius The Help, Tate Taylor MENU Sort by: y - Year d - Director t - Movie title q - Quit Choose an option: 2005: Munich Steven Spielberg, 2006: The Prestige Christopher Nolan, 2006: The Departed, Martin Scorsese 2007: Into the Wild, Sean Penn 2008: The Dar…
tagged with: nested-loops
score: -1
tagged with: sorting
answer count: 2

http://stackoverflow.com/comment/92230449
score: 1
comment on: http://stackoverflow.com/q/52649186
has text: `foo` is a class, `foo()` is an instance. You seems to mix those notions.
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/52730667
type: Tag
tag name: pdf
tags question: http://stackoverflow.com/q/52683133
tags question: http://stackoverflow.com/q/52622317
tags question: http://stackoverflow.com/q/52637585

http://stackoverflow.com/q/52662585
type: Question
has comment: http://stackoverflow.com/comment/92256431
accepted answer: http://stackoverflow.com/a/52662819
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92256721
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: CSV to JSON conversion for nested records
has comment: http://stackoverflow.com/comment/92255375
has body: I am trying to convert records available in the csv file into JSON format so that it can be consumed by the REST Webservice. Sample Input File : Id,LineNo,Amt,ReceivedDt,FromDt,ToDate 123545,1,1000.00,2019-02-01T00:00:00,2019-02-01T00:00:00,2019-02-01T00:00:00 123545,2,200.00,2019-02-01T00:00:00,2019-02-01T00:00:00,2019-02-01T00:00:00 Expected output : { "gfsAuthData": [ { "Id" : "123545", "LineNo" : 1, "Amt" : "1000.00", "ReceivedDt" : "2019-02-01T00:00:00", "FromDt" : "2019-02-01T00:00:00", "ToDate" : "2019-02-01T00:00:00" }, { "Id" : "123545", "LineNo" : 2, "Amt" : "2000.00", "ReceivedDt" : "2019-02-01T00:00:00", "FromDt" : "2019-02-15T00:00:00", "ToDate" : "2019-02-15T00:00:00" } ] } What modifications should I do in my code to achieve about output? Code : import json,csv with open('Test.csv') as f: inputfile = csv.DictReader(f) for row in inputfile : print(json.dumps(row, indent=4)) Code Output { "ToDate": "2019-02-01T00:00:00", "ReceivedDt": "2019-02-01T00:00:00", "Id": "123545", "LineNo": "1", "Amt": "1000.00", "FromDt": "2019-02-01T00:00:00" } { "ToDate": "2019-02-01T00:00:00", "ReceivedDt": "2019-02-01T00:00:00", "Id": "123545", "LineNo": "2", "Amt": "200.00", "FromDt": "2019-02-01T00:00:00" }
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52662819
has comment: http://stackoverflow.com/comment/92256411
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/52642417
answer count: 1
has body: I am trying to create a Multiclass Text Classifier as explained here. However, my code is breaking at line: NB_pipeline.fit(X_train, train[category]) Below is the error which I am getting: File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322) I tried to find out what train[category] returns and I got same error. 1) X_train is a dataframe with one column and contains customer feedback. 2) train is a dataframe with two columns; first column contains customer review(same as X_train) and second column contains one of the 5 categories (Systems Error, Proactive Communication, Staff Behaviour, Website Functionalities, Others). 3) category is one of the above mentioned categories. Below is the sample train dataframe: Index Feedback Category 0 While making payment got system error. System error Staff behaviour was good at hotel 1 While making payment got system error. Staff Behaviour Staff behaviour was good at hotel
accepted answer: http://stackoverflow.com/a/52701508
favorite count: 0
tagged with: multiclass-classification
has comment: http://stackoverflow.com/comment/92324418
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: text-classification
type: Question
has answer: http://stackoverflow.com/a/52701508
has title: Multiclass Text Classification in Python
downvote count: 0

http://stackoverflow.com/comment/92298662
score: 0
type: QuestionComment
has text: Please take a moment to [format](https://stackoverflow.com/editing-help#comment-formatting) your code, and possibly provide us with a [MCVE]
type: Comment
comment on: http://stackoverflow.com/q/52685557

http://stackoverflow.com/comment/92349848
has text: @Julien yeah if you have the division operator but usually I see 12/3*2 as 12*(1/3)*2 so order didn't seem to matter for me. You are right I guess.
type: Comment
comment on: http://stackoverflow.com/q/52711556
type: QuestionComment
score: 0

http://stackoverflow.com/a/52720132
type: Answer
has body: My guess is that the first time you run it the interpreter does not rescan the modules so the package is installed but the interpreter is not aware of it. You must restart the interpreter. Maybe reloading the sys.path could do the job - see How to refresh sys.path?: import importlib, site importlib.reload(site) although reload is frowned upon for good reason and maybe simpler is to restart the interpreter - or alternatively directly add the new pandas and numpy dirs to sys.path although starts getting dirty
answers question: http://stackoverflow.com/q/52718366
score: 0

http://stackoverflow.com/comment/92410709
comment on: http://stackoverflow.com/a/52730513
type: AnswerComment
has text: Rahlf, as you have helped me a lot already, I will request some more. In case we do not want to remove the second occurences in a group but rather assign a value different from the first occurence, how can we implement that?
score: 0
type: Comment

http://stackoverflow.com/comment/92264170
has text: True! But they don't need to. They terminate autonomously.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52666736
type: Comment

http://stackoverflow.com/comment/92216738
type: AnswerComment
comment on: http://stackoverflow.com/a/52641941
type: Comment
has text: and python -v ?
score: 0

http://stackoverflow.com/a/52741343
has comment: http://stackoverflow.com/comment/92454665
downvote count: 0
answers question: http://stackoverflow.com/q/52740014
score: 1
has comment: http://stackoverflow.com/comment/92429119
type: Answer
has body: If the names are of varying lengths and you dont want to just remove a set number of spaces between them you can search for blank characters to find where sname begins and name ends: # open file in "read" mode fobj_in = open("85488_66325_R85V54.txt", "r") # use readlines to create a list, each member containing a line of 85488_66325_R85V54.txt lines = fobj_in.readlines() # For each line search from the end backwards for the first " " char # when this char is found create first_name which is a list containing the # elements of line from here onwards and a second list which is the elements up to # this point. Then search for a non " " char and remove the blank spaces. # remaining_line and first_name can then be concatenated back together using # + with the desired number of spaces between then (in this case 12). for line_number, line in enumerate(lines): first_name_found = False new_line_created = False for i in range(len(line)): if(line[-i] is " " and first_name_found is False): first_name = line[-i+1:] remaining_line = line[:-i+1] first_name_found = True for j in range(len(remaining_line)): if(remaining_line[-j-1] is not " " and new_line_created == False): new_line = remaining_line[0:-j]+ " "*12 + first_name new_line_created = True lines[line_number] = new_line then just write lines to 85488_66325_R85V54.txt.
upvote count: 1
has comment: http://stackoverflow.com/comment/92467868

http://stackoverflow.com/q/52656336
score: 0
answer count: 2
tagged with: user-interface
type: UnansweredQuestion
tagged with: python
has title: Is it possible to grab a label variable and put into list with tkinter
has answer: http://stackoverflow.com/a/56115690
tagged with: tkinter
has answer: http://stackoverflow.com/a/52657525
type: Question
has body: I've created a temperature converter programme in which the calculated temperature from an entry widget gets displayed in a separate label, what I need to do is to grab that converted variable and put it into a list. I think that making a connected entry widget to the label widget would work where they are connected so I could grab the variable using the .get method but that would look awfully messy. Is there any other way I could proceed with this? This is my first post and I am a beginner in Python, very sorry if the code looks messy and if I included too much code. data = [] tempVal = "Celcius" def store_temp(sel_temp): global tempVal tempVal = sel_temp class Calculator: def __init__(self, num_a, num_b): self.num_a= num_a self.num_b = num_b def convert(self): if tempVal == 'Fahrenheit': return float((float(self.num_a) - 32)* 5 / 9) if tempVal == 'Celcius': return float((float(self.num_a) * 9/ 5) + 32) def display_add(entry_numa,entry_numb,label_answer): #get the value from entry_numa num_a = entry_numa.get() num_b = entry_numb.get() num_a = str(num_a) num_b = str(num_b) #create an object global data calc = Calculator(num_a,num_b) label_answer['text'] = calc.convert() data += [calc] def calc_history(): global data #creat e another window window_calc_list = Tk() window_calc_list.geometry("400x200") #create a listbox listbox_calc_list = Listbox(window_calc_list, width= 300) listbox_calc_list.pack() listbox_calc_list.insert(END, "list of data") for info in data: listbox_calc_list.insert(END, str(info.num_a) + " " + str(info.num_b) + " " ) window_calc_list.mainloop() def main(): window = Tk() window.geometry("500x150") validate_letter = window.register(only_letters) validate_nb = window.register(only_numbers_max_3) label = Label(window, width = 30, background = 'lightblue', text='enter temperature, only numbers') label.grid(row=0, column=0) entry_numa = Entry(window, width = 30, validate="key", validatecommand=(validate_nb, '%d', '%P')) entry_numa.grid(row = 0, column…

http://stackoverflow.com/a/52697345
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52697260
has body: This is kind of subset sum problem. It might be solved with dynamic programming. To make data suitable for subset sum formulation, one could make a list of source data together with negated data elements and provide checking that only one element from pair (x,-x) takes part in sum formation (for example, using binary masks). +limit for minimal number of used elements = 2

http://stackoverflow.com/comment/92376633
type: QuestionComment
has text: Can you upload your csv file somewhere to test it with pandas, i'm sure pandas will sort it out.
score: 0
comment on: http://stackoverflow.com/q/52725076
type: Comment

http://stackoverflow.com/comment/92398825
score: 0
has text: Thank you. So I understand there should be another parsing function and use xpaths according to the form request.Any best practices i should follow would be good to know.
type: AnswerComment
comment on: http://stackoverflow.com/a/52721540
type: Comment

http://stackoverflow.com/q/52746418
type: AnsweredQuestion
has title: sys.argv contains '-c', but not the script. Why?
score: 1
has comment: http://stackoverflow.com/comment/92417646
upvote count: 1
has comment: http://stackoverflow.com/comment/92417593
type: Question
tagged with: command-line-arguments
has comment: http://stackoverflow.com/comment/92418069
has comment: http://stackoverflow.com/comment/92417626
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52746510
has body: I'm just curious about the sys.argv behavior I find strange and inconsistent. I expected sys.argv to only contain the script arguments (not the arguments that are parsed by the python3 executable). In practice, I see that sys.argv contains the -c argument intended for python3. What surprises me then is that the next argument - the script body - is missing. I expect either 2 arguments or 4, but not 3. What's the logic behind this? $ python3 -c 'import sys;print(sys.argv)' 1 2 ['-c', '1', '2'] Update: Ok. I got it. This only happens with the -c argument and not other arguments: $ python3 -b -c 'import sys;print(sys.argv)' -d 1 2 ['-c', '-d', '1', '2'] I still find it confusing and with that in the inline script case the argv[0] would contain the script text or -c &lt;script text&gt; or python3 -c &lt;script text&gt; P.S. Here is the script that initially confused me: python3 -c ' import argparse import sys parser = argparse.ArgumentParser() print(parser.parse_known_args(sys.argv)) ' -a 1 -b 2 -c 3 (Namespace(), ['-c', '-a', '1', '-b', '2', '-c', '3']) I was surprised to see the first -c in the output. Turns out you should not just pass argv to parse_known_args.
favorite count: 0
linked to: http://stackoverflow.com/q/2050961
has comment: http://stackoverflow.com/comment/92417735
accepted answer: http://stackoverflow.com/a/52746510
tagged with: python
has comment: http://stackoverflow.com/comment/92417518

http://stackoverflow.com/a/52711486
has body: Here's your termination condition: while (lo &lt;= hi): And here's where lo and hi can possibly change values: lo = mid ... hi = mid The logical conclusion is that, if this code loops enough times, you'll end up with lo == hi. mid will then be set to the average of the two, which is equal to both of them, and that's where all three variables will stay. And as such, the loop will not terminate. There are two possible solutions: either change the way you're reassigning lo or hi, or change the termination condition to &lt; instead of &lt;=.
score: 2
answers question: http://stackoverflow.com/q/52711429
has comment: http://stackoverflow.com/comment/92351313
downvote count: 0
has comment: http://stackoverflow.com/comment/92352656
upvote count: 2
has comment: http://stackoverflow.com/comment/92349249
type: Answer

ssh
tags question: http://stackoverflow.com/q/52693273
tags question: http://stackoverflow.com/q/52665890
tags question: http://stackoverflow.com/q/52621902
tags question: http://stackoverflow.com/q/52632693
tags question: http://stackoverflow.com/q/52613455
tags question: http://stackoverflow.com/q/52713682
tags question: http://stackoverflow.com/q/52651397
type: Tag
tag name: ssh

http://stackoverflow.com/q/52676280
has answer: http://stackoverflow.com/a/52676399
has body: I am creating a dice program that must roll the dice a certain amount of times and append those rolls to a list. I am trying to figure out how to add commas in between each item of the list. This is the code that I have so far: listRolls = [] def listPrint(): for i, item in enumerate(listRolls): if (i+1)%13 == 0: print(item) else: print(item,end=' ')
type: Question
has comment: http://stackoverflow.com/comment/92281925
linked to: http://stackoverflow.com/q/44778
possible better answer: http://stackoverflow.com/a/52676330
has title: Trying to add a comma in between each value of my list python
favorite count: 0
upvote count: 5
answer count: 3
downvote count: 3
accepted answer: http://stackoverflow.com/a/52676358
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52676330
has answer: http://stackoverflow.com/a/52676358

http://stackoverflow.com/comment/92279681
score: 0
type: AnswerComment
has text: Wrong in the sense that it does not provide the output specified by the OP for the given `A` and `n`.
type: Comment
comment on: http://stackoverflow.com/a/52674887

http://stackoverflow.com/a/52653324
answers question: http://stackoverflow.com/q/52650583
score: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/52650583
has comment: http://stackoverflow.com/comment/92240697
has comment: http://stackoverflow.com/comment/92240622
has body: No, there is no faster method available for dictionaries. That's because the performance cost is all in processing each item from the iterator, computing its hash and slotting the key into the dictionary data hash table structures (including growing those structures dynamically). Executing the dictionary comprehension bytecode is really insignificant in comparison. dict(zip(it, it)), {k: k for k in it} and dict.fromkeys(it) are all close in speed: &gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; tests = { ... 'dictcomp': '{k: k for k in it}', ... 'dictzip': 'dict(zip(it, it))', ... 'fromkeys': 'dict.fromkeys(it)', ... } &gt;&gt;&gt; timings = {n: [] for n in tests} &gt;&gt;&gt; for magnitude in range(2, 8): ... it = range(10 ** magnitude) ... for name, test in tests.items(): ... peritemtimes = [] ... for repetition in range(3): ... count, total = Timer(test, 'from __main__ import it').autorange() ... peritemtimes.append(total / count / (10 ** magnitude)) ... timings[name].append(min(peritemtimes)) # best of 3 ... &gt;&gt;&gt; for name, times in timings.items(): ... print(f'{name:&gt;8}', *(f'{t * 10 ** 9:5.1f} ns' for t in times), sep=' | ') ... dictcomp | 46.5 ns | 47.5 ns | 50.0 ns | 79.0 ns | 101.1 ns | 111.7 ns dictzip | 49.3 ns | 56.3 ns | 71.6 ns | 109.7 ns | 132.9 ns | 145.8 ns fromkeys | 33.9 ns | 37.2 ns | 37.4 ns | 62.7 ns | 87.6 ns | 95.7 ns That's a table of the per-item cost for each technique, from 100 to 10 million items. The timings go up as the additional cost of growing the hash table structures accumulate. Sure, dict.fromkeys() can process items a little bit faster, but it's not an order of magnitude faster than the other processes. It's (small) speed advantage does not come from being able to iterate in C here; the difference lies purely in not having to update the value pointer each iteration; all keys point to the single value reference. zip() is slower because it builds additional objects (creating a 2-item tuple for each key-value pair is n…
downvote count: 1
has comment: http://stackoverflow.com/comment/92240492
upvote count: 10
type: AcceptedAnswer

http://stackoverflow.com/q/52663756
has comment: http://stackoverflow.com/comment/92328776
favorite count: 0
has title: Not able to query using gremlinpython
tagged with: gremlin-server
answer count: 1
tagged with: python
score: 6
has comment: http://stackoverflow.com/comment/92343425
has comment: http://stackoverflow.com/comment/92377186
tagged with: janusgraph
has body: I'm using gremlinpython to access the data in Janusgraph, but it is throwing an exception whereas the data is accessible from Gremlin shell. Here is the Python code which I'm running remotely: from gremlin_python import statics from gremlin_python.structure.graph import Graph from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection graph = Graph() g = graph.traversal().withRemote(DriverRemoteConnection('ws://&lt;IP&gt;:8182/gremlin','g', username="janusgraph")) print g.V().has('name', 'saturn').next() This is the exception that I'm getting: Traceback (most recent call last): File "test.py", line 10, in &lt;module&gt; print g.V().has('name', 'saturn').next() File "/root/venv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 70, in next return self.__next__() File "/root/venv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 43, in __next__ self.traversal_strategies.apply_strategies(self) File "/root/venv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 346, in apply_strategies traversal_strategy.apply(traversal) File "/root/venv/lib/python2.7/site-packages/gremlin_python/driver/remote_connection.py", line 143, in apply remote_traversal = self.remote_connection.submit(traversal.bytecode) File "/root/venv/lib/python2.7/site-packages/gremlin_python/driver/driver_remote_connection.py", line 54, in submit results = result_set.all().result() File "/root/venv/lib/python2.7/site-packages/concurrent/futures/_base.py", line 462, in result return self.__get_result() File "/root/venv/lib/python2.7/site-packages/concurrent/futures/_base.py", line 414, in __get_result raise exception_type, self._exception, self._traceback KeyError: None Output from the Gremlin shell: gremlin&gt; graph = JanusGraphFactory.open('conf/janusgraph-hbase-es.properties') ==&gt;standardjanusgraph[hbase:[slv-01, slv-02…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92334409
downvote count: 0
has comment: http://stackoverflow.com/comment/92373131
has comment: http://stackoverflow.com/comment/92367133
has comment: http://stackoverflow.com/comment/92321127
has comment: http://stackoverflow.com/comment/92262037
tagged with: gremlin
type: Question
has comment: http://stackoverflow.com/comment/92300645
has answer: http://stackoverflow.com/a/52725985
accepted answer: http://stackoverflow.com/a/52725985
upvote count: 6

variables
tags question: http://stackoverflow.com/q/52737248
tag name: variables
tags question: http://stackoverflow.com/q/52670222
tags question: http://stackoverflow.com/q/52629354
type: Tag
tags question: http://stackoverflow.com/q/52717452
tags question: http://stackoverflow.com/q/52640425
tags question: http://stackoverflow.com/q/52610231
tags question: http://stackoverflow.com/q/52739311
tags question: http://stackoverflow.com/q/52649186
tags question: http://stackoverflow.com/q/52649343
tags question: http://stackoverflow.com/q/52622237
tags question: http://stackoverflow.com/q/52747036
tags question: http://stackoverflow.com/q/52665271

http://stackoverflow.com/q/52742283
downvote count: 0
tagged with: scikit-learn
tagged with: keras
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/60441764
linked to: http://stackoverflow.com/q/56824968
has comment: http://stackoverflow.com/comment/110552391
has answer: http://stackoverflow.com/a/52742732
type: UnansweredQuestion
upvote count: 1
has body: as explained in https://keras.io/models/model, Keras' fit function x can be Numpy array of training data (if the model has a single input), or list of Numpy arrays (if the model has multiple inputs). If input layers in the model are named, you can also pass a dictionary mapping input names to Numpy arrays. but it doesn't seem to be possible with sklearn.model_selection.GridSearchCV fit. Is that true? Is there any workaround? Thanks!
type: Question
score: 1
tagged with: grid-search
has title: fit: passing multiple inputs with sklearn.model_selection.GridSearchCV
answer count: 2

http://stackoverflow.com/a/52672402
upvote count: 1
answers question: http://stackoverflow.com/q/52672369
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52672369
type: Answer
has body: Define a wrapper function; let compare do its thing (the actual comparison), and let another function take care of calling input and passing the response to compare. def do_comparison(): year = int(input("Enter a year to compare against: ")) return compare(year)
score: 1

http://stackoverflow.com/comment/92329931
score: 1
comment on: http://stackoverflow.com/a/52700986
has text: Yes, but if you want to only insert one parameter _per line_ then you do _not_ add as many `?` as there are items in your outer list. What if I wanted to insert 10,000 rows? Should I supply 10K `?`?
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52618490
score: 0
has body: I'd like to (efficiently) evaluate a Gaussian mixture model (GMM) over an (n,d) list of datapoints, given the GMM parameters ($\pi_k, \mu_k, \Sigma_k$). I can't find a way to do this using standard sklearn or scipy packages. EDIT: assume there is n datapoints, dimension d so (n,d), and GMM has k components, so for example the covariance matrix of the k-th component, \Sigma_k, is (d,d), and altogether \Sigma is (k,d,d). For example, if you first fit a GMM in sklearn, you can call score_samples, but this only works if I'm fitting to data. Or, in scipy you can run a for-loop over multivariate_normal.pdf with each set of parameters, and do a weighted sum/dot product, but this is slow. Checking the source code of either was not illuminating (for me). I'm currently hacking something together with n-d arrays and tensor dot products .. oy .. hoping someone has a better way?
has comment: http://stackoverflow.com/comment/92171169
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: scipy
type: Question
tagged with: numpy
has title: Efficient Gaussian mixture evaluation
tagged with: gmm
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/92171666

http://stackoverflow.com/comment/92454468
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52742470
has text: @5th My apologies, Edited it.

http://stackoverflow.com/a/52747106
answers question: http://stackoverflow.com/q/52747073
has body: You are redefining self.z and self.y as None after you define them with func. Get rid of the self.z and self.y in __init__ class Test: def __init__(self, l): self.l = l self.func(self.l) # or I tried self.func(l) # These are redefining the variables, comment out # self.z = None # self.y = None def func(self, l): self.z = l self.y = 123
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92418931
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52747073

http://stackoverflow.com/a/52654418
score: 0
type: Answer
has body: This is done using the tree control's selection events. I would bind to those and when they get fired, you would update the right side of the display. You can usually do this by either resetting the widgets on the right with new data, or by hiding / destroying those widgets and placing new ones in their place. I have an XML editor that you can look at that might help you see how this sort of thing could be done: https://github.com/driscollis/boomslang Unfortunately there is a lot of code that would be needed to fully demonstrate the concept that you are referring to.
answers question: http://stackoverflow.com/q/52652754

http://stackoverflow.com/a/52728291
answers question: http://stackoverflow.com/q/52728139
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/52728139
has comment: http://stackoverflow.com/comment/92382029
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/92382558
type: AcceptedAnswer
has body: For a Series you can use astype on the part only which is notnull without need to re-replace the NaNs df = pd.DataFrame([1, np.nan, 'String']) df[df.notnull()] = df[df.notnull()].astype(str) As remarked in the comments, for a DataFrame you can use df.where(df.isna(), df.astype(str))

http://stackoverflow.com/a/52676639
downvote count: 0
has comment: http://stackoverflow.com/comment/92282372
has comment: http://stackoverflow.com/comment/92282636
has comment: http://stackoverflow.com/comment/92282744
type: Answer
has body: You want datetime.timedelta() import datetime import time old_time = datetime.datetime.now() time.sleep(20) new_time = datetime.datetime.now() # The below line returns a 'timedelta' object. delta = new_time - old_time print('{} seconds have passed.'.format(delta.total_seconds())) # or print( '{} days, {} hours, {} minutes, {} seconds passed.'.format( delta.days, delta.seconds//3600, (delta.seconds//60)%60, int(delta.total_seconds()%60))) I believe it also exists for just date and time modules as well.
score: 1
answers question: http://stackoverflow.com/q/52676374
upvote count: 1

http://stackoverflow.com/comment/92200940
comment on: http://stackoverflow.com/q/52633803
score: 0
type: Comment
type: QuestionComment
has text: Why do you expect lossless JPGs when your code explicitly creates PNGs? And IIRC, PNG is always lossless.

http://stackoverflow.com/q/52636288
favorite count: 0
has answer: http://stackoverflow.com/a/52636445
has answer: http://stackoverflow.com/a/52636390
accepted answer: http://stackoverflow.com/a/52636390
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Fastest way to build numpy array from sum of coordinates
score: 1
type: Question
duplicate of: http://stackoverflow.com/q/36863404
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52636445
answer count: 2
has body: Say I have a list (or numpy.array) of (row, col) coordinates, e.g.: [(0, 0), (1, 1), (0, 0)] I'd like to build the 2x2 array like this: 2 0 0 1 where each of the listed coordinates is counted and put in the right place in the array. I.e. (0, 0) appears twice, so a[0, 0] == 2. I know I can build this by iterating and poking the array for each element, but I wanted to check if there is any support in numpy regarding building the array like this, mostly for performance reasons. Can you point me in the right direction if so? Also, is there a reduce-like functionality along the above lines? I.e. do new = f(acc, el) instead of new = acc + el.
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/92206356
linked to: http://stackoverflow.com/q/36863404

http://stackoverflow.com/comment/92224827
comment on: http://stackoverflow.com/q/52646316
score: 0
type: Comment
type: QuestionComment
has text: You _could_ use various tools to reformat the file, converting each `;` to a newline char. But I suspect that's _not_ permitted for this exercise. You're supposed to read that line, and split it up properly with your Python code. Do you know how to split `"username:password;username1:password1;username2:password2"` into a list of 3 strings, splitting on the semicolons?

http://stackoverflow.com/a/52636919
downvote count: 1
answers question: http://stackoverflow.com/q/52636846
has comment: http://stackoverflow.com/comment/92206935
upvote count: 4
has body: It could be that this data stream is JSON5, in which case there's a parser for that: https://pypi.org/project/json5/ This situation can be alleviated by a regex substitution that looks for ", }, and replaces it with " }, allowing for any amount of whitespace between the quotes, comma and close-curly. &gt;&gt;&gt; import re &gt;&gt;&gt; s = '{ "key1": "value1", "key2": "value2", }' &gt;&gt;&gt; re.sub(r"\"\s*,\s*\}", "\" }", s) '{ "key1": "value1", "key2": "value2" }' Giving: &gt;&gt;&gt; import json &gt;&gt;&gt; s2 = re.sub(r"\"\s*,\s*\}", "\" }", s) &gt;&gt;&gt; json.loads(s2) {'key1': 'value1', 'key2': 'value2'} EDIT: as commented, this is not a good practice unless you are confident your JSON data contains only simple words, and this change is not corrupting the data-stream further. As I commented on the OP, the best course of action is to repair the up-stream data source. But sometimes that's not possible.
score: 3
type: Answer

http://stackoverflow.com/comment/137491674
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52732077
has text: @MathematicsBeginner: We're not calling `free` on a Python object, though. We're calling `free` on a buffer allocated by the questioner's C code, not by the Python memory management system. It needs to be freed in whatever way is appropriate for how the questioner's C code allocated it.

http://stackoverflow.com/q/52646107
tagged with: forms
upvote count: 1
answer count: 1
has body: My HTML template has a form which looks like this on the browser: I want to get the string "oranges" in Python when the user presses the "Select" button next to "oranges". Here's how my form looks like: {% for product in [["A100", "oranges"], ["A101", "apples"]] %} {{product[1]}} {% include select_button ignore missing %} {% endfor %} Trying request.form["A100"] returns a Bad Request error. Is there a way to get such tr tags values?
tagged with: flask
tagged with: tr
favorite count: 0
tagged with: python
downvote count: 0
has title: How to get HTML tags when pressing button in Flask?
score: 1
accepted answer: http://stackoverflow.com/a/52646516
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52646516

http://stackoverflow.com/q/52733452
answer count: 1
has answer: http://stackoverflow.com/a/52737459
tagged with: scikit-learn
tagged with: recommendation-engine
has body: I am trying to implement a recommender system to users based on their rating. I think the most common one. I was reading alot and shortlisted Surprise, a python-scikit based recommender systems. While am able to import data and run prediction, its not exactly as I would want it. Right now what I have: I can pass a user_id, item_id and rating and get the probability of that user giving the rating I passed. What I really want to do: Pass a user_id and in return get a list of items that would be potentially liked/rated highly by that user based on the data. from surprise import Reader, Dataset from surprise import SVD, evaluate # Define the format reader = Reader(line_format='user item rating timestamp', sep='\t') # Load the data from the file using the reader format data = Dataset.load_from_file('./data/ecomm/e.data', reader=reader) # Split data into 5 folds data.split(n_folds=5) algo = SVD() # Retrieve the trainset. trainset = data.build_full_trainset() algo.fit(trainset) //Inputs are: user_id, item_id &amp; rating. print algo.predict(3, 107, 1) Sample lines from data file. First column is user_id, 2nd is item id, 3rd is rating and then timestamp. 196 242 3 881250949 186 302 3 891717742 22 377 1 878887116 244 51 2 880606923 166 346 1 886397596 298 474 4 884182806 115 265 2 881171488 253 465 5 891628467 305 451 3 886324817 6 86 3 883603013
tagged with: python
tagged with: collaborative-filtering
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52737459
type: Question
has title: Basic filtering of data based on user & item in Python SciKit
score: 0

http://stackoverflow.com/comment/92437592
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52740474
type: Comment
has text: Are you not overwriting the old images with the new ones, by having the same file-name at `filesink` ? Can this be a reason for the scrambled image file?

http://stackoverflow.com/comment/92379688
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52726959
has text: please read this _carefully_: https://stackoverflow.com/help/mcve
type: Comment

http://stackoverflow.com/q/52725314
upvote count: 1
type: Question
tagged with: numpy
answer count: 1
downvote count: 0
has title: np.loadtxt datetime error: data ValueError: time data ' 2018-10-01 11:29:40.475195' does not match format '%Y-%m-%d %H:%M:%S.%f'
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52725956
has body: I have a .txt file with following data: 2018-10-01 11:29:31.147695, -1.006520e-01, 2018-10-01 11:29:40.475195, 1.021820e-01, 2018-10-01 11:29:42.835195, -2.164020e-01 now I want to load the .txt with np.loadtxt. I have: convertfunc =lambda x : dt.datetime.strptime(x.decode("ascii"), '%Y-%m-%d %H:%M:%S.%f') min_max = np.loadtxt("file.txt", delimiter=',', converters={0: convertfunc, 2: convertfunc, 4: convertfunc}) following error occurs: convertfunc =lambda x : dt.datetime.strptime(x.decode("ascii"), '%Y-%m-%d %H:%M:%S.%f') min_max = np.loadtxt(r"C:\Users\mdk\Desktop\93307\location_1.txt", delimiter=',', converters={0: convertfunc, 2: convertfunc, 4: convertfunc}) can somebody help me with a solution?
score: 1
has comment: http://stackoverflow.com/comment/92376034

http://stackoverflow.com/comment/92401767
score: 1
has text: thats because your X Data has four Dimensions (Columns) and a scatter plot is two dimensional. your scatter plot doesnt make any sense if you reshape your data like you did. The way to go here would be four scatter plots - one X Column and your Y column in each plot.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52737775

http://stackoverflow.com/q/52619368
score: -1
has comment: http://stackoverflow.com/comment/92173541
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/52661863
favorite count: 0
has comment: http://stackoverflow.com/comment/92173512
has body: Task: I have a task to match the strings in my first column of csv file to log files, if it exist then put the matched string in the third column otherwise put "undetected" Contents of my log file -trendx.log Contents of my csv file - sha1_vsdt.csv Expected Output: Code: So far I have used this concept using pandaframe and numpy, just followed somebody's advice import numpy as np import pandas as pd import csv #Log data into dataframe using genfromtxt logdata = np.genfromtxt("trendx.log", delimiter=" ",invalid_raise = False,dtype=str, comments=None,usecols=np.arange(0,24)) logframe = pd.DataFrame(logdata) #Dataframe trimmed to use only SHA1, PRG and IP df2=(logframe[[10,14,15]]).rename(columns={10:'SHA1', 14: 'PRG',15:'IP'}) #sha1_vsdt data into dataframe using read_csv df1=pd.read_csv("sha1_vsdt.csv",delimiter=r"|",error_bad_lines=False,engine = 'python',quoting=3) #Using merge to compare the two CSV df = pd.merge(df1, df2, left_on='SHA-1', right_on='SHA1', how='left').replace(np.nan, 'undetected', regex=True) print df'SHA-1','VSDT','PRG','IP' Then I'm having this error: Warning (from warnings module): File "C:\Users\Administrator\Desktop\OJT\match.py", line 6 logdata = np.genfromtxt("trendx.log", delimiter=" ",invalid_raise = False,dtype=str, comments=None,usecols=np.arange(0,24)) ConversionWarning: Some errors were detected ! Line #1 - #113 (got 1 columns instead of 24) Traceback (most recent call last): File "C:\Users\Administrator\Desktop\OJT\match.py", line 9, in &lt;module&gt; df2=(logframe[[10,14,15]]).rename(columns={10:'SHA1', 14: 'PRG',15:'IP'}) File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2682, in __getitem__ return self._getitem_array(key) File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2726, in _getitem_array indexer = self.loc._convert_to_indexer(key, axis=1) File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 1327, in _convert_to_indexer .format(mask=objarr[mask])) KeyError: '[10 14 15] not in ind…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92173378
tagged with: python
has title: How to detect if a string in csv file exist in log file?
upvote count: 0
has comment: http://stackoverflow.com/comment/92254225
type: Question
has answer: http://stackoverflow.com/a/52620397

http://stackoverflow.com/q/52612651
linked to: http://stackoverflow.com/q/35494331
tagged with: generics
favorite count: 0
has title: Pythonnet delegate method with generics not being called
has body: I'm using a Python script with Pythonnet to drive a C# library. This library fires delegate methods on certain events. I'm registering the delegate method but it isn't being called. The method in question is defined as event EventHandler&lt;EventArgs&gt; SystemInformationUpdated The funny thing is that another method with a custom class return value IS being called, defined as event EventHandler&lt;PeripheralDiscoveredEventArgs&gt; PeripheralDiscovered When I run this code with IronPython everything works fine, so I think it's a PythonNET issue. My code is like this: from System import EventHandler, EventArgs (...) dc = EventHandler[PeripheralDiscoveredEventArgs](centralOnPeripheralDiscovered_callback) central.PeripheralDiscovered += dc iuc = EventHandler[EventArgs](systemInformationUpdated_callback) central.SystemInformationUpdated += iuc The systemInformationUpdated_callback is NOT being executed while the centralOnPeripheralDiscovered_callback function is being called. I also tried the following code: from System import EventArgs (...) EventHandler = getattr(System, 'EventHandler`1') dc = EventHandler[PeripheralDiscoveredEventArgs](centralOnPeripheralDiscovered_callback) central.PeripheralDiscovered += dc EventHandler = getattr(System, 'EventHandler`1') iuc = EventHandler[EventArgs](systemInformationUpdated_callback) central.SystemInformationUpdated += iuc It didn't work either (as I believe the bug was corrected in PythonNET 2.2). Using the console I get dc &lt;0, Culture=neutral, PublicKeyToken=null]]&gt; iuc &lt;0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]&gt; The iuc object Target property is Target &lt;__System_EventHandler`1\[\[System_EventArgs\, mscorlib\, Version=4_0_0_0\, Culture=neutral\, PublicKeyToken=b77a5c561934e089\]\]Dispatcher&gt; __System_EventHandler`1\[\[System_EventArgs\, mscorlib\, Version=4_0_0_0\, Culture=neutral\, PublicKeyToken=b77a5c561934e089\]\]Dispatcher I also looked at Python for .NET readme:Using Generics, Unable to use G…
type: UnansweredQuestion
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/114746998
has comment: http://stackoverflow.com/comment/114734814
type: Question
tagged with: c#
tagged with: delegates
answer count: 1
downvote count: 0
tagged with: python.net
upvote count: 3
has answer: http://stackoverflow.com/a/52651060

http://stackoverflow.com/q/52711149
favorite count: 0
has comment: http://stackoverflow.com/comment/92348687
tagged with: python
has comment: http://stackoverflow.com/comment/92348706
tagged with: prediction
answer count: 0
type: UnansweredQuestion
tagged with: regression
has comment: http://stackoverflow.com/comment/92348905
type: Question
has body: I'm working on this type of data: Date Of Stop count 0 2012-01-01 180 1 2013-01-01 348 2 2014-02-01 537 3 2015-02-01 498 4 2016-03-01 719 5 2017-03-01 406 And trying to make a prediction for the dates I don't have data (count) This is my code where I divide dates to first 11 months and the 12th month Then I'm trying based on the first 11 Month define what can I get on 12th month dfhalf = groupbyClass[(groupbyClass['Date Of Stop'] &gt; '01/01/2012') &amp; (groupbyClass['Date Of Stop'] &lt; '12/01/2012')] dfpred = groupbyClass[(groupbyClass['Date Of Stop'] &gt;= '12/01/2012') &amp; (groupbyClass['Date Of Stop'] &lt; '01/01/2013')] from sklearn.linear_model import LinearRegression X = dfhalf['Date Of Stop'] # put dates in here y = dfhalf['count'] # put knowh in here model = LinearRegression() model.fit(X, y) X_predict = dfpred['Date Of Stop'] # dates for prediction y_predict = model.predict(X_predict) This unfortunately throws at me something like this: ValueError: Expected 2D array, got 1D array instead: array=['2012-01-02T00:00:00.000000000' '2012-01-03T00:00:00.000000000' '2012-01-04T00:00:00.000000000' '2012-01-05T00:00:00.000000000' '2012-01-06T00:00:00.000000000' '2012-01-07T00:00:00.000000000' '2012-01-08T00:00:00.000000000' '2012-01-09T00:00:00.000000000' '2012-01-10T00:00:00.000000000' '2012-01-11T00:00:00.000000000' .... Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. I tried to use different forms of .reshape(-1, 1 and (1, -1) when I define my X or y. But no luck. I don't understand what I need to do and why.
linked to: http://stackoverflow.com/q/48518471
has comment: http://stackoverflow.com/comment/92348593
score: 1
has comment: http://stackoverflow.com/comment/92349211
upvote count: 1
has comment: http://stackoverflow.com/comment/92348948
downvote count: 0
linked to: http://stackoverflow.com/q/29748717
has title: Making prediction with Python and linear regression

http://stackoverflow.com/comment/92387866
type: QuestionComment
comment on: http://stackoverflow.com/q/52716785
score: 0
has text: I just used CLAHE in opencv for processing (because I am a beginner), and the results I am looking for are already attached to the problem.
type: Comment

http://stackoverflow.com/comment/92210681
score: 0
type: AnswerComment
type: Comment
has text: fixed it, the file was actually in another folder but in downloads. I moved the files out of the folder into the downloads and it worked.
comment on: http://stackoverflow.com/a/52638815

http://stackoverflow.com/a/52729196
answers question: http://stackoverflow.com/q/52727814
has body: If you use TensorFlow as your Keras backend, you could leverage tf.distributions to compute the CDF of the normal distribution: from tensorflow.distributions import Normal def probit(x): normal = Normal(loc=0., scale=1.) return normal.cdf(x)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52727814
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/52645618
tagged with: word2vec
upvote count: 1
type: Question
score: 1
has body: I have trained word2Vec model on a huge corpus using gensim. Then i have tried to find gender bias in the word2vec model. After this I am neutralizing the bias for few specific professional words. Referred the following link for gender de-biasing https://datascience-enthusiast.com/DL/Operations_on_word_vectors.html On de-biasing or neutralizing a word, new vector of the specific word is returned. Is it possible to take such new vectors of existing words and retrain the previous model. Please let me know if there are any techniques of doing so. Thanks and Regards AIMC
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92281128
has title: retrain existing word2vec model with new word vectors
tagged with: python
tagged with: gensim
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52636846
has answer: http://stackoverflow.com/a/72468652
has answer: http://stackoverflow.com/a/63555547
tagged with: python
score: 11
upvote count: 11
type: AnsweredQuestion
has title: Python can't parse JSON with extra trailing comma
has answer: http://stackoverflow.com/a/52636881
has answer: http://stackoverflow.com/a/52636887
has answer: http://stackoverflow.com/a/52636861
type: Question
accepted answer: http://stackoverflow.com/a/63555547
has answer: http://stackoverflow.com/a/52636904
possible better answer: http://stackoverflow.com/a/52636881
tagged with: http://stackoverflow.com/tag/json
has body: This code: import json s = '{ "key1": "value1", "key2": "value2", }' json.loads(s) produces this error in Python 2: ValueError: Expecting property name: line 1 column 16 (char 15) Similar result in Python 3: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 16 (char 15) If I remove that trailing comma (after "value2"), I get no error. But my code will process many different JSONs, so I can't do it manually. Is it possible to setup the parser to ignore such last commas?
tagged with: runtime-error
has answer: http://stackoverflow.com/a/52636919
has comment: http://stackoverflow.com/comment/92206933
has comment: http://stackoverflow.com/comment/92206788
downvote count: 0
answer count: 7
favorite count: 0
tagged with: parsing

http://stackoverflow.com/comment/129491923
type: Comment
has text: It's not entirely impossible. For example if your DBMS supports JSON and has a JSON list aggregation function, you could build a JSON list of objects all within the DBMS. In other words, you'd condense the grouped rows into a single row, with a column of JSON.
type: AnswerComment
comment on: http://stackoverflow.com/a/52773549
score: 0

http://stackoverflow.com/a/52609404
type: Answer
has comment: http://stackoverflow.com/comment/92156455
has comment: http://stackoverflow.com/comment/92155367
has comment: http://stackoverflow.com/comment/92155946
has comment: http://stackoverflow.com/comment/92156380
upvote count: 3
has comment: http://stackoverflow.com/comment/92155737
has comment: http://stackoverflow.com/comment/92155526
answers question: http://stackoverflow.com/q/52609146
score: 3
has comment: http://stackoverflow.com/comment/92154682
has comment: http://stackoverflow.com/comment/92155304
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92155232
has comment: http://stackoverflow.com/comment/92156839
has comment: http://stackoverflow.com/comment/92155095
has body: First, you should be connecting to your website... Second, you should use waits you can read about it here the code should look something like: 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 base_url = "https://www.nationalevacaturebank.nl" start_url = "https://www.nationalevacaturebank.nl/vacature/zoeken?query=&amp;location=&amp;distance=city&amp;limit=100&amp;sort=relevance&amp;filters%5BcareerLevel%5D%5B%5D=Starter&amp;filters%5BeducationLevel%5D%5B%5D=MBO" my_xpath = '//*[@id="search-results-container"]/div/div[1]/div[2]/article/job/a' driver = webdriver.Firefox() driver.get(start_url) wait = WebDriverWait(driver, 10) element = wait.until(EC.element_to_be_clickable((By.XPATH, my_xpath))) Edit I order to get all the links of the individual job listing you can create a list of the links and append theme: wait = WebDriverWait(driver, 10) elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="search-results-container"]//article/job/a'))) list_of_links = [] for i in elements: list_of_links.append(i.get_attribute('href')) # print(f"link = {i.get_attribute('href')}") print(list_of_links) Hope this helps you!
accepted answer of: http://stackoverflow.com/q/52609146

http://stackoverflow.com/q/52656929
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52657132
has answer: http://stackoverflow.com/a/52657052
has answer: http://stackoverflow.com/a/52657132
tagged with: python
has title: How to see if column elements swapped in a later row
type: AnsweredQuestion
has body: I've just been asked to help out on this, and I'm not sure I can come up with a piece of code that runs reasonably fast. There are two columns of data: the first is the user id number of a social media user who initiates contact with someone; the second column is the user-id of the person who they initiate contact with. Further, assume that the rows are ordered by time. I wish to see all the user-ids of people who "followed-back" their followers at a later date. This is what I have so far, and it's quite slow. How do I do this without for loops? def myFun2(num): N = df.shape[0] init_follower = df['follower'][num] init_followee = df['followee'][num] for i in range(num+1,N): a = init_followee == df['follower'][i] b = init_follower == df['followee'][i] if a and b: return i df = pd.DataFrame({'follower' : ['a', 'a', 'b'], 'followee' : ['b', 'c', 'a']}) # prints 2 because that's the row where a follows back b for i in range(df.shape[0]): print(myFun2(i))
type: Question
accepted answer: http://stackoverflow.com/a/52657052
score: 4
upvote count: 4
tagged with: numpy
answer count: 2

http://stackoverflow.com/q/52708163
has answer: http://stackoverflow.com/a/52710121
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: amazon-ec2
tagged with: boto3
tagged with: amazon-web-services
type: Question
has body: I am trying to create an EC2 instance using the below code: response = EC2.run_instances( # BlockDeviceMappings=deviceMappings, BlockDeviceMappings=[ { "DeviceName": "/dev/xvdb", "VirtualName": "swap", "Ebs": { "DeleteOnTermination": True, "Encrypted": True, "VolumeType": "standard", "VolumeSize": 16 }, }, ], ImageId=amiId, MaxCount=1, MinCount=1, InstanceType=instance_class, InstanceInitiatedShutdownBehavior='stop', SubnetId=subnet_id, # SecurityGroupIds=security_groups, SecurityGroupIds=['sg-8c2bb6f5','sg-edc49b89'], # TagSpecifications=tagSpecs TagSpecifications=[ { 'ResourceType':'instance', 'Tags':[ { 'Key':'owner', 'Value':'Sanjeev' }, { 'Key':'Name', 'Value':'SanjeevTEST' }, { 'Key':'Environment', 'Value':'PreProduction' }, ] }, ] ) Code works as expected when BlockDeviceMappings, SecurityGroupIds and TagSpecifications are provided in line as above. But, when But, when I read them from a file into a variable and pass the variable, then the command fails with below error: botocore.exceptions.ParamValidationError: Parameter validation failed: Invalid type for parameter TagSpecifications, value: [ { 'ResourceType':'instance', 'Tags':[ { 'Key':'owner', 'Value':'Sanjeev' }, { 'Key':'Name', 'Value':'SanjeevTEST' }, { 'Key':'Environment', 'Value':'PreProduction' }, ] }, ] , type: &lt;type 'str'&gt;, valid types: &lt;type 'list'&gt;, &lt;type 'tuple'&gt; I am storing the device mappings, security groups and tags in a file as we have to create multiple instances and don't want to edit the code whenever we need to create a new instance. How do I resolve this error? Your help will be greatly appreciated. Thanks, Sanjeev
tagged with: python
has title: How to pass device mappings and tag specifications to Boto3 Python run_instances

http://stackoverflow.com/comment/92139984
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52602835
has text: I don't want to have to run your script. Why don't you update your question with the command-line you are using to run your script and post the output that results.

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/52632777
tags question: http://stackoverflow.com/q/52630865
tag name: countvectorizer

http://stackoverflow.com/a/52702296
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52701932
has body: Here's a naïve Pandas loop via pd.DataFrame.apply and pd.Series.value_counts: def max_count(s): return s.value_counts().values[0] res = df[df.apply(max_count, axis=1).le(3)] print(res) A B C D E F G 0 1 4 9 4 6 9 8 3 2 6 9 5 4 4 5 4 2 8 1 9 5 8 9 5 2 2 2 5 6 3 6
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/92218021
score: 0
has text: @yoonghm..No I've installed it by ```python3 -m pip install --user jupyter```
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52642696

http://stackoverflow.com/comment/108954695
has text: Thanks a lot! Sorry came back to this late
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52679951

http://stackoverflow.com/a/52679753
answers question: http://stackoverflow.com/q/52679704
score: 3
accepted answer of: http://stackoverflow.com/q/52679704
type: AcceptedAnswer
downvote count: 0
has body: Use collections.defaultdict: from collections import defaultdict data = [{'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}, {'id': 1, 'name': 'gesiel'}] d = defaultdict(list) for x in data: d[x['id']].append(x) print(d) # defaultdict(&lt;class 'list'&gt;, {1: [{'id': 1, 'name': 'foo'}, {'id': 1, 'name': 'gesiel'}], 2: [{'id': 2, 'name': 'bar'}]})
upvote count: 3
type: Answer

http://stackoverflow.com/q/52727619
answer count: 3
has comment: http://stackoverflow.com/comment/92380479
accepted answer: http://stackoverflow.com/a/52727716
has answer: http://stackoverflow.com/a/52727697
possible better answer: http://stackoverflow.com/a/52727697
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52728606
has comment: http://stackoverflow.com/comment/92380609
type: Question
has body: I have a df that looks like this, dtype is object can not cast to int or float: col1 100 100k 100k-100m 10m 50 How do I replace the k with 000 and the m with 000000 within this column that is type object? Furthermore, once I can replace the k or m how do I replace everything that is not a number with nothing? New df should look like this(not the blank space): col1 100 100000 10000000 50 Tried this code: df.col1 = (df.col1.replace(r'[KM]+$', '', regex=True).astype(float) * \ df.col1.str.extract(r'[\d\.]+([KM]+)', expand=False) .fillna(1) .replace(['K','M'], [10**3, 10**6]).astype(int)) but columns have to be float
has answer: http://stackoverflow.com/a/52727716
has title: How to replace 'k' or 'm' with 000s from object column in dataframe and replace non number values?
upvote count: 1
tagged with: python

http://stackoverflow.com/q/52739336
answer count: 2
downvote count: 0
tagged with: pandas
has title: np.any() alternative if column is different than NaN or 0
has body: I want to check if a column in a Dataframe contains a different value than 0 or NaN. Therefore I tried np.any() but it also returns true if only NaN and 0 are in the column. np.any([0 , np.NaN, 0]) True What it the best way to get an output like this: (type of the column is float64) df = [0 , np.NaN, 18, 0] True df = [0, np.NaN, 0] False Thank you, R
tagged with: nan
favorite count: 0
possible better answer: http://stackoverflow.com/a/52740169
has answer: http://stackoverflow.com/a/52739388
has answer: http://stackoverflow.com/a/52740169
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52739388
type: Question
tagged with: numpy

http://stackoverflow.com/comment/92149315
type: AnswerComment
type: Comment
has text: well that code runs as is. So not sure what you mean
comment on: http://stackoverflow.com/a/52598194
score: 0

http://stackoverflow.com/comment/112442863
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/63578860
has text: I believe this code is wrong- there are edge cases not being taken care of

http://stackoverflow.com/comment/92368617
type: Comment
type: QuestionComment
has text: If you have `return_sequences=False`, the output should be a 2D tensor.If it is `True`, it should be a 3D tensor.What is your `y`?
score: 0
comment on: http://stackoverflow.com/q/52721616

http://stackoverflow.com/comment/92235868
type: QuestionComment
score: 1
has text: Show your code as text. A screenshot is not acceptable because it can't be copied and pasted into an editor for experimentation, among other things.
comment on: http://stackoverflow.com/q/52652066
type: Comment

http://stackoverflow.com/a/52720214
type: Answer
has comment: http://stackoverflow.com/comment/92367043
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/92391175
downvote count: 1
has comment: http://stackoverflow.com/comment/92405141
has body: It may be because of the different users running the script. I think that when you run it from php it is executed as user www-data Maybe you ran pip from a virtualenv or for some other reason www-data user doesn't have access to fpdf module. Edit: Useful links from the comments: How to install Python Package for global use by all users (incl. www-data) http://nocurve.com/2018/04/23/running-python-script-from-php-as-www-data/
answers question: http://stackoverflow.com/q/52719515
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52719515
has comment: http://stackoverflow.com/comment/92366799

http://stackoverflow.com/a/52631785
type: Answer
has body: The most straightforward way is using the nested for loop. k = 0 d = {} for i in range(4): for j in range(4): d[k] = (i, j) k += 1 or, if you prefer oneliners, double comprehension dict( enumerate ( [ (i, j) for i in range(4) for j in range(4)] )) To have one simple for loop or comprehension we can use integer arithmetic operators // (integer division) and % remainder { k : (k // 4, k % 4) for k in range(16) } This probably more elegant and fast
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52631700
accepted answer of: http://stackoverflow.com/q/52631700
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52649188
tagged with: python
has answer: http://stackoverflow.com/a/52664868
tagged with: pytorch
type: Question
has body: This is the Network: class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) # output layer def forward(self, x): x = F.relu(self.hidden(x)) # activation function for hidden layer x = self.predict(x) # linear output return x net = Net(n_feature=1, n_hidden=10, n_output=1) pytorch_total_params = sum(p.numel() for p in net.parameters()) print(pytorch_total_params) w = list(net.parameters()) print(w) This is the runnung result: 31 [Parameter containing: tensor([[ 0.9534], [-0.0309], [-0.9570], [-0.4179], [-0.3757], [-0.4227], [-0.8866], [ 0.2107], [ 0.0222], [ 0.2531]], requires_grad=True), Parameter containing: tensor([-0.0358, -0.2533, 0.2979, 0.9777, 0.9606, 0.9460, 0.9059, 0.7582, -0.5286, 0.3367], requires_grad=True), Parameter containing: tensor([[-0.2863, -0.3157, 0.2086, -0.0011, -0.0415, -0.2574, -0.0683, -0.0788, -0.0339, -0.0195]], requires_grad=True), Parameter containing: tensor([0.2031], requires_grad=True)] I don't know why is the number of parameters be 31? And also don't understand the numbers printed above.(whether it is weight or bias Because I thought in Relu function, there will only be (2 parameters*10) which is weight and bias multiply 10 hidden layers.
has title: How to derive weight and bias in a neural network?
score: 0
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/52678048
upvote count: 2
tagged with: regression
tagged with: machine-learning
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92284977
has title: Reproducing results using keras with tensorflow background
has comment: http://stackoverflow.com/comment/92285600
downvote count: 0
tagged with: keras
has body: I am building a simple Neural Network using keras with tensorflow background. I am new to ML. My aim is to get reproducible results. I have read various blogs to do this and have implemented something like below: import numpy as np import tensorflow as tf import pandas as pd from numpy.random import seed seed(1) from tensorflow import set_random_seed set_random_seed(2) # Parameters learning_rate = .001 training_epochs = 2000 display_step = 5 train = pd.read_csv('T:/2.0 Pricing/45. Machine learning/R Training/Training-2017/Prince/Kaggle House Price Competition/House Prices - Advanced Regression Techniques/Data/train.csv') test = pd.read_csv('T:/2.0 Pricing/45. Machine learning/R Training/Training-2017/Prince/Kaggle House Price Competition/House Prices - Advanced Regression Techniques/Data/test.csv') train=train.loc[train['GrLivArea'] &lt;4000] train=train.loc[train['TotalBsmtSF'] &lt;5000] train=train.loc[train['1stFlrSF'] &lt;3000] train=train.loc[train['2ndFlrSF'] &lt;2000] train=train.loc[train['LotArea'] &lt;80000] train=train.loc[train['BsmtFinSF1'] &lt;5000] train_numeric=train.select_dtypes(exclude=['object']) train_catagorical=train.select_dtypes(include=['object']) train_catagorical=train_catagorical.apply(lambda col: pd.factorize(col, sort=True)[0]) train_variables=train_catagorical.join(train_numeric, how='outer') #train=pd.get_dummies(train) #train_variables=train.select_dtypes(include=variables) #train_variables=train[variables] train_variables=train_variables.fillna(train_variables.mean()) train_variables = train_variables.drop(labels=['SalePrice','Id'], axis=1) train_variables=pd.DataFrame(train_variables,dtype='float32') #train_variables=pd.DataFrame(train_variables[variablestouse],dtype='float32') train_response=pd.DataFrame(train'SalePrice',dtype='float32') test_numeric=test.select_dtypes(exclude=['object']) test_catagorical=test.select_dtypes(include=['object']) test_catagorical=test_catagorical.apply(lambda col: pd.factorize(col, sort=True)[0]…
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0

http://stackoverflow.com/q/52601564
favorite count: 0
has body: Ansible Version : 2.3.1.0 Python Version : 2.7.5 Command : ansible-playbook -i inventories/DEV/ playbooks/patching.yml -e "ticketnum=12345 perform_action=stop ansible_ssh_user=abc" -k Setup: project |_____ pythonengine |______ engine.py |_____ playbooks |_____ patching.yml |_____ inventories |_____ DEV |____hosts |____group_vars |____all |___ all.yml |____host_vars |____host1 |___ all.yml |_____ QA |____hosts |____group_vars |____all |___ all.yml |____host_vars |____host2 |___ all.yml The playbook executes perfectly fine, As part of automation while calling the playbook from Python API [ engine.py ], Its unable to get the variables defined under group_vars and host_vars. here is the code : def runPlaybook(self, playbookYML, hostfile, remoteUser, remoteUserpwd, ticketnum, patchAction, envt): try: loader = Dataloader() inventory = Inventory(loader=loader, variable_manager=VariableManager(), host_list=hostfile) variable_manager = VariableManager() variable_manager.extra_vars = { 'ticketnum': ticketnum, 'perform_action': patchAction, 'ansible_ssh_user': remoteUser } options = namedtuple('Options', ['listtags','listtasks', 'listhosts', 'syntax', 'connection', 'module_path', 'fork', 'remote_user', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'verbosity', 'check', 'diff', 'become', 'become_method','become_user']) options = Options(listtags=False,listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, fork=100, remote_user=remoteUser, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, verbosity=None, check=False, diff=False, become=False, become_method=sudo,become_user=remoteUser) passwords = {'conn_pass': remoteUserPwd} pbex = PlaybookExecutor(playbook=[playbookYML], inventory=inventory, variable_manager=variable_manager, loader=loader, option=options, passwords=passwords) results = pbex.run except Exception as e: logger.error(traceback.print_exc()) raise The above code is failing t…
score: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/54239444
type: Question
answer count: 2
tagged with: ansible
has answer: http://stackoverflow.com/a/52671265
tagged with: ansible-inventory
has title: Ansible Python API - Unable to load group vars
tagged with: python

windows
tags question: http://stackoverflow.com/q/52744511
tags question: http://stackoverflow.com/q/52621659
tags question: http://stackoverflow.com/q/52714549
tags question: http://stackoverflow.com/q/52691196
tags question: http://stackoverflow.com/q/52718655
tags question: http://stackoverflow.com/q/52661315
tags question: http://stackoverflow.com/q/52731407
tags question: http://stackoverflow.com/q/52725002
tags question: http://stackoverflow.com/q/52717364
tags question: http://stackoverflow.com/q/52654470
tags question: http://stackoverflow.com/q/52630324
tags question: http://stackoverflow.com/q/52741369
tags question: http://stackoverflow.com/q/52671019
tags question: http://stackoverflow.com/q/52609180
tags question: http://stackoverflow.com/q/52693216
tags question: http://stackoverflow.com/q/52698797
tags question: http://stackoverflow.com/q/52713401
tags question: http://stackoverflow.com/q/52638709
tags question: http://stackoverflow.com/q/52740901
tags question: http://stackoverflow.com/q/52700284
tags question: http://stackoverflow.com/q/52719371
tags question: http://stackoverflow.com/q/52715430
tags question: http://stackoverflow.com/q/52684331
tags question: http://stackoverflow.com/q/52590878
type: Tag
tags question: http://stackoverflow.com/q/52743460
tags question: http://stackoverflow.com/q/52652014
tags question: http://stackoverflow.com/q/52688917
tags question: http://stackoverflow.com/q/52732565
tags question: http://stackoverflow.com/q/52676223
tags question: http://stackoverflow.com/q/52711520
tag name: windows
tags question: http://stackoverflow.com/q/52711988
tags question: http://stackoverflow.com/q/52630855
tags question: http://stackoverflow.com/q/52621367

http://stackoverflow.com/q/52700624
score: 1
upvote count: 3
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/92328236
tagged with: assertion
linked to: http://stackoverflow.com/q/5142418
has title: Comparison in Python assert statement
has body: After checking few python open source projects I found examples where same function have test cases with assert &lt;&gt; and assert &lt;&gt; is True. And I cannot find answer about best practices of using assert statement with and without full condition. For example function def is_even(number): if number % 2 == 0: return True else: return False can be tested in such way assert is_even(6) is True assert is_even(6) == True but also it can be tested like assert is_even(6) And here I see problem cause if function is_even will be changed on def is_even(number): if number % 2 == 0: return &lt;&gt; else: return False Where &lt;&gt; can be changed on any number(except 0) or non empty string - last test will pass. But this will be another function. I saw this and this SO question about assert usage but seems they don't fully cover my question. From another side PEP 8 specification have such example Don't compare boolean values to True or False using == Yes: if greeting: No: if greeting == True: Worse: if greeting is True: But is it also about assert usage?
has comment: http://stackoverflow.com/comment/92328544
has comment: http://stackoverflow.com/comment/92327874
has comment: http://stackoverflow.com/comment/92328050
tagged with: assert
answer count: 2
has answer: http://stackoverflow.com/a/52701157
has comment: http://stackoverflow.com/comment/92327815
linked to: http://stackoverflow.com/q/944592
has comment: http://stackoverflow.com/comment/92524651
favorite count: 0
has answer: http://stackoverflow.com/a/52701020
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92327995
tagged with: python
has comment: http://stackoverflow.com/comment/92459811
duplicate of: http://stackoverflow.com/q/14733883

http://stackoverflow.com/comment/92369337
has text: Please use this site: https://www.tripadvisor.com.au/Hotel_Review-g56003-d266157-Reviews-Magnolia_Hotel_Houston-Houston_Texas.html
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52718105
type: Comment

http://stackoverflow.com/comment/92403944
type: AnswerComment
comment on: http://stackoverflow.com/a/52739425
has text: It need a little more code, but your advice does the trick. Thanks!
type: Comment
score: 0

http://stackoverflow.com/comment/92219629
comment on: http://stackoverflow.com/q/52643591
has text: If your CSV file looks like that, then it's probably because you're not splitting the lines correctly. In the line `user = line.split(",")` you're splitting by a comma. Try it with `user = line.split()`
type: QuestionComment
type: Comment
score: 3

http://stackoverflow.com/a/52608470
score: 2
has comment: http://stackoverflow.com/comment/110658935
has comment: http://stackoverflow.com/comment/92151353
has comment: http://stackoverflow.com/comment/92150982
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52607864
type: Answer
has body: As mentioned in the comments above, you should use apply instead: df['reult_col'] = df.apply(lambda x: some_func(*tuple(x.values)), axis=1)

http://stackoverflow.com/q/52741901
score: 0
has comment: http://stackoverflow.com/comment/92409323
has comment: http://stackoverflow.com/comment/92409894
has comment: http://stackoverflow.com/comment/92409627
has body: I need to get the result of python script run in terminal and it be used in php so i had tried with shell_exec, exec, passthru, system. Now the problem was the python script take more time to generate the result(upto 45 secs) so it would be returned empty result. if i am used sample python script(just print one array) it working fine with those php functions(shell_exec,exec,system,passthru). What i do for myself to resolve the problem. Thanks in advance.
tagged with: terminal
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92409694
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/92408891
has comment: http://stackoverflow.com/comment/92409840
answer count: 0
has comment: http://stackoverflow.com/comment/92409458
type: Question
has title: Unable to get the results from python script when using shell_exec() in php
has comment: http://stackoverflow.com/comment/92410072
has comment: http://stackoverflow.com/comment/92408763

http://stackoverflow.com/comment/92378880
has text: You can still use canvas to draw something you do not need to use it for the bar. Unless you are wanting to draw something on the bar? If you do want to draw on the BAR you can still do this with a canvas and just place the canvas object in the bar frame.
comment on: http://stackoverflow.com/q/52714026
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52691979
answers question: http://stackoverflow.com/q/52690966
has body: You're trying to access self.sender before initializing it. Reordering initialization might help us here. import datetime import hashlib class Block: def __init__( self, previous_block_hash, data, timestamp, sender, ): self.previous_block_hash = previous_block_hash self.data = data self.timestamp = timestamp #reordering self.hash and self.sender as self.get_sender() references to self.sender self.sender = self.get_sender() self.hash = self.get_hash() @staticmethod def create_genesis_block(): return Block('0', '0', datetime.datetime.now(), '') def get_sender(self): self.sender = input('Enter senders ID number: ') return self.sender def get_hash(self): header_bin = str(self.previous_block_hash) + str(self.data) \ + str(self.timestamp) + str(self.sender) inner_hash = \ hashlib.sha256(header_bin.encode()).hexdigest().encode() outer_hash = hashlib.sha256(inner_hash).hexdigest() return outer_hash hope this helps
accepted answer of: http://stackoverflow.com/q/52690966
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/92137816
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52601778
has text: `b=a.copy()` will solve your problem.

http://stackoverflow.com/q/52675506
type: Question
score: 10
has answer: http://stackoverflow.com/a/63703030
has answer: http://stackoverflow.com/a/58702830
answer count: 3
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/35475103
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/59917905
has title: Get Chrome tab URL in Python
tagged with: google-chrome
upvote count: 10
has body: I want to get information about my Chrome tabs like the URL of the current tab or get all URLs automatically but I can't find any documentation about it. I installed the Chrome API but there's nothing like that from what I have seen. Thanks for your help

http://stackoverflow.com/comment/92376029
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52725099
has text: You mention "Ubuntu 18.04 Lambda" in your edit. Do you mean you're running this on AWS Lambda?
score: 0

http://stackoverflow.com/q/52597178
has body: Is it possible to run a Jupyter notebook server and run Python code (not a script, dynamic code based on actions in a webpage)? My idea is to run Jupyter notebook server on a localhost, and leverage the Python data science stack for the analysis part.
type: UnansweredQuestion
tagged with: python
tagged with: jupyterhub
has comment: http://stackoverflow.com/comment/92158771
has title: Using Jupyter notebook server to execute Python code on the browser?
answer count: 0
has comment: http://stackoverflow.com/comment/92129070
type: Question
tagged with: jupyter-lab
score: 0
tagged with: jupyter
has comment: http://stackoverflow.com/comment/92142466
tagged with: jupyter-notebook

http://stackoverflow.com/a/52691283
answers question: http://stackoverflow.com/q/52691214
downvote count: 1
score: -1
upvote count: 0
has body: Is that what you want ? def sqr(num,l=[]): if num == 1: return l+[num] else : return sqr(num-1,l+[num**2]) Though, I hope you have in mind that list comprehension will 100s time more efficient and the pythonic way.
type: Answer

http://stackoverflow.com/q/52600125
type: Question
linked to: http://stackoverflow.com/q/24971556
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52604167
has title: Openpyxl number_format not modifying cell values derived from formula
type: UnansweredQuestion
has body: Openpyxl's 'number_format' is not modifying cell values derived from formulas because the resulting values are of Type String in Python. I need the data in a particular custom format for a software that reads trajectory information. NOTE: I already saw the same issue addressed here: https://bitbucket.org/openpyxl/openpyxl/issues/376/number-format-not-refreshing-cells I agree with the original answer: the issue is that excel is not storing the data resulting from the formulas in its cache. The data is stored as a string. I am just not sure how to change the data from String to int once it is read by Openpyxl: import csv import openpyxl from openpyxl.styles import Alignment wb = openpyxl.Workbook() ws = wb.active wb.active f = open(r"...\....\...\automated.csv") reader = csv.reader(f, delimiter=',') for row in reader: ws.append(row) f.close() wb.save(r"...\...\...\...\automated.xlsx") sheet=wb.active wb.guess_types = True sheet['F1'] = '***** Time Start' rowNumber = 2 # Start reading from row 3 for i, cellObj in enumerate(ws, 3): # 3 is the starting row to write on rowNumber += 1 cellObj = ws.cell(row=i, column=6) # 6 is the column to start writing on cellObj.value = '=OFFSET(B6,E{0},0)'.format(str(rowNumber).format(i)) cellObj.number_format = 'dd mmm yyyy hh:mm:ss.000 "UTCG"' if i == 25: break ws = wb.active wb.save(r"...\...\...\...\automated.xlsx") I know the code is working because the values stored as '0' are modified by the code perfectly (see highlight) because they do NOT use any formula for that cell: NOTE: The number_format is applied to ALL the cells (I checked this for each row): But since the cell is a string it does not reflect the changes. I am fairly new to Python and attempted to cast cellObj.value as an int but that did not work. Any help or advice on how to do this would be appreciated. I have dug through Stack Overflow for the past 4 days and have not seen any solution to this issue. Thank you! edit: I am using the latest version of openpyxl 2.5.3 …
tagged with: python
downvote count: 0
score: 1
tagged with: openpyxl
tagged with: excel

http://stackoverflow.com/q/52650416
type: AnsweredQuestion
tagged with: odoo
score: 1
has title: Odoo 10 : Remove or disable the New Message function
has answer: http://stackoverflow.com/a/59643012
type: Question
accepted answer: http://stackoverflow.com/a/52666978
possible better answer: http://stackoverflow.com/a/52658697
has answer: http://stackoverflow.com/a/52658697
downvote count: 0
has body: Can somebody give a hint how to remove/disable the New message button in contacts module??It doesnt seem to be part of form view.
has answer: http://stackoverflow.com/a/52659280
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52666978
upvote count: 1
tagged with: python
tagged with: module

http://stackoverflow.com/comment/92167791
has text: Okay no worries. I think I will get my IT guy to give me access to a Linux box as Windows is always a nightmware. I truly appreciate your time on this.
type: Comment
comment on: http://stackoverflow.com/a/52600577
score: 0
type: AnswerComment

dynamic-dispatch
type: Tag
tag name: dynamic-dispatch
tags question: http://stackoverflow.com/q/52731618

http://stackoverflow.com/comment/137518959
has text: @user2357112 You're right. Py_finalize() seems to work incorrectly. I've tested the same code in Python script itself and it works!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52732077

http://stackoverflow.com/comment/92259113
type: QuestionComment
has text: @norok2 what do you mean?
score: 0
comment on: http://stackoverflow.com/q/52664372
type: Comment

python-requests
tags question: http://stackoverflow.com/q/52715847
tags question: http://stackoverflow.com/q/52650938
tags question: http://stackoverflow.com/q/52636795
tags question: http://stackoverflow.com/q/52725892
type: Tag
tags question: http://stackoverflow.com/q/52695214
tags question: http://stackoverflow.com/q/52727207
tags question: http://stackoverflow.com/q/52679808
tags question: http://stackoverflow.com/q/52686968
tags question: http://stackoverflow.com/q/52653224
tags question: http://stackoverflow.com/q/52634552
tags question: http://stackoverflow.com/q/52719207
tags question: http://stackoverflow.com/q/52682932
tags question: http://stackoverflow.com/q/52730062
tags question: http://stackoverflow.com/q/52697135
tags question: http://stackoverflow.com/q/52698283
tags question: http://stackoverflow.com/q/52720673
tags question: http://stackoverflow.com/q/52745313
tags question: http://stackoverflow.com/q/52721619
tags question: http://stackoverflow.com/q/52747035
tags question: http://stackoverflow.com/q/52716219
tags question: http://stackoverflow.com/q/52675152
tags question: http://stackoverflow.com/q/52617523
tags question: http://stackoverflow.com/q/52729095
tags question: http://stackoverflow.com/q/52704501
tags question: http://stackoverflow.com/q/52627563
tags question: http://stackoverflow.com/q/52649213
tags question: http://stackoverflow.com/q/52640053
tags question: http://stackoverflow.com/q/52683737
tags question: http://stackoverflow.com/q/52729749
tags question: http://stackoverflow.com/q/52727061
tags question: http://stackoverflow.com/q/52722534
tag name: python-requests
tags question: http://stackoverflow.com/q/52613680
tags question: http://stackoverflow.com/q/52716024
tags question: http://stackoverflow.com/q/52722362
tags question: http://stackoverflow.com/q/52710123
tags question: http://stackoverflow.com/q/52657610
tags question: http://stackoverflow.com/q/52654022
tags question: http://stackoverflow.com/q/52638914
tags question: http://stackoverflow.com/q/52588733
tags question: http://stackoverflow.com/q/52705158
tags question: http://stackoverflow.com/q/52692120
tags question: http://stackoverflow.com/q/52608218
tags question: http://stackoverflow.com/q/52638979
tags question: http://stackoverflow.com/q/52652421
tags question: http://stackoverflow.com/q/52593468
tags question: http://stackoverflow.com/q/52603029
tags question: http://stackoverflow.com/q/52701411
tags question: http://stackoverflow.com/q/52618451
tags question: http://stackoverflow.com/q/52667762

http://stackoverflow.com/comment/92255435
score: 0
type: AnswerComment
has text: Thanks a lot! How is it possible to generate these? Where do you have this url from?
type: Comment
comment on: http://stackoverflow.com/a/52629516

http://stackoverflow.com/comment/92178502
type: QuestionComment
score: 1
has text: @Vineeth Sai: That's referred to as tabs of 4 spaces and tabs of 8 spaces—but you're right that they should not be mixed together in the same code.
comment on: http://stackoverflow.com/q/52621323
type: Comment

http://stackoverflow.com/q/52672185
has answer: http://stackoverflow.com/a/52672588
score: 0
has body: I have a dataset which is only one column. I want to cut the column into multiple dataframes. I use a for loop to create a list which contains the values at which positions I want to cut the dataframe. import pandas as pd df = pd.read_csv("column.csv", delimiter=";", header=0, index_col=(0)) number_of_pixels = int(len(df.index)) print("You have " + str(number_of_pixels) +" pixels in your file") number_of_rows = int(input("Enter number of rows you want to create")) list=[] #this list contains the number of pixels per row for i in range (0,number_of_rows): #this loop fills the list with the number of pixels per row pixels_per_row=int(input("Enter number of pixels in row " + str(i))) list.append(pixels_per_row) print(list) After cutting the column into multiple dataframes I want to transpose each dataframe and concating all dataframes back together using: df1=df1.reset_index(drop=True) df1=df1.T df2=df2.reset_index(drop=True) df2=df2.T frames = [df1,df2] result = pd.concat(frames, axis=0) print(result) So I want to create a loop that cuts my dataframe into multiple frames at the positions stored in my list. Thank you!
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/92274274
tagged with: python
accepted answer: http://stackoverflow.com/a/52672588
has title: Cuting dataframe loop
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/92361092
comment on: http://stackoverflow.com/a/52717056
type: AnswerComment
has text: @ImportanceOfBeingErnest valid point, depending upon the frequency `DayLocator`, `MonthLocator`, `YearLocator` etc had to be used.
type: Comment
score: 0

http://stackoverflow.com/comment/92402438
has text: @BigSteve [The Zen of Python](https://www.python.org/dev/peps/pep-0020/) includes "There should be one-- and preferably only one --obvious way to do it". I have no doubt that just about any sufficiently fluent Python programmer would come up with that exact line of code in seconds. I didn't really write it. In some sense -- Python wrote it for me.
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52738877

http://stackoverflow.com/q/52614096
has comment: http://stackoverflow.com/comment/92162629
has answer: http://stackoverflow.com/a/52614170
downvote count: 1
has comment: http://stackoverflow.com/comment/92162510
has comment: http://stackoverflow.com/comment/92162595
has comment: http://stackoverflow.com/comment/92162590
linked to: http://stackoverflow.com/q/931092
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52614138
has comment: http://stackoverflow.com/comment/92162712
possible better answer: http://stackoverflow.com/a/52614134
score: 1
has answer: http://stackoverflow.com/a/52614134
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/92162621
has body: I have this code and I don't why it doesn't print the input string in reversed order. I have specified it to print from the last character of the string to the first character with (-1,0,-1). string=str(input()) for i in range(-1,0,-1): print(string[i],end="")
tagged with: python
has title: How do you modify this code so that it will print the input string in reversed order?
accepted answer: http://stackoverflow.com/a/52614138
has answer: http://stackoverflow.com/a/52614136
upvote count: 2

http://stackoverflow.com/q/52633391
type: Question
score: 1
tagged with: python-3.6
answer count: 2
has title: Clearing inputText with a button release in Kivy
downvote count: 0
has answer: http://stackoverflow.com/a/74196553
favorite count: 0
has body: Let's imagine we have a form where the person wrote some stuff on the inputs but need to clear them all, how would I do that in Kivy? I tried this but it didn't work: main.py: class CreateUra(GridLayout): def clear_inputs(self, *args): for item in args: item = '' class UraApp(App): def build(self): return CreateUra() if __name__ == "__main__": UraApp().run() Ura.kv: &lt;CreateUra&gt;: cols: 1 padding: 10 spacing: 10 row_force_default: True row_default_height: '32dp' BoxLayout: Label: text: 'Contexto:' TextInput: hint_text: "Contexto da ura" focus: True multiline: False cursor_color: (0, 0, 0, 0.8) id: context_input BoxLayout: Label: text: 'Nome da ura:' TextInput: hint_text: "Nome do arquivo da ura" multiline: False cursor_color: (0, 0, 0, 0.8) id: ura_file_name Button: text: 'Create Ura' id: bt_create on_press: root.uraConfig() on_release: root.clear_inputs(context_input.text, ura_file_name.text) *Ignore the uraConfig on the on_press I tried this way and it worked: Button: text: 'Create Ura' id: bt_create on_press: root.uraConfig() on_release: context_input.text = '' I'm quite new to kivy and Python, so I'm not sure if this was the best way to clear the texts, but what I did wrong? Or if you guys could give some light in the best way to do it.
has answer: http://stackoverflow.com/a/52633902
tagged with: python
tagged with: kivy
possible better answer: http://stackoverflow.com/a/74196553
accepted answer: http://stackoverflow.com/a/52633902
type: AnsweredQuestion
tagged with: kivy-language
upvote count: 1

http://stackoverflow.com/q/52613320
tagged with: tuples
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92161418
has comment: http://stackoverflow.com/comment/92161474
answer count: 4
has body: input data: input_tuple = ( (1, 'name1', 'Noah'), (1, 'name2', 'Liam'), (2, 'name3', 'Mason'), (3, 'name4', 'Mason'), (4, 'name5', 'Noah'), (4, 'name6', 'Liam'), (5, 'name7', 'Elijah'), (5, 'name8', 'Noah'), (5, 'name9', 'Liam') ) converted into dict(key, value): input_tuple = { 1: [['name1', 'Noah'], ['name2', 'Liam']], 2: 'name3', 'Mason', 3: 'name4', 'Mason', 4: [['name5', 'Noah'], ['name6', 'Liam']], 5: [['name7', 'Elijah'], ['name8', 'Noah'], ['name9', 'Liam']] } did some more filter just for understanding the data model: dict = { 1: ['Noah', 'Liam'], 2: ['Mason'], 3: ['Mason'], 4: ['Noah', 'Liam'], 5: ['Elijah', 'Noah', 'Liam'] } Now i want to eliminate duplicate and then revert back to tuple like below: duplicate matching conditions: 1) eliminate duplicate if len(value) > 1 2) value should exact match not partial. Note: key 2 and 3 value is not duplicate because len(value) is not -gt 1 key 4 value has gone because its exact duplicate since we are doing exact matching, hence in key 5 value ['Noah', Liam] will not go. output_tuple = ( (1, 'name1', 'Noah'), (1, 'name2', 'Liam'), (2, 'name3', 'Mason'), (3, 'name4', 'Mason'), (5, 'name7', 'Elijah'), (5, 'name8', 'Noah'), (5, 'name9', 'Liam') ) code which i tried: from functools import reduce from collections import defaultdict input_tuple_dictionary = defaultdict(list) for (key, *value) in input_tuple: input_tuple_dictionary[key].append(value[1]) input_tuple_dictionary for index in range(len(input_tuple_dictionary)-1): for key, value in input_tuple_dictionary.items(): if len(value) &gt; 1: if value == value[index+1]: print(key)
favorite count: 0
has comment: http://stackoverflow.com/comment/92161311
has comment: http://stackoverflow.com/comment/92161521
has answer: http://stackoverflow.com/a/52613808
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92161422
has comment: http://stackoverflow.com/comment/92161400
has comment: http://stackoverflow.com/comment/92161733
has title: remove duplicates (tuple of tuples)
upvote count: 1
has answer: http://stackoverflow.com/a/52613725
accepted answer: http://stackoverflow.com/a/52613808
downvote count: 1
possible better answer: http://stackoverflow.com/a/52613541
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92161141
has answer: http://stackoverflow.com/a/52613541
has answer: http://stackoverflow.com/a/52613768
tagged with: duplicates
has comment: http://stackoverflow.com/comment/92161444
type: Question
has comment: http://stackoverflow.com/comment/92161413

http://stackoverflow.com/q/52649252
type: AnsweredQuestion
has title: Why in python does the list(range) way much faster than the [i for i in range()] way when creating a number sequence?
type: Question
linked to: http://stackoverflow.com/q/29356846
has answer: http://stackoverflow.com/a/52650827
score: 0
duplicate of: http://stackoverflow.com/q/29356846
accepted answer: http://stackoverflow.com/a/52650827
answer count: 1
has body: I'm using python3.6. For my computer creating a 1e8 number sequence, the former way would spend about 3 seconds while the latter way spent 10 more seconds. Just as the title has presented I wonder what's the difference between the two ways?
tagged with: python

sample
tags question: http://stackoverflow.com/q/52618197
type: Tag
tag name: sample
tags question: http://stackoverflow.com/q/52660179
tags question: http://stackoverflow.com/q/52674171

http://stackoverflow.com/q/52655615
score: 0
has body: I have a series of transactions similar to this table: ID Customer Date Amount 1 A 6/12/2018 33,223.00 2 A 9/20/2018 635.00 3 B 8/3/2018 8,643.00 4 B 8/30/2018 1,231.00 5 C 5/29/2018 7,522.00 However I need to get the mean amount of the last six months (as of today) I was using df.groupby('Customer').resample('W')['Amount'].sum() And get something like this: CustomerCode PayDate A 2018-05-21 268 2018-05-28 0.00 2018-06-11 0.00 2018-06-18 472,657 2018-06-25 0.00 However with this solution I only get the range of dates where the customers had amount. I need to extend the weeks for each customer so I can get the whole range of the six months (in weeks). In this example I would need to get for customer A from the week of '2018-04-05' (which is exactly six months ago from today) till the week of today (filled with 0 of course since there was no amount)
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/92242511
type: UnansweredQuestion
tagged with: indexing
has comment: http://stackoverflow.com/comment/92242615
tagged with: date
has answer: http://stackoverflow.com/a/52656442
type: Question
has title: Pandas extend index date using group by
has answer: http://stackoverflow.com/a/52668009
answer count: 2

http://stackoverflow.com/q/52644069
has title: Calculating the sum of a imported table
type: AnsweredQuestion
type: Question
upvote count: 2
score: 0
downvote count: 2
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52644984
accepted answer: http://stackoverflow.com/a/52644984
has body: This is the content of my text file: nummer naam vak1 vak2 vak3 vak4 vak5 1234567 Jan 5 7 0 6 4 3526435 Marie 5 5 7 0 0 2230431 Kees 6 10 0 8 6 7685433 André 4 7 8 7 5 0364678 Antoinette 0 2 8 8 8 1424354 Jerôme 7 9 0 5 0 4536576 Kamal 8 0 8 7 8 1256033 Diana 0 0 0 0 0 5504657 Petra 6 6 7 0 6 9676575 Malika 0 6 0 0 8 0253756 Samira 3 8 6 7 10 I have imported the list and I am able to open and print the results into python but that's it. Below is my code for the same: results = open("resultaten.txt","r") Empty_str = '' line = results.readline() while line != Empty_str: print(line.strip('\n')) line = results.readline() results.close() The goal of my program is I have to calculate the SUM of the results in Row and Column direction. If the result is a 0, the course cannot have any effect on the sum of the row or column.

http://stackoverflow.com/comment/92319137
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52696365
has text: Strings don't "have regexes". That's something you define. Not clear what you're trying to say
score: 1

http://stackoverflow.com/comment/92169249
type: Comment
has text: @G.Anderson I think you might be right... trying to solve that now...
comment on: http://stackoverflow.com/q/52617427
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92316406
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52694844
has text: @DarkSuniuM While I agree on the first part, the second is misleading since Django ORM is a part Django.

http://stackoverflow.com/q/52701688
has answer: http://stackoverflow.com/a/54841961
has comment: http://stackoverflow.com/comment/92329985
upvote count: 34
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/57335579
has comment: http://stackoverflow.com/comment/92330587
has title: Pandas ImportError: matplotlib is required for plotting
accepted answer: http://stackoverflow.com/a/52705465
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/57335579
has answer: http://stackoverflow.com/a/62445310
type: Question
has answer: http://stackoverflow.com/a/52701814
has comment: http://stackoverflow.com/comment/92330033
has comment: http://stackoverflow.com/comment/92329908
has comment: http://stackoverflow.com/comment/92332295
has body: Pandas does not recognize installed matplotlib library here is the code import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() ts.plot() error is c:\users\xxxxx\appdata\local\programs\python\python36\lib\site-packages\pandas\plotting\_core.py in _raise_if_no_mpl() 55 # TODO(mpl_converter): remove once converter is explicit 56 if not _HAS_MPL: ---&gt; 57 raise ImportError("matplotlib is required for plotting.") 58 59 ImportError: matplotlib is required for plotting.
answer count: 6
tagged with: pandas
has comment: http://stackoverflow.com/comment/92329936
downvote count: 0
has comment: http://stackoverflow.com/comment/92332156
favorite count: 0
linked to: http://stackoverflow.com/q/43422135
has answer: http://stackoverflow.com/a/74817765
has comment: http://stackoverflow.com/comment/92332237
has answer: http://stackoverflow.com/a/52705465
tagged with: python
score: 34

http://stackoverflow.com/comment/92197095
score: 0
has text: question edited
type: QuestionComment
comment on: http://stackoverflow.com/q/52631315
type: Comment

http://stackoverflow.com/comment/92135005
type: QuestionComment
comment on: http://stackoverflow.com/q/52599656
score: 0
has text: Also, you seem to be unnecessarily turning the bytes received into a string at the client side. If the received data is not, in fact, a UTF-8 encoded string then this will result in data corruption.
type: Comment

http://stackoverflow.com/a/52644996
answers question: http://stackoverflow.com/q/52642355
type: Answer
score: 0
type: AcceptedAnswer
has body: a = tkinter.simpledialog.askstring("Prompt", "Enter Separator", parent = window) appends a \ in front of every \ just to make sure that it is interpreted properly. Hitting Tab Key won't work because tkinter will just switch widgets. To fix this issue try this before you store the return value of simpledialog, This also solves the question of "How to replace double backslash with single backslash" import codecs a = tkinter.simpledialog.askstring("Prompt", "Enter Separator", parent = window) a = codecs.escape_decode(a)[0].decode('utf-8') This will make sure your a variable always has \t only.
accepted answer of: http://stackoverflow.com/q/52642355

amazon-web-services
tags question: http://stackoverflow.com/q/52670635
tags question: http://stackoverflow.com/q/52739471
tags question: http://stackoverflow.com/q/52745181
tags question: http://stackoverflow.com/q/52708163
tags question: http://stackoverflow.com/q/52705563
tags question: http://stackoverflow.com/q/52660501
tags question: http://stackoverflow.com/q/52725852
tags question: http://stackoverflow.com/q/52739632
tags question: http://stackoverflow.com/q/52630920
tags question: http://stackoverflow.com/q/52651665
tags question: http://stackoverflow.com/q/52717444
tags question: http://stackoverflow.com/q/52735509
tags question: http://stackoverflow.com/q/52597625
tags question: http://stackoverflow.com/q/52711036
tags question: http://stackoverflow.com/q/52653184
type: Tag
tags question: http://stackoverflow.com/q/52675027
tags question: http://stackoverflow.com/q/52639945
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/52689411
tags question: http://stackoverflow.com/q/52738357
tags question: http://stackoverflow.com/q/52684987
tags question: http://stackoverflow.com/q/52594497
tags question: http://stackoverflow.com/q/52599874
tags question: http://stackoverflow.com/q/52736337
tags question: http://stackoverflow.com/q/52723491
tags question: http://stackoverflow.com/q/52625812
tags question: http://stackoverflow.com/q/52645443
tags question: http://stackoverflow.com/q/52740107
tags question: http://stackoverflow.com/q/52707464
tags question: http://stackoverflow.com/q/52590059
tags question: http://stackoverflow.com/q/52719729
tags question: http://stackoverflow.com/q/52628560
tags question: http://stackoverflow.com/q/52743032
tags question: http://stackoverflow.com/q/52640323
tags question: http://stackoverflow.com/q/52605238
tags question: http://stackoverflow.com/q/52692681

http://stackoverflow.com/comment/92342085
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52707891
type: Comment
has text: Your code is not complete, it's just a list of functions. Also, that error message comes with way more information. Please help us help you.

http://stackoverflow.com/comment/92304783
has text: You have a double check for b[i] != 0. Normal Python and Numba behaviour is to check for 0 and to throw an error. This likely breaks any SIMD vectorization and have usually a high influence on execution speed. But you can change that within Numba to @njit(error_model='numpy') to avoid this double checking for a division by 0. It is also recommendable to allocate memory with np.empty and set the result to 0 within an else statement.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52674448
type: AnswerComment

http://stackoverflow.com/comment/92120316
type: QuestionComment
has text: You want to run a batch file that will open multiple cmd prompts to run simultaneously your scripts?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52590878

http://stackoverflow.com/a/52678019
type: Answer
has comment: http://stackoverflow.com/comment/92284943
answers question: http://stackoverflow.com/q/52677877
score: 1
has comment: http://stackoverflow.com/comment/92284914
upvote count: 1
has comment: http://stackoverflow.com/comment/92284964
has body: If processing word1 and word2 is independent of each other, then you can modify your code as follows: word_found = False if word1 in dict: #process word1 word_found = True if word2 in dict: #process word2 word_found = True if not word_found: #error message
downvote count: 0
has comment: http://stackoverflow.com/comment/92285028

http://stackoverflow.com/q/52637037
has answer: http://stackoverflow.com/a/52749019
favorite count: 0
tagged with: linux
possible better answer: http://stackoverflow.com/a/52655570
accepted answer: http://stackoverflow.com/a/52749019
tagged with: python
score: -1
tagged with: text
type: AnsweredQuestion
has title: How can I create a pandas dataframe from specific columns of a .txt file?
has comment: http://stackoverflow.com/comment/92207186
downvote count: 1
type: Question
has body: I have a number of text files with a specific format. Each column of the text file is allocated to specific information. There aren't any real delimiters, sometimes the entire set of columns is filled up and thus there isn't always white space. For example 1 ALA X 4 80.8 40.6 2 VAL X 234 90.1 42.7 3 VAL X1143 95.2 47.8 ... 34ALANX3324100.2345.8 Columns 1-2 are dedicated to a straight count from 1-99. Columns 3-6 are dedicated to an identification tag. Column 7 is an modifier tag. Columns 8-11 are a number representing a value in another sequence. The actual meanings don't matter, I'm just explaining to help make it clear what is going on with this .txt file. In this case I'm interested in columns 1-2 (with values from 0-99) and columns 8-11 (which has values from 0-9999). It is possible that these values sometimes return NaN or letters. I need to take those columns from the .txt file and put them into a pandas dataframe that has two columns. It seems obnoxious to have to add my own delimiters. Is there a way to tell pandas to create a dataframe column using a few of these text file columns? I am using Python 3.6, pandas v0.23.4, on Linux. edit: For clarification, when referring to columns of the .txt file I mean to refer to the location of the cursor as you move along horizontally. So the very first character of any line is in column 1, the second character of any line is column 2, the thirteenth character of any line is column 13, etc. When I say column when referring to pandas, I mean the actual column in context of how that word is used in pandas dataframes. Sorry for any possible confusion.
tagged with: dataframe
answer count: 2
tagged with: pandas
upvote count: 0
has answer: http://stackoverflow.com/a/52655570

http://stackoverflow.com/q/52646772
answer count: 1
has title: Removing decimal from line chart
tagged with: matplotlib
has body: my year data when display on a table its a whole number but when I input it into a line chart under the x axis it splits itself in different time of the year. Could anyone help me sort it into just the year itself? Here's my current code: df.plot( x = "Year", kind="line", figsize = (10,5), legend = True) plt.ticklabel_format(style="plain", axis="y") plt.xlabel("Year") plt.ylabel("Profit") plt.title("Yearly Profit") plt.show()
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/52647104
downvote count: 0
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/29188757
tagged with: python
has comment: http://stackoverflow.com/comment/92225710
duplicate of: http://stackoverflow.com/q/29188757
upvote count: 2
has answer: http://stackoverflow.com/a/52647104

http://stackoverflow.com/comment/92240550
has text: Perfect, thanks. Apologies for the slow up take!
type: Comment
comment on: http://stackoverflow.com/q/52654194
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92366231
score: 0
type: Comment
has text: count of find is 0 for some index in a and hence there are 0's
type: AnswerComment
comment on: http://stackoverflow.com/a/52717614

google-cloud-functions
tag name: google-cloud-functions
type: Tag
tags question: http://stackoverflow.com/q/52693824
tags question: http://stackoverflow.com/q/52636483

http://stackoverflow.com/q/52603364
has body: I’m trying to store DPI information in an Encapsulated PostScript (EPS) image with Pillow library. For instance: from PIL import Image size = 650, 827 path = 'grey.eps' image = Image.new('L', size, color='grey') image.save(path, dpi=(300, 300)) But I can’t retrieve this info on reading: image = Image.open(path) dpi = image.info['dpi'] print(dpi) I get: Traceback (most recent call last): ... KeyError: 'dpi' Is it possible to have DPI information in EPS images or is it a limitation to the Pillow library?
upvote count: 2
accepted answer: http://stackoverflow.com/a/52604689
tagged with: python
type: AnsweredQuestion
tagged with: python-imaging-library
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52604689
tagged with: eps
favorite count: 0
tagged with: dpi
has title: Store DPI info in EPS image
score: 2

http://stackoverflow.com/q/52600281
has body: I need to enable some pages to write an arbitrary URL that does not depend on the structure of the site. For example I have structure: / /blog /blog/blogpost1 /blog/blogpost2 But, for example, I need change url from /blog/blbogpost2 to /some/blogpost/url1 For this, I decided to give the opportunity to handle any URL of the main page of the site. class IndexPage(RoutablePageMixin, Page): ... @route(r'^(?P&lt;path&gt;.*)/$') def render_page_with_special_path(self, request, path, *args, **kwargs): pages = Page.objects.not_exact_type(IndexPage).specific() for page in pages: if hasattr(page, 'full_path'): if page.full_path == path: return page.serve(request) # some logic But now, if this path is not found, but I need to return this request to the standard handler. How can I do it?
type: Question
accepted answer: http://stackoverflow.com/a/52600442
score: 1
has title: Wagtail render any path in index page
tagged with: wagtail
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52600442
tagged with: python
type: AnsweredQuestion
tagged with: django
upvote count: 1

http://stackoverflow.com/comment/92376375
score: 0
comment on: http://stackoverflow.com/q/52725076
type: QuestionComment
has text: is there anything i can do to seperate them into columns or seperate strings?
type: Comment

http://stackoverflow.com/a/52627793
downvote count: 0
has comment: http://stackoverflow.com/comment/92190371
score: 1
has comment: http://stackoverflow.com/comment/92191749
has comment: http://stackoverflow.com/comment/92189918
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52626888
has comment: http://stackoverflow.com/comment/92190270
answers question: http://stackoverflow.com/q/52626888
has body: When I run your code I do not get any error, only I get an empty answer. text/html None 0 Done And it is correct because in that url there is nothing of content since if you use a browser we will see that it redirects us to another url: https://sourceforge.net/projects/pyqt/, so to enable that redirection the RedirectionTargetAttribute attribute of reply is analyzed. import sys from PyQt5 import QtCore, QtNetwork class MainWindow(QtCore.QObject): def __init__(self): super().__init__() target = "http://pyqt.sourceforge.net" self.manager = QtNetwork.QNetworkAccessManager(self) self.manager.finished.connect(self.on_finished) self.start_request(target) def start_request(self, url): request = QtNetwork.QNetworkRequest(QtCore.QUrl(url)) self.manager.get(request) @QtCore.pyqtSlot(QtNetwork.QNetworkReply) def on_finished(self, reply): redirection_target = reply.attribute(QtNetwork.QNetworkRequest.RedirectionTargetAttribute) if reply.error(): print("There was an error. {}".format(response.errorString())) elif redirection_target is not None: reply.deleteLater() print("redirection_target: {}".format(redirection_target)) self.start_request(redirection_target) else: print(reply.header(QtNetwork.QNetworkRequest.ContentTypeHeader)) print(reply.header(QtNetwork.QNetworkRequest.LastModifiedHeader)) print(reply.header(QtNetwork.QNetworkRequest.ContentLengthHeader)) print(reply.readAll()) reply.deleteLater() QtCore.QCoreApplication.quit() if __name__ == '__main__': app = QtCore.QCoreApplication(sys.argv) w = MainWindow() sys.exit(app.exec_()) Output: redirection_target: PyQt5.QtCore.QUrl('https://sourceforge.net/projects/pyqt/') text/html; charset=utf-8 None None b'&lt;!doctype html&gt;\n&lt;!-- Server: sfs-consume-8 --&gt;\n&lt;html class="no-js" lang="en"&gt;\n &lt;head&gt;\n &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;&lt;script type="text/...
type: Answer
has comment: http://stackoverflow.com/comment/92190502
has comment: http://stackoverflow.com/comment/92191565

http://stackoverflow.com/comment/92257887
type: QuestionComment
has text: Do they have to be all separate lists? Or can the input be a list of lists?
score: 0
comment on: http://stackoverflow.com/q/52663874
type: Comment

http://stackoverflow.com/comment/92393563
comment on: http://stackoverflow.com/a/52734395
type: Comment
has text: Great. Thank you, Matias. I will have a try.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92120013
type: Comment
type: QuestionComment
has text: What if the method is `POST` but `user_u.is_valid() and profile_u.is_valid()` does not hold?
comment on: http://stackoverflow.com/q/52592658
score: 3

http://stackoverflow.com/q/52673881
tagged with: pandas
downvote count: 0
has title: Pandas: Is there a way to group together values within a column?
favorite count: 0
has answer: http://stackoverflow.com/a/52674671
tagged with: python
has comment: http://stackoverflow.com/comment/92277460
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52673998
accepted answer: http://stackoverflow.com/a/52673998
score: 1
upvote count: 1
type: Question
has body: I'm using pandas to crunch a DataFrame in which one column is called "Rank", for military rank. When I use groupby on the data and create a crosstab, I notice that some of the values in Rank are synonyms. For example, I have separate rows in my cross table for "Private 1st Class," "Private First Class," and "PFC." Assuming I can manually create a dictionary to relate all of those "synonyms" together, is there a way I can get pandas to apply it to my DataFrame so that the values are all considered the same for the purposes of counts, crosstables, and so on? So for the example above, if I decided to standardize on "PFC" I would create the following: {"Private 1st Class": "PFC", "Private First Class": "PFC"}. I looked at groupby, but as far as I can tell it sorts the whole frame by columns, and doesn't support equivalent values like this. If I'm wrong, could someone please point me to the relevant part of the documentation?
possible better answer: http://stackoverflow.com/a/52674671
has comment: http://stackoverflow.com/comment/92277452
answer count: 2

http://stackoverflow.com/comment/92137498
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52601623
has text: So I can get `1 + 1/1! + 1/2! + 1/n!`

http://stackoverflow.com/q/52619696
downvote count: 1
has comment: http://stackoverflow.com/comment/92205944
type: Question
has comment: http://stackoverflow.com/comment/92206177
tagged with: inheritance
has comment: http://stackoverflow.com/comment/92205778
has comment: http://stackoverflow.com/comment/92205746
score: 0
has comment: http://stackoverflow.com/comment/92204837
has comment: http://stackoverflow.com/comment/92204797
has comment: http://stackoverflow.com/comment/92173824
has comment: http://stackoverflow.com/comment/92205666
tagged with: nested
has comment: http://stackoverflow.com/comment/92206507
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92205891
answer count: 0
has comment: http://stackoverflow.com/comment/92173597
has comment: http://stackoverflow.com/comment/92204798
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: In the following, B is an outer class, which inherits from Bbase, and A is an inner class, which inherits from Abase. I create B with class variable B.b=None, then alter B.b. I then repeat the process. In the new derived class, I find that indeed B.b=None, so I have created a pristine replicate of the B class, which was my intent. So far, so good. Also within B, I create a class A with class variable A.a=None, and I alter that as well. However, in the repetition of the process, what I thought was my new replicate of A turns out to have A.a equal to the previously altered value, rather than None which I expect from the initializer in the base class. That is, I have not received a pristine replicate of A after all, but rather my replicate of B contains the same class A (or perhaps a copy with the same alteration) that I created earlier. This is shown by the following code and output. I actually want my otherwise pristine replicate of B to contain a pristine replicate of A, rather than the previously modified version of A. How can I accomplish this? Code: class Abase(): a = None class Bbase(): b = None class A(Abase): pass print('Run 1') class B(Bbase): pass print('B.b, B.A.a=', B.b, B.A.a, '(Expect "None None")') B.b = 23 B.A.a = 47 print('B.b, B.A.a=', B.b, B.A.a, '(Expect "23 47")') print() print('Run 2') class B(Bbase): pass print('B.b, B.A.a=', B.b, B.A.a, '(Expect "None None")') B.b = 23 B.A.a = 47 print('B.b, B.A.a=', B.b, B.A.a, '(Expect "23 47")') Output (Python 3.7.0, MacOS 10.13.6): Run 1 B.b, B.A.a= None None (Expect "None None") B.b, B.A.a= 23 47 (Expect "23 47") Run 2 B.b, B.A.a= None 47 (Expect "None None") &lt;==== B.b, B.A.a= 23 47 (Expect "23 47") By the way, if I create A outside of B, then insert it into B via B.A = A, this has the desired effect. I was hoping, though, to create it within B, like the other objects belonging to class B. Resolution First, as a result of this discussion and a followup with colleagues at Hack Manhattan, I've been disapp…
has title: Python: Creating a class from a baseclass inside another class created from a baseclass
has comment: http://stackoverflow.com/comment/92206701
has comment: http://stackoverflow.com/comment/92206571
has comment: http://stackoverflow.com/comment/92173610

http://stackoverflow.com/comment/92403487
score: 0
comment on: http://stackoverflow.com/q/52738057
type: Comment
type: QuestionComment
has text: I think you might want to consider `levinshtein distance` as a measure of string similarity

http://stackoverflow.com/a/52742371
has comment: http://stackoverflow.com/comment/92412824
answers question: http://stackoverflow.com/q/52741194
has comment: http://stackoverflow.com/comment/92410859
score: 2
has body: Firstly, you dont need to write Selector(response).xpath(...) Instead you can just write response.xpath(...) Secondly, In the PopularitySpider you need to change the selectors as:- popularity = response.xpath('//div[contains(@class, "question-summary")]') for poppart in popularity: item = PopularityItem() item['votes'] = poppart.xpath( '//div[contains(@class, "votes")]//span/text()').extract() item['answers'] = poppart.xpath( '//div[contains(@class, "answered")]//span/text()').extract() item['views'] = poppart.xpath( '//div[contains(@class, "views")]//span/text()').extract() yield item Hope it solves your problem. Note: The good practice to check whether your selector is working or not is to use inspect option in browser (chrome etc), even better option would be to test your code in scrapy shell. You just need to run the following command:- scrapy shell www.example.com
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92412304
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92411482
type: Answer
accepted answer of: http://stackoverflow.com/q/52741194

http://stackoverflow.com/comment/92170501
type: Comment
has text: Thanks for your responses :) Yeah, I agree with your readability comment. I've used list comps to speed up other areas of this pipeline. This little segment is really slowing down my code though. All help and comments greatly appreciated
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52618146

http://stackoverflow.com/q/52731143
tagged with: python
tagged with: circular-dependency
type: Question
has body: How should I resolve the following circular dependency? I have a file A that exposes API methods and delegates all the backend logic to a separate file, A_impl. In A.py, I also expose an Enum which clients need to pass in as an argument to some of the API methods: # A.py import A_impl class MyEnum(Enum): ONE = 1 TWO = 2 THREE = 3 def A(x: MyEnum): return A_impl._A(x) A_impl actually needs MyEnum: #A_impl.py from A import MyEnum def _A(x: MyEnum): pass One way to resolve this is to just merge the two modules together but that defeats the purpose of splitting it up for cleaner code in the first place. A_impl consists of dozens of helper functions and putting the public and private methods into one module was getting messy.
has answer: http://stackoverflow.com/a/52731163
score: 0
answer count: 1
has title: Pythonic Way to structure module API with circular import
has comment: http://stackoverflow.com/comment/92387426
tagged with: python-3.x
type: UnansweredQuestion

multiprocessing
tags question: http://stackoverflow.com/q/52600959
tags question: http://stackoverflow.com/q/52600240
tags question: http://stackoverflow.com/q/52668592
tags question: http://stackoverflow.com/q/52609672
tags question: http://stackoverflow.com/q/52727856
tags question: http://stackoverflow.com/q/52701150
tags question: http://stackoverflow.com/q/52715595
tags question: http://stackoverflow.com/q/52632791
tags question: http://stackoverflow.com/q/52651506
tags question: http://stackoverflow.com/q/52652852
tags question: http://stackoverflow.com/q/52642700
tags question: http://stackoverflow.com/q/52614042
tags question: http://stackoverflow.com/q/52636002
tags question: http://stackoverflow.com/q/52653224
tags question: http://stackoverflow.com/q/52693216
tags question: http://stackoverflow.com/q/52616895
tags question: http://stackoverflow.com/q/52666736
tags question: http://stackoverflow.com/q/52677330
tags question: http://stackoverflow.com/q/52613759
type: Tag
tags question: http://stackoverflow.com/q/52652780
tags question: http://stackoverflow.com/q/52721139
tag name: multiprocessing

http://stackoverflow.com/comment/92385352
has text: @jackarnold, Possibly your CSV file has an unnamed column. But hard to tell, you should search for other Q&A on this issue, or ask a new question with a [mcve].
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52674900

http://stackoverflow.com/comment/92264881
has text: and as guess, some function from the `itertools` will do what You want, just check this module.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52667345
type: Comment

http://stackoverflow.com/comment/92374736
comment on: http://stackoverflow.com/q/52724530
type: QuestionComment
has text: are the values coordinates, by any chance?
type: Comment
score: 0

http://stackoverflow.com/a/52668292
has comment: http://stackoverflow.com/comment/92266556
has body: You could do something like this: import maths list_with_numbers=[] def results(): for _ in range(1,10): a = maths.numbers() list_with_numbers.append(a) print(list_with_numbers) It is obvious, but don´t forget to all the function itself.
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92266643
has comment: http://stackoverflow.com/comment/92266457
answers question: http://stackoverflow.com/q/52668183
type: Answer

http://stackoverflow.com/comment/92167958
has text: Perfect thanks! I am now running into an error saying cannot import name 'Horizontal location'. Any ideas to this?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52616795

http://stackoverflow.com/comment/92123229
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52594018
has text: no, it does not return anything to me since children() returns an empty list. the widgets that are added to a layout are not children of the layout but the widget where the layout was set up, which is why I find it strange and is the reason for my request.

http://stackoverflow.com/comment/92380855
comment on: http://stackoverflow.com/q/52720467
has text: You're surely right @Divakar, but if I arrived on this question from Google: [How to conditionally combine two numpy arrays *of the same shape*](https://stackoverflow.com/questions/46558114/how-to-conditionally-combine-two-numpy-arrays-of-the-same-shape) I would have thought that it's not related to this problem (not knowing broadcasting)... Never mind, thank you for your help anyway.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92270020
comment on: http://stackoverflow.com/a/52669667
has text: You really know a lot about python and pygame. How did you come to know so much about the language and how to use it with pygame?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52657426
type: AcceptedAnswer
score: -1
answers question: http://stackoverflow.com/q/52657017
type: Answer
has body: You can use the following list comprehension: [','.join(sorted(i.split(','), key=lambda s: tuple(map(int, s.split()[0].split('.'))))) for i in a] so that with the following input (note that I've changed the 192.168.70.19 in your sample input to 192.168.70.39 to demonstrate that the IP-addresses are sorted numerically): a=['192.168.70.19 (tcp/1433)', '192.168.70.223 (tcp/1051),192.168.70.39 (tcp/1025),192.168.70.245 (tcp/1025)', '192.168.70.19 (tcp/3389),192.168.70.223 (tcp/3389)'] the above list comprehension would return: ['192.168.70.19 (tcp/1433)', '192.168.70.39 (tcp/1025),192.168.70.223 (tcp/1051),192.168.70.245 (tcp/1025)', '192.168.70.19 (tcp/3389),192.168.70.223 (tcp/3389)']`
downvote count: 2
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52657017

http://stackoverflow.com/q/52671209
has comment: http://stackoverflow.com/comment/92274947
score: 0
has title: MongoDB Only Logging Documents In Localhost
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92275190
tagged with: pymongo
has comment: http://stackoverflow.com/comment/92275068
has body: [Answered] I have started using MongoDB, and it works great to an extent. When I access Compass, if I sign in as the localhost port 27017; I can see all my documents. However, I ideally want it to be logging the documents on my account in which it's not. When I sign into Compass with my account details, they are not there. In you code I am doing MongoClient = MongoClient("mongodb://localhost:27017/") and again, it logs my documents in the localhost, but not my account. I'm guessing the issue is that I am using localhost in connecting, if so what do I put? Or is there something I am doing wrong? I would like to save it to my account.
type: Question
tagged with: mongodb

http://stackoverflow.com/q/52600484
has answer: http://stackoverflow.com/a/52600520
type: Question
tagged with: try-catch
possible better answer: http://stackoverflow.com/a/52600520
accepted answer: http://stackoverflow.com/a/52600506
tagged with: int
score: 0
tagged with: syntax-error
answer count: 2
has title: Python saying variable is non type when it is an int
has body: I am writing this program for my class and whenever I run it inputting only integers it runs fine. As soon as I input a string and trigger the try exception block, it runs the function again but it says that the variable ticket is a non type when it should be an integer and i'm not sure why this is happening. Problem Function: def asktickets(): # Notifies user that data inputed was wrong and explains why then lets you try again asktickets2 = input('Enter the number of violations 0 or more: ') try: tickets = int(asktickets2) if tickets &lt; 0: continue2 = input( 'Invalid input: The number of violations must be more than 0. Please click enter to try again.') asktickets() else: return int(tickets) except ValueError: continue2 = input( 'Invalid input: The number of violations must be more than 0. Please click enter to try again.') asktickets2 = 0; tickets = 0 asktickets() Full Code (the error is happening with the variable tickets in the main when it is passed into the RiskCode() method but only if you enter a string then an integer first when running the program: # File Name: Shepherd_Project 1.py def askage(): # Asks user for age askage2 = input('Please enter age of client (age must be between 16-105): ') try: age = int(askage2) if age &lt;= 15 or age &gt; 105: continue1 = input('Invalid input: Age range must be between 16-105. Please click enter to try again.') askage() else: return age except ValueError: continue2 = input( 'Invalid input: The age range must be between 16-105. Please click enter to try again.') askage() def asktickets(): # Notifies user that data inputed was wrong and explains why then lets you try again asktickets2 = input('Enter the number of violations 0 or more: ') try: tickets = int(asktickets2) if tickets &lt; 0: continue2 = input( 'Invalid input: The number of violations must be more than 0. Please click enter to try again.') asktickets() else: return int(tickets) except ValueError: continue2 = input( 'Invalid input: The number of violations m…
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52600506

http://stackoverflow.com/q/52657804
tagged with: binary
has comment: http://stackoverflow.com/comment/92287896
type: UnansweredQuestion
tagged with: bit
tagged with: python
has answer: http://stackoverflow.com/a/52657941
downvote count: 2
tagged with: set
upvote count: 1
has title: Python Binary compare to List values
type: Question
linked to: http://stackoverflow.com/q/374626
score: -1
has comment: http://stackoverflow.com/comment/92246184
has comment: http://stackoverflow.com/comment/92246278
answer count: 1
has body: I am trying to figure out how to do this in Python: Print out all subsets of any given set. For example: [1,2] So the answer is by hand the following: [] [2] [1] [1,2] I realized that the total number of solutions would be 2(exp)n, where n is the number of elements in the list. So for example, if the list is [1,3,4], then the total number of subsets would be 2(exp)3 = 8. I also realized that if I got the binary bit representation of the list above, the following appears: So for example: [1,2] 00 : [] 01 : [2] 10 : [1] 11 : [1,2] Each position of the bit that contains a 1, that is the position of the subset when indexing it to the original set [1,2]. eg binary 01 = get index at position 1 of the original set [1,2] which would be [2]. Binary 11, means get index positions 0 and 1 from the original set [1,2] which gives an answer of [1,2], etc. How can I code this, the code I have is so messy, is there a easy way to map this?
favorite count: 0

http://stackoverflow.com/q/52600944
has answer: http://stackoverflow.com/a/52601213
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/52601095
has comment: http://stackoverflow.com/comment/92136288
has title: How to write a random vote generator in Python
score: -1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: So I have to write a code that prompts a user to input a number which is the number of voters and then those voters are distributed by percentages to 3 candidates. On top of that, I have to import a random number and if that number is >= 5 that vote counts as a fraud and gets subtracted. Also if they are bribed the vote goes to a different candidate. Finally, I need to make a pie chart using turtle to display the results. This is all I have so far: import turtle, random voters = int(input("Enter the # of would-be voters here: ")) numIM = 0 numCA = 0 numSM = 0 while (voters &gt; 0): numIM = random.randint(0,100) if numIM &lt;= 5: voters -= 1 numCA = random.randint(0, 100) if numCA &lt;= 5: voters -= 1 numSM = random.randint(0, 100) if numSM &lt;= 5: voters -= 1 The confusing part to me is this: Determine which hero the voter will vote for. Again, you will use a random number between 1 and 100 to determine which hero they voted for. The heroes have the following chance of being picked: Iron Man - 34% Captain America - 33% Spiderman - 33%
downvote count: 1
type: Question

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/52698947
tags question: http://stackoverflow.com/q/52676963
tags question: http://stackoverflow.com/q/52595247
tags question: http://stackoverflow.com/q/52616907
tags question: http://stackoverflow.com/q/52705784
tags question: http://stackoverflow.com/q/52620712
tags question: http://stackoverflow.com/q/52691503
tags question: http://stackoverflow.com/q/52728469
tags question: http://stackoverflow.com/q/52703476
type: Tag
tags question: http://stackoverflow.com/q/52698292
tags question: http://stackoverflow.com/q/52589475
tags question: http://stackoverflow.com/q/52608052
tags question: http://stackoverflow.com/q/52600940
tags question: http://stackoverflow.com/q/52721709
tags question: http://stackoverflow.com/q/52656353
tags question: http://stackoverflow.com/q/52598116
tags question: http://stackoverflow.com/q/52699913
tags question: http://stackoverflow.com/q/52705648
tags question: http://stackoverflow.com/q/52730332
tags question: http://stackoverflow.com/q/52702954
tags question: http://stackoverflow.com/q/52658905
tags question: http://stackoverflow.com/q/52710503
tags question: http://stackoverflow.com/q/52692529
tags question: http://stackoverflow.com/q/52720185
tags question: http://stackoverflow.com/q/52742797
tags question: http://stackoverflow.com/q/52715847
tags question: http://stackoverflow.com/q/52647266
tags question: http://stackoverflow.com/q/52669276
tags question: http://stackoverflow.com/q/52598031
tags question: http://stackoverflow.com/q/52706457
tags question: http://stackoverflow.com/q/52689859
tags question: http://stackoverflow.com/q/52596492
tags question: http://stackoverflow.com/q/52743998
tags question: http://stackoverflow.com/q/52674168
tags question: http://stackoverflow.com/q/52620805
tags question: http://stackoverflow.com/q/52683831
tags question: http://stackoverflow.com/q/52590484
tags question: http://stackoverflow.com/q/52654797
tag name: html
tags question: http://stackoverflow.com/q/52663376
tags question: http://stackoverflow.com/q/52730256
tags question: http://stackoverflow.com/q/52611748
tags question: http://stackoverflow.com/q/52700395
tags question: http://stackoverflow.com/q/52603355

nbconvert
tags question: http://stackoverflow.com/q/52710762
tag name: nbconvert
type: Tag

http://stackoverflow.com/comment/92336501
score: 0
comment on: http://stackoverflow.com/q/52704841
type: Comment
type: QuestionComment
has text: Can't you just write all the obtained hashes to a file and read/compare from there (instead of converting each time)? The faster option could be to store the hashes in a database and using an index speed up lookups.

http://stackoverflow.com/q/52724369
has title: Get input from dynamically created input
upvote count: 2
downvote count: 2
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92374409
type: Question
answer count: 1
has body: How would I retrieve input if I created a bunch of input boxes like this expensefields=[] expenses = [i for i in range(6)] count=0 for expense in expenses: expense = Entry(master) expense.grid(row=count,column=2) expenseinputs.append(expense) count=count+1 I know about using the .get() method, but not sure how to approach this. If I'm doing this the wrong way I'd love to get some pointers.
score: 0
has answer: http://stackoverflow.com/a/52724638
has comment: http://stackoverflow.com/comment/92374786
accepted answer: http://stackoverflow.com/a/52724638
favorite count: 0
has comment: http://stackoverflow.com/comment/92374936
tagged with: tkinter

http://stackoverflow.com/comment/92355811
has text: find_element_by_class_name or find_elements_by_class_name does not work with multiple class names. the locator should specify the full class name, if you wish to grab a partial name from the full class, use xpath.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52715015

http://stackoverflow.com/q/52627238
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92188237
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/92187999
has comment: http://stackoverflow.com/comment/92188281
upvote count: 1
type: Question
has body: Any exist built in method or best practices to check containers type with typing library? I would like see: from typing import List isinstance([1,2,3], List[int]) General problem is different behavior with same syntax: In [22]: isinstance([1,2], List) Out[22]: True In [23]: isinstance([1,2], List[int]) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-23-8598eb948ef8&gt; in &lt;module&gt;() ----&gt; 1 isinstance([1,2], List[int]) /usr/lib/python3.7/typing.py in __instancecheck__(self, obj) 706 707 def __instancecheck__(self, obj): --&gt; 708 return self.__subclasscheck__(type(obj)) 709 710 def __subclasscheck__(self, cls): /usr/lib/python3.7/typing.py in __subclasscheck__(self, cls) 714 if cls._special: 715 return issubclass(cls.__origin__, self.__origin__) --&gt; 716 raise TypeError("Subscripted generics cannot be used with" 717 " class and instance checks") 718 TypeError: Subscripted generics cannot be used with class and instance check```
has comment: http://stackoverflow.com/comment/92188900
has title: Python check isinstance with typing
has comment: http://stackoverflow.com/comment/92190588
has comment: http://stackoverflow.com/comment/92188294
tagged with: typing
downvote count: 0
duplicate of: http://stackoverflow.com/q/43646823
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/52714074
has comment: http://stackoverflow.com/comment/92355648
upvote count: 1
answers question: http://stackoverflow.com/q/52713631
type: Answer
downvote count: 0
score: 1
has body: One solution is View.py class AttributeView(generics.ListAPIView): serializer_class = AttributeSerializer queryset = Attribute.objects.all() def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(dict({"Attribute": serializer.data})) model.py class Attribute(models.Model): name = models.CharField(max_length=50) code = models.CharField(max_length=50) value = models.IntegerField(default=0) @property def get_group(self): return dict({"name": self.name, "code": self.code}) serializer.py class AttributeSerializer(serializers.ModelSerializer): group = serializers.ReadOnlyField(source='get_group') class Meta: model = Attribute fields = ('name', 'code', 'value', 'group')

http://stackoverflow.com/q/52693485
has body: I am working on an assignment and have the assignment completed, but wanted to see if there was a way to utilize the months list under enter_rainfall. When I enter ask user for rain amount I want to know if it possible to add the months_list at the end with index and have the index add one for every iteration. code is below: def main(): months_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] rain = enter_rainfall() average = avg_rainfall(rain) low_high = low_High(rain, months_list) def enter_rainfall(): rain_fall = [] months = 12 for month in range(months): rain_amount = float(input('Please enter the amount of rainfall for each month:')) rain_fall.append(rain_amount) return(rain_fall) def avg_rainfall(rain): total = 0 for value in rain: total += value average = total / len(rain) print('The total rainfall for the year is', total, 'inches') print('The average monthly rainfall is', format(average, '.2f'), 'inches') return(average) def low_High(rain, months_list): low_val = min(rain) low_month = months_list[rain.index(low_val)] high_val = max(rain) high_month = months_list[rain.index(high_val)] print('The month with the highest rainfall is', high_month) print('The month with the lowest rainfall is', low_month) main()
has answer: http://stackoverflow.com/a/52693519
has comment: http://stackoverflow.com/comment/92313784
type: Question
has comment: http://stackoverflow.com/comment/92314362
has comment: http://stackoverflow.com/comment/92313800
score: 0
has comment: http://stackoverflow.com/comment/92314397
answer count: 1
type: UnansweredQuestion
has title: Is it possible to add list to print statement in Python?
tagged with: python

http://stackoverflow.com/a/52733187
upvote count: 1
has comment: http://stackoverflow.com/comment/92420742
score: 1
has body: Best approach would be to go back and change the delimiter in your file from , to something more sensible but if that's not an option so you can do something like this as a workaround: import csv with open(os.path.join(somelocation, somefile.txt), "r", encoding="utf-8", errors="replace") as inputfile: spamreader = csv.reader(inputfile, delimiter='¬') for row in spamreader: new_row = row.rsplit(",", 2) print("|".join(new_row)) This uses a delimer not seen in your text so doesn't split any lines (so you could do the reading with inputfile.readlines() instead), then it uses rsplit to split on the two rightmost commas to create the columns
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52733087

http://stackoverflow.com/q/52724273
has answer: http://stackoverflow.com/a/52727457
possible better answer: http://stackoverflow.com/a/73461577
answer count: 2
has answer: http://stackoverflow.com/a/73461577
downvote count: 0
favorite count: 0
has title: AppIndicator3.Indicator: is there a way to hide/show it at runtime?
accepted answer: http://stackoverflow.com/a/52727457
tagged with: python
tagged with: gtk
type: AnsweredQuestion
score: 1
tagged with: pygobject
has body: I am trying to hide the `AppIndicator3.Indicator`` once is shown but so far all my tries have failed. So far I tried to just set the instance to None in the hope that the garbage collector would remove it and I tried to set the menu to None. This is how I am showing it: def __show_app_indicator(self) -&gt; None: if AppIndicator3: icon_theme = Gtk.IconTheme.get_default() icon_name = icon_theme.lookup_icon('weather-showers-symbolic', 16, 0).get_filename() self.__app_indicator: AppIndicator3.Indicator = AppIndicator3.Indicator \ .new(APP_ID, icon_name, AppIndicator3.IndicatorCategory.HARDWARE) self.__app_indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) self.__app_indicator.set_menu(self.__app_indicator_menu)
upvote count: 1
type: Question

http://stackoverflow.com/comment/92217979
comment on: http://stackoverflow.com/a/52642725
has text: wow, it was near my nose, i had wrote same you but with a little difference. this----> mywriter.writerow(L1[0],L1[1])
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52714119
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52713952
score: 2
has body: You can use glob pattern: File_list = glob.glob('/'.join((path, *('[0-9]' * n for n in (3, 2, 4)), '.format')))
downvote count: 0

http://stackoverflow.com/comment/92164663
type: Comment
has text: Thanks! I will try it
comment on: http://stackoverflow.com/a/52615051
score: 1
type: AnswerComment

http://stackoverflow.com/a/52658415
score: 0
has body: The sort keyword argument was introduced in version 0.23.0 (see what’s new) in order to allow the user to control an unwanted effect (automatic sorting of indexes on non concatenating axis, only in case join=outer). So it appears that during your update pandas was downgraded. Are you able to keep a version >= 0.23.0? If not you might want to go through the related pandas issue to look for workarounds (basically you would have to unsort after the call). Edit: Going through the issue, the best workaround I found is: “My workaround uses unique_everseen from the Itertools Recipes.” columns = unique_everseen([column for df in dfs for column in df.columns]) df = pd.concat(dfs)[columns]
type: Answer
answers question: http://stackoverflow.com/q/52658139
has comment: http://stackoverflow.com/comment/92285163

http://stackoverflow.com/a/52710412
type: Answer
answers question: http://stackoverflow.com/q/52710153
has body: You could try using the By module: from selenium.webdriver.common.by import By from selenium import webdriver browser = webdriver.Firefox() browser.get("https://www.theurl.com") browser.find_element(By.NAME,"userName").send_keys("Test")
score: 0

http://stackoverflow.com/q/52607864
score: 4
has comment: http://stackoverflow.com/comment/92150116
has comment: http://stackoverflow.com/comment/92150529
answer count: 3
has comment: http://stackoverflow.com/comment/110694315
has comment: http://stackoverflow.com/comment/92150340
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/92150843
linked to: http://stackoverflow.com/q/7837722
linked to: http://stackoverflow.com/q/45670242
favorite count: 0
has comment: http://stackoverflow.com/comment/92150656
tagged with: http://stackoverflow.com/tag/zip
linked to: http://stackoverflow.com/q/40646458
has body: This is just a nitpicking syntactic question... I have a dataframe, and I want to use list comprehension to evaluate a function using lots of columns. I know I can do this df['result_col'] = [some_func(*var) for var in zip(df['col_1'], df['col_2'],... ,df['col_n'])] I would like to do something like this df['result_col'] = [some_func(*var) for var in zip(df'col_1', 'col_2',... ,'col_n')] i.e. not having to write df n times. I cannot for the life of me figure out the syntax.
has answer: http://stackoverflow.com/a/52608411
has comment: http://stackoverflow.com/comment/128786305
linked to: http://stackoverflow.com/q/16476924
accepted answer: http://stackoverflow.com/a/52608411
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92150028
has comment: http://stackoverflow.com/comment/109772012
has comment: http://stackoverflow.com/comment/110659005
tagged with: dataframe
linked to: http://stackoverflow.com/q/58567199
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/92150285
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/62064822
possible better answer: http://stackoverflow.com/a/52608470
has title: Dataframe list comprehension "zip(...)": loop through chosen df columns efficiently with just a list of column name strings
linked to: http://stackoverflow.com/q/11285613
has answer: http://stackoverflow.com/a/52608470
downvote count: 0

python-requests-html
tags question: http://stackoverflow.com/q/52699466
type: Tag
tag name: python-requests-html

http://stackoverflow.com/a/52712686
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/92351970
has comment: http://stackoverflow.com/comment/92354746
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52712198
has comment: http://stackoverflow.com/comment/92351418
has body: You could obtain the result by group by operation along with a aggregation from django.db.models import Count, Max qs.values('Zone').annotate(zone_count=Count('Zone')).aggregate(most_frequent_zone=Max('zone_count'))
answers question: http://stackoverflow.com/q/52712198
has comment: http://stackoverflow.com/comment/92351753

http://stackoverflow.com/comment/92311495
score: 1
has text: you are the man thanks a bunch
comment on: http://stackoverflow.com/a/52692298
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92398771
type: Comment
comment on: http://stackoverflow.com/a/52736986
type: AnswerComment
score: 0
has text: Ah - so your solution may not work as the next closest mat date could on a trade done in the past well?

http://stackoverflow.com/comment/92295990
type: Comment
comment on: http://stackoverflow.com/a/52683960
type: AnswerComment
has text: Is there another way? I've put the execute part in a function which I'm calling many times and generating various statements, It would be better not to have to change the function since I'm not passing in the variables but placing them in the string.
score: 0

http://stackoverflow.com/a/52670772
has body: n1 = 40 n2 = 305 # sort lexicograhically ns = sorted(str(n1) + str(n2)) # move the first non-zero element to the start i = ns.count('0') if 0 &lt; i &lt; len(ns): ns[0:0] = ns.pop(i)
answers question: http://stackoverflow.com/q/52670595
type: Answer
has comment: http://stackoverflow.com/comment/92271801
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/52590546
accepted answer: http://stackoverflow.com/a/52590687
type: Question
score: 3
answer count: 2
has comment: http://stackoverflow.com/comment/92115885
possible better answer: http://stackoverflow.com/a/52590697
favorite count: 0
has answer: http://stackoverflow.com/a/52590697
upvote count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/92115859
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: How can I use .loc with .str.match() to update column values but with a function call? The code I'm trying is like; df.loc[df['Col1'].str.match(r'\d\d/\d\d/\d\d\d\d', na=False), 'Col2'] = _my_func(df['Col1']) a simple regex pattern to find date format, and then _myfunc(); def _my_func(data) for row in data.iteritems(): day = int(row[1][:2]) month = int(row[1][3:5]) year = int(row[1][6:]) fecha = datetime.datetime(year, month, day, 0, 0, 0) diff = fecha - datetime.datetime.now() if diff.days &gt; 0: return 'Yes' elif diff.days &lt; 0: return 'No' Is this a correct way to return values from the function into the dataframe? Also if I insert a print('test') into the _my_func just before either return, it only prints test one time, instead of a print for each row in the data passed to the function, does anyone know why? Thank you.
has title: Populating column in pandas dataframe using a function call
has answer: http://stackoverflow.com/a/52590687

http://stackoverflow.com/q/52714026
has comment: http://stackoverflow.com/comment/92378880
linked to: http://stackoverflow.com/q/20860325
has comment: http://stackoverflow.com/comment/92378713
has answer: http://stackoverflow.com/a/52720802
score: 1
has comment: http://stackoverflow.com/comment/92378839
accepted answer: http://stackoverflow.com/a/52720802
answer count: 2
tagged with: taskbar
downvote count: 0
tagged with: icons
favorite count: 0
tagged with: titlebar
tagged with: python
possible better answer: http://stackoverflow.com/a/65987716
has comment: http://stackoverflow.com/comment/92378192
has answer: http://stackoverflow.com/a/65987716
type: AnsweredQuestion
has title: python tkinter restore window without title bar
has comment: http://stackoverflow.com/comment/92378662
tagged with: tkinter
has body: I have a tkinter window that I removed the title bar from and added a custom close and minimize button to. When the program first loads it doesn't display an icon to the taskbar. When I click the custom made minimize button it then creates an icon on the taskbar; however, when I click to restore the window I am unable to get rid of the titlebar again. I want the icon to always show on the taskbar, and when the program is minimized and then restored I would like the title bar to still be gone from .overrideredirect(1). Unfortunately I'm having trouble resetting the flag before and after minimizing without making the taskbar icon disappear. Please let me know what I am doing wrong. Thanks! #!/usr/bin/python3 from tkinter import * import tkinter as tk import datetime import time import math root = tk.Tk() root.overrideredirect(1) def close(): root.destroy() def minimizeWindow(): root.withdraw() root.overrideredirect(False) root.iconify() root.resizable(False, False) canvas = Canvas(root, width = 400, height = 400) canvas.pack() exit = Button(root, text='x', command = close) exitWindow = canvas.create_window(10,10, window=exit) minimize = Button(root, text='-', command = minimizeWindow) minimizeWindow = canvas.create_window(30,10,window=minimize) icon = PhotoImage(file='py.gif') root.tk.call('wm', 'iconphoto', root._w, icon) root.mainloop() # starts the mainloop I am trying to make it work for both windows and linux. The reason I'm taking out the title bar altogether is to avoid the differences that come from the OS font and window settings. It's currently exhibiting this same behavior on both Operating Systems. To reiterate, I want the taskbar icon to show up on program launch and I want the program's window to maintain it's titlebar-less state when restored from being minimized.
upvote count: 1
type: Question

http://stackoverflow.com/q/52719729
has title: Deploying python with docker, images too big
favorite count: 0
accepted answer: http://stackoverflow.com/a/52719901
has comment: http://stackoverflow.com/comment/92366574
has comment: http://stackoverflow.com/comment/92400906
has answer: http://stackoverflow.com/a/52724099
has body: We've built a large python repo that uses lots of libraries (numpy, scipy, tensor flow, ...) And have managed these dependencies through a conda environment. Basically we have lots of developers contributing and anytime someone needs a new library for something they are working on they 'conda install' it. Fast forward to today and now we need to deploy some applications that use our repo. We are deploying using docker, but are finding that these images are really large and causing some issues, e.g. 10+ GB. However each individual application only uses a subset of all the dependencies in the environment.yml. Is there some easy strategy for dealing with this problem? In a sense I need to know the dependencies for each application, but I'm not sure how to do this in an automated way. Any help here would be great. I'm new to this whole AWS, Docker, and python deployment thing... We're really a bunch of engineers and scientists who need to scale up our software. We have something that works, it just seems like there has to be a better way .
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52724099
upvote count: 5
has answer: http://stackoverflow.com/a/52720025
type: Question
score: 5
downvote count: 0
tagged with: amazon-web-services
tagged with: docker
has answer: http://stackoverflow.com/a/52719901
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/92364731

http://stackoverflow.com/comment/92163395
has text: Glad I could help! as for the docs, I guess this should fit: [Writing the Setup Configuration File](https://docs.python.org/3/distutils/configfile.html) from the `distutils` docs.
type: AnswerComment
comment on: http://stackoverflow.com/a/52613394
type: Comment
score: 1

http://stackoverflow.com/comment/92232765
type: AnswerComment
comment on: http://stackoverflow.com/a/52650004
type: Comment
has text: Thank you for the reference. Strange that all second items are not displaying after typing all of them in.
score: 0

http://stackoverflow.com/comment/92242639
has text: We’ll dropna will only recognize values pandas considers null. If by empty you mean the empty string, that doesn’t count. Can you show some of your data, preferably from `df.head().to_dict()`
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52655623

http://stackoverflow.com/q/52706603
tagged with: python
answer count: 1
has title: Adding unique values in the output in Pandas
accepted answer: http://stackoverflow.com/a/52706844
has body: import pandas as pd data = {'numbers' : [1, 2, 3, 1, 3, 2, 2, 3, 3, 1, 2, 1, 1, 2, 3], 'colors' : ['red', 'yellow', 'red', 'green', 'blue', 'purple', 'blue', 'blue', 'green', 'blue', 'purple', 'blue', 'blue', 'purple', 'red']} df = pd.DataFrame(data) temp = df.groupby('numbers').colors.apply(' --&gt; '.join) I got some help with my code earlier but now I'm stuck on another step... The current output looks like this: 1 red --&gt; green --&gt; blue --&gt; blue --&gt; blue 2 yellow --&gt; purple --&gt; blue --&gt; purple --&gt; purple 3 red --&gt; blue --&gt; blue --&gt; green --&gt; red But I need to aggregate the similar values so that the output will look like this: 1 red --&gt; green --&gt; blue x3 2 yellow --&gt; purple --&gt; blue --&gt; purple x2 3 red --&gt; blue x2 --&gt; green --&gt; red I've attempted using things like ['colors'].count() But this counts all the values in total, when I am looking for duplicate values next to each other.
downvote count: 0
tagged with: pandas-groupby
tagged with: pandas
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52706844
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2

http://stackoverflow.com/a/52687024
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52686748
type: Answer
score: 3
upvote count: 3
has body: Pandas has native support for a large class of operations on datetimes, so one solution here would be to use pd.to_datetime to convert your dates from strings to pandas' representation of datetimes, pd.Timestamp, then just create a mask based on the current date: df['date'] = pd.to_datetime(df['date'], dayfirst=True) df[df['date'] &gt; pd.Timestamp.now()] For example: In [34]: df['date'] = pd.to_datetime(df['date'], dayfirst=True) In [36]: df Out[36]: id date 0 1 2018-02-01 1 2 2019-05-01 2 3 2018-03-05 3 4 2018-11-23 In [37]: df[df['date'] &gt; pd.Timestamp.now()] Out[37]: id date 1 2 2019-05-01 3 4 2018-11-23
answers question: http://stackoverflow.com/q/52686748

http://stackoverflow.com/comment/92124174
type: Comment
comment on: http://stackoverflow.com/q/52593557
has text: Either you use the system clipboard, or you effectively end up writing your own, and reinventing the wheel needs a compelling argument, so: why do you even care about whether it uses the clipboard or not? Is there a performance hit or the like you're running into?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92394262
has text: Which two places? Don't build a `svc_list` variable in the first place and you're good. `data['services']` is your service list.
type: Comment
comment on: http://stackoverflow.com/a/52734626
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92300462
has text: I've tried using " print(type(start_date)) " but I'm getting None in return and obviously the flask eror is " must be string or read-only buffer, not None " Thanks for your help
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52685975
type: Comment

http://stackoverflow.com/a/52658727
has body: I think this just a tempoary solution for you to sovle your current problems . So you just create own custom keywoard like below by using library python pynput . from pynput.keyboard import Key, Controller keyboard = Controller() # Press and release key def acceptDownloadff(): keyboard.press(Key.down) keyboard.release(Key.down) keyboard.press(Key.enter) keyboard.release(Key.enter) and here is a sample robotframework just call this keyword from your python file : *** Settings *** Library Selenium2Library Library test.py *** Variables *** ${url} yoururl *** Test Cases *** Make Something open browser ${url} ff Click Element id=dl acceptDownloadff i'm already tested it . and it's work and can solve your problem if you are unable to find other solution.
has comment: http://stackoverflow.com/comment/92251816
downvote count: 0
has comment: http://stackoverflow.com/comment/92249295
has comment: http://stackoverflow.com/comment/92253965
has comment: http://stackoverflow.com/comment/92250014
has comment: http://stackoverflow.com/comment/92251740
answers question: http://stackoverflow.com/q/52640018
type: Answer
has comment: http://stackoverflow.com/comment/92249347
has comment: http://stackoverflow.com/comment/92249454
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92250797

http://stackoverflow.com/comment/92370466
has text: You must show your code if you want help debugging it. It's one of our rules.
type: Comment
comment on: http://stackoverflow.com/q/52714024
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92193623
comment on: http://stackoverflow.com/a/52629885
type: Comment
score: 0
type: AnswerComment
has text: So is the conclusion here that the sample size is simply too small to conduct a meaningful t-test?

http://stackoverflow.com/a/52595146
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/52594984
score: -1
has comment: http://stackoverflow.com/comment/92125108
upvote count: 0
has body: You can use builtin function zip for this as shown below: list1, list2 = map(list, zip(*data)) list1 and list2 will contain lists as required from the given list data

http://stackoverflow.com/q/52730667
has comment: http://stackoverflow.com/comment/92443463
linked to: http://stackoverflow.com/q/15207271
has comment: http://stackoverflow.com/comment/92386451
has comment: http://stackoverflow.com/comment/92495157
linked to: http://stackoverflow.com/q/32150690
has comment: http://stackoverflow.com/comment/92409130
has comment: http://stackoverflow.com/comment/92495267
has comment: http://stackoverflow.com/comment/92497908
has comment: http://stackoverflow.com/comment/92490438
has comment: http://stackoverflow.com/comment/92442161
has comment: http://stackoverflow.com/comment/92386958
has comment: http://stackoverflow.com/comment/92407129
answer count: 2
has comment: http://stackoverflow.com/comment/92388090
has comment: http://stackoverflow.com/comment/92507464
tagged with: http://stackoverflow.com/tag/pdf
has title: Can't get working command line on prompt to work on subprocess
downvote count: 0
tagged with: cmd
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92463780
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52795276
has comment: http://stackoverflow.com/comment/92386902
tagged with: python
has answer: http://stackoverflow.com/a/52795363
has comment: http://stackoverflow.com/comment/92497436
tagged with: subprocess
tagged with: pypdf
has comment: http://stackoverflow.com/comment/92388149
upvote count: 1
has comment: http://stackoverflow.com/comment/92408558
has comment: http://stackoverflow.com/comment/92455052
has body: I need to extract text from a PDF. I tried the PyPDF2, but the textExtract method returned an encrypted text, even though the pdf is not encrypted acoording to the isEncrypted method. So I moved on to trying accessing a program that does the job from the command prompt, so I could call it from python with the subprocess module. I found this program called textExtract, which did the job I wanted with the following command line on cmd: "textextract.exe" "download.pdf" /to "download.txt" However, when I tried running it with subprocess I couldn't get a 0 return code. Here is the code I tried: textextract = shlex.split(r'"textextract.exe" "download.pdf" /to "download.txt"') subprocess.run(textextract) I already tried it with shell=True, but it didn't work. Can anyone help me?
type: Question

http://stackoverflow.com/comment/92188545
comment on: http://stackoverflow.com/a/52627285
type: Comment
score: 0
type: AnswerComment
has text: @petrush: unsure of it. Do you really need the typing module here? If you don't, simply using `collections.namedtuple` could be simpler.

http://stackoverflow.com/comment/92204285
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52635518
has text: `google R collatz efficient` - first 2 hits - should help :) got no idea about R

http://stackoverflow.com/comment/92335007
has text: You left out the most important part.. the function. Can you include some dummy function if it's too long to share? As well as expected output.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52704241

http://stackoverflow.com/comment/92409113
has text: don't you think this is overkill. Why not to use drop_duplicates? By default it will keep 1st occurrence.
type: Comment
comment on: http://stackoverflow.com/a/52741388
score: 0
type: AnswerComment

http://stackoverflow.com/q/52626430
accepted answer: http://stackoverflow.com/a/52627136
has title: In python I do "dictionary = {"key": [value, value], (etc)}" How do I do this in Visual Basic?
type: Question
has comment: http://stackoverflow.com/comment/92187044
has body: I'm doing a small adventure game for my computer science class in VB and to do the inventory of the character, I need to know how to make a dictionary(so I can have the name of the item) and a list as the values of the item(the list would be something like obj = [Quantity,Damage_Dealt(or Health_Received)]). I've done some research and I tried to do Dim knife As New List(Of Integer) knife.add(1)#the first one is how many knives and the second is the dmg knife.add(1) Dim inv As New Dictionary(Of String, List(Of Integer)) inv.add("knife", knife) but there are some things missing or hopefully there is an easier way to do it. Even if it is possible to create 2 or 3-d array (e.g. inv = [[knife, 1, 1], [bread, 2, 0]]) I would appreciate the most straightforward way of changing the python dictionary = {"key": [value, value], (etc)} into VB Thank you in advance I forgot to mention that all that is in a sub within a class.
has comment: http://stackoverflow.com/comment/92186374
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/92186111
has answer: http://stackoverflow.com/a/52627136
tagged with: python
tagged with: dictionary
tagged with: vb.net
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/52626594
has answer: http://stackoverflow.com/a/52626971
has answer: http://stackoverflow.com/a/52626594

http://stackoverflow.com/a/52685861
downvote count: 0
type: Answer
upvote count: 3
has body: If you want to make sure that 'a=' and 'b=' is stripped only from the beginning of the string, you have to use pattern matching, e.g.: import re re.sub('^[^=]*=','','a=alpha')
answers question: http://stackoverflow.com/q/52685821
score: 3

http://stackoverflow.com/comment/95064637
type: AnswerComment
has text: This is true, however @Mauritius could store segments of trajectories (or at least bounding boxes of segments) together with trajectory ID in the r-tree, not the bounding boxes representing the trajectories.
type: Comment
comment on: http://stackoverflow.com/a/52621865
score: 0

http://stackoverflow.com/comment/92380127
has text: This works like a charm. I'm studying Pandas right now , and couldn't quite figure out how to get over the hump. Thanks
type: Comment
comment on: http://stackoverflow.com/a/52727355
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92135929
type: AnswerComment
comment on: http://stackoverflow.com/a/52600778
type: Comment
has text: I think `choice[sheldon]` would read better. Or something that denotes the tuple value is what the key defeats
score: 0

http://stackoverflow.com/a/52708615
has body: You are missing one level in your dict get. run this and you will see. print messagejson['Records'][0]['sql'] The 'key' is within the value of the 'object' key, so you need to add 'object' before you get 'key' print messagejson['Records'][0]['sql']['object']['key']
has comment: http://stackoverflow.com/comment/92343962
has comment: http://stackoverflow.com/comment/92343596
has comment: http://stackoverflow.com/comment/92343786
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52708568
has comment: http://stackoverflow.com/comment/92343722
downvote count: 0
answers question: http://stackoverflow.com/q/52708568
type: Answer
has comment: http://stackoverflow.com/comment/92344035
score: 2

http://stackoverflow.com/comment/92334905
comment on: http://stackoverflow.com/q/52702229
type: QuestionComment
type: Comment
score: 2
has text: @Willem Van Onsem actually I’m reading a book for CSP and it says use backtracking even though there are better ways

http://stackoverflow.com/a/52887199
type: Answer
upvote count: 4
downvote count: 0
has body: The best approach to get installed wkhtmltopdf on Heroku by getting the binary of wkhtmltopdf for python 3 instead of wkhtmltopdf-pack and you can achieve this by using pydf. You can install it simply using pip like: pip install python-pdf or for Python 2: pip install python-pdf==0.30.0 Unlike the buildpack based approach pydf installs with the wkhtmltopdf binary included making it very easy to use, and this is the right approach for Heroku. But if you still want to stick with build-pack wkhtmltopdf, here's another solution you can give it a try: Via: CLI Installation $ heroku create --buildpack https://github.com/homelight/wkhtmltox-buildpack.git Or Manually: Add the following line to your .buildpacks file https://github.com/homelight/wkhtmltox-buildpack.git Please note that this buildpack is only compatible with the cedar-14 stack. You can use heroku stack:set cedar-14 to set the correct stack.
score: 4
has comment: http://stackoverflow.com/comment/92757660
answers question: http://stackoverflow.com/q/52721272

http://stackoverflow.com/q/52741957
score: 1
has answer: http://stackoverflow.com/a/52892163
tagged with: pymongo
tagged with: pymodm
type: Question
has body: The MongoDB server is hosted in a docker container. Created a super user with root permission to login using username and password. Using pymodm to connect to MongoDB server from Python script. I'm able to connect to the docker hosted MongoDB server from the shell as well as the Compass tool. The effort to connect and insert new items programatically using Python script fails with Authentication Failed error. The script is as follows: from pymodm import connect from pymodm import MongoModel, fields import urllib.parse class Dummy(MongoModel): email = fields.EmailField(primary_key=True) name = fields.CharField() class Meta: connection_alias = 'Mongo' # Establish a connection to the database. mongo_uri = "mongodb://monadmin:" + urllib.parse.quote("myPassword@123") + "@192.168.x.x:27017/Test" # Establish a connection to the database. def Connect2DB() try: #connect('mongodb://localhost:27017/PMOTest') connect(mongo_uri, alias="Mongo") print("db connection success") return True except: print("db connection failed") return False def Insert_record(): try: Dummy(email="hello@test.com", name="test").save() print("save success") except ex: print("save failed") if __name__ == "__main__": if Connect2DB(): Insert_record() The connection succeeds but the insert record is failing with the following error: pymongo.errors.OperationFailure: Authentication failed
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52892163
has title: Authentication failed error in Python script to connect MongoDB server using pymodm
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/92234499
type: Comment
type: QuestionComment
has text: I recently saw in the docs of `imageio` that capturing a frame from webcam there is also a simple oneliner. IMHO I think that the time taken for this is mainly HW dependant - but you could just give it a try and see... https://imageio.readthedocs.io/en/stable/userapi.html
score: 0
comment on: http://stackoverflow.com/q/52651116

http://stackoverflow.com/q/52614042
answer count: 1
has answer: http://stackoverflow.com/a/52614235
type: UnansweredQuestion
tagged with: python
tagged with: multiprocessing
type: Question
has title: Is it possible to get interactive feedback with python's Pool.map()
has comment: http://stackoverflow.com/comment/92171594
has body: I have something that looks like: from multiprocessing import Pool def handle_element((element, params)): # do handling print ('done handling element') elements = [....] element_params = [(), (), ...] pool = Pool() pool.map(handle_element, zip(elements, element_params)) I only see the prints after map() concludes. Is there a way to get more interactive feedback out of map()? Edit: Using Python 2.7
tagged with: python-multiprocessing
tagged with: pool
score: 0

http://stackoverflow.com/a/59889715
upvote count: 77
type: AcceptedAnswer
score: 76
type: Answer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52673610
has body: To avoid truncation and to control how much of the tensor data is printed use the same API as numpy's numpy.set_printoptions(threshold=10_000). Example: x = torch.rand(1000, 2, 2) print(x) # prints the truncated tensor torch.set_printoptions(threshold=10_000) print(x) # prints the whole tensor If your tensor is very large, adjust the threshold value to a higher number. Another option is: torch.set_printoptions(profile="full") print(x) # prints the whole tensor torch.set_printoptions(profile="default") # reset print(x) # prints the truncated tensor All the available set_printoptions arguments are documented here.
answers question: http://stackoverflow.com/q/52673610

http://stackoverflow.com/q/52627163
tagged with: selenium
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/92188311
has comment: http://stackoverflow.com/comment/92187952
type: Question
has comment: http://stackoverflow.com/comment/92187870
downvote count: 0
has answer: http://stackoverflow.com/a/52628072
has comment: http://stackoverflow.com/comment/92188404
has comment: http://stackoverflow.com/comment/92189454
answer count: 1
has comment: http://stackoverflow.com/comment/92189615
has comment: http://stackoverflow.com/comment/92187770
score: 1
has title: Selenium stop working after a period of time
favorite count: 0
has body: I want to extract the data which has 9000 pages. After extracting approx 1700 pages it stopped working when I want it to continue, it starts from the beginning and execute after approx 1000 pages. In this code, I have to select the zone manually. How do I scrap data of total pages? Is there any time limitation of chromedriver (for session)? import requests from bs4 import BeautifulSoup from selenium import webdriver import time import csv url = "https://www.mcg.gov.in/default1.aspx?HTT=B" driver = webdriver.Chrome(executable_path = 'D:/Python_module/chromedriver_win32/chromedriver.exe') driver.get(url) time.sleep(4) driver.find_element_by_xpath('//*[@id="CphContentPlaceHolderbody_mcg"]/section/div[1]/div/a[1]/div').click() time.sleep(2) driver.find_element_by_xpath('//*[@id="CphContentPlaceHolderbody_lnkViewSurveyDataBtn"]').click() time.sleep(4) driver.find_element_by_xpath('//*[@id="CphContentPlaceHolderbody_PropertySearchControl1_btnSearch"]').click() time.sleep(4) #-----------------This is for extracting the data of page-1----------------------------------- driver.find_element_by_xpath('//*[@id="form"]/div[4]/div[11]/table/tbody/tr/td[12]/a').click() time.sleep(1) print("If you are in second page then the code is fine.") soup = BeautifulSoup(driver.page_source, 'html.parser') current_url = driver.current_url table = soup.find('table', {'class':'table table-hover table-bordered'}) #divs = soup.find('div', {'id':'CphContentPlaceHolderbody_PropertySearchControl1_upTop'}) print(table) for row in table.findAll('tr')[1:]: raw_data = row.findAll('td')[0:] property_id = raw_data[0].text ward_no = raw_data[1].text owner = raw_data[2].text print(owner) page_no = page_no+1 try: while True: driver.find_element_by_xpath('//*[@id="form"]/div[4]/div[11]/table/tbody/tr/td[14]/a').click() time.sleep(1) print("If you are in second page then the code is fine.") soup = BeautifulSoup(driver.page_source, 'html.parser') current_url = driver.current_url table = soup.find('table', {'cla…
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92187690

http://stackoverflow.com/comment/92251446
type: Comment
has text: The code and links you gave me really helped me a lot.Thank you very much
comment on: http://stackoverflow.com/a/52660012
score: 1
type: AnswerComment

http://stackoverflow.com/q/52672656
has comment: http://stackoverflow.com/comment/92275686
type: UnansweredQuestion
has body: My Procfile contains web: gunicorn chn_parking.wsgi Why I am getting this error? Can't open file 'manage.py': [Errno 2] No such file or directory I am trying to deploy an app on Heroku. All was fine...
tagged with: django
tagged with: python
tagged with: heroku
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/92275968
has answer: http://stackoverflow.com/a/52672771
has comment: http://stackoverflow.com/comment/92275741
type: Question
has comment: http://stackoverflow.com/comment/92275306
has comment: http://stackoverflow.com/comment/92275045
has answer: http://stackoverflow.com/a/52675898
upvote count: 3
answer count: 2
has title: Can't open file 'manage.py': [Errno 2] No such file or directory
favorite count: 0
has comment: http://stackoverflow.com/comment/92275730

python-unittest
tags question: http://stackoverflow.com/q/52593584
tags question: http://stackoverflow.com/q/52711728
tags question: http://stackoverflow.com/q/52602278
tags question: http://stackoverflow.com/q/52617206
tags question: http://stackoverflow.com/q/52605689
tags question: http://stackoverflow.com/q/52743977
type: Tag
tags question: http://stackoverflow.com/q/52605915
tags question: http://stackoverflow.com/q/52682351
tags question: http://stackoverflow.com/q/52717834
tags question: http://stackoverflow.com/q/52723672
tags question: http://stackoverflow.com/q/52643756
tag name: python-unittest
tags question: http://stackoverflow.com/q/52613181

http://stackoverflow.com/q/52643889
type: UnansweredQuestion
tagged with: python
has body: This is my problem, if someone can help me... From a server which has been just upgraded from Debian 7 Wheezy to Debian 8 Jessie, some issues appear since the upgrade of python-django for a mumble server ; but above all trying to install certbot broke dependencies. After this command apt-get install python-certbot-apache -t jessie-backports E: Sub-process /usr/bin/dpkg returned an error code (1) some paquets python should been upgraded to a backport version, but it brokes dependencies... last upgrade show these errors message (sorry locales are in french): $ apt upgrade Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait Calcul de la mise à jour... Fait 0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour. 18 partiellement installés ou enlevés. Il est nécessaire de prendre 0 o/681 ko dans les archives. Après cette opération, 0 o d'espace disque supplémentaires seront utilisés. Souhaitez-vous continuer ? [O/n] O Paramétrage de python-augeas (0.5.0-1~bpo8+1) ... Traceback (most recent call last): File "/usr/bin/pycompile", line 35, in &lt;module&gt; from debpython.version import SUPPORTED, debsorted, vrepr, \ File "/usr/share/python/debpython/version.py", line 24, in &lt;module&gt; from ConfigParser import SafeConfigParser ImportError: No module named 'ConfigParser' dpkg: erreur de traitement du paquet python-augeas (--configure) : le sous-processus script post-installation installé a retourné une erreur de sortie d'état 1 dpkg: erreur de traitement du paquet python-cffi (--configure) : le paquet est dans un état vraiment incohérent; vous devriez le réinstaller avant de tenter de le configurer. Paramétrage de python-configargparse (0.11.0-1~bpo8+1) ... Traceback (most recent call last): File "/usr/bin/pycompile", line 35, in &lt;module&gt; from debpython.version import SUPPORTED, debsorted, vrepr, \ File "/usr/share/python/debpython/version.py", line 24, in &lt;module&gt; from ConfigP…
has answer: http://stackoverflow.com/a/52668919
score: 0
type: Question
has title: python-certbot dependencies broken E: Sub-process /usr/bin/dpkg returned an error code (1)
answer count: 1
tagged with: debian-jessie
tagged with: apt
tagged with: debian

http://stackoverflow.com/a/70859309
score: 1
upvote count: 1
has body: Theoretically, time.sleep(0.25) induces a wait of 250ms. However, the actual wait may be shorter or longer instead of being precisely 250ms. This is because: The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. Other methods of using wait with selenium include: Implicit wait: driver.implicitly_wait(0.25) Explicit wait: WebDriverWait(driver).until(document_initialised)
downvote count: 0
answers question: http://stackoverflow.com/q/52603847
type: Answer

gmail
type: Tag
tags question: http://stackoverflow.com/q/52721545
tag name: gmail

http://stackoverflow.com/comment/92386569
comment on: http://stackoverflow.com/a/52703845
has text: I am using -type because creating joints, there is a node somewhere with joint in his name (eve if I've worked on a really simple scene file) I've just assumed that you had a list of known named node. If you use type nurbsCurve, you will get shapes and will have to find the transform to parent it. I'll try something tomorrow when I'll have maya. My point in this code was : you can build an ID dictionnary and associate everything. In this case, there is one group, one joint but you could work with multiple group to parent to joints. Im not a rigging guy so I try to take things as broad as I can
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52595899
has body: first.py import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys import HtmlTestRunner class Environment(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path="D:\\auto\\chromedriver.exe") # login test case def test_login(self): driver = self.driver driver.maximize_window() driver.get("http://localhost/dashboard/user/login") self.driver.find_element_by_id('uemail').send_keys('xyz@gmail.com') self.driver.find_element_by_id('upwd').send_keys('1234567890') self.driver.find_element_by_id('upwd').send_keys(Keys.RETURN) def tearDown(self): self.driver.close() if __name__ == "__main__": unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='D:\\auto\\reports')) second.py import unittest import HtmlTestRunner import first class Notification(environment.test_login): def test_going_notification_page(self): going_noti_page = self.driver.find_element_by_class_name('color7') print(self.driver.execute_script("arguments[0].click();", going_noti_page)) if __name__ == "__main__": unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='D:\\auto\\reports'))
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52596330
tagged with: selenium
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92127229
score: -1
has title: why i am not able to execute second.py
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/92290475
type: Comment
has text: @Nitesh , welcome. [Accept the answer](https://stackoverflow.com/help/accepted-answer) if it solved your issue
comment on: http://stackoverflow.com/a/52679554
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92272754
score: 0
has text: Because this is how the tensorflow has "patched" setting attributes.
type: QuestionComment
comment on: http://stackoverflow.com/q/52671481
type: Comment

http://stackoverflow.com/comment/92122405
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [Pandas groupby - set of different values](https://stackoverflow.com/questions/47542980/pandas-groupby-set-of-different-values)
comment on: http://stackoverflow.com/q/52593689

http://stackoverflow.com/q/52731229
answer count: 1
score: 4
has comment: http://stackoverflow.com/comment/92388892
favorite count: 0
has answer: http://stackoverflow.com/a/53037025
accepted answer: http://stackoverflow.com/a/53037025
tagged with: python
upvote count: 4
tagged with: node.js
type: AnsweredQuestion
downvote count: 0
has title: How to spawn Python process from Heroku Node
tagged with: process
type: Question
tagged with: heroku
tagged with: spawn
has body: Am trying to execute a Python script from node. It's hitting the endpoint, and runs fine locally but when I try deploy from Heroku, I get the following error log: ``` 2018-10-10T01:00:14.689410+00:00 app[web.1]: events.js:183 2018-10-10T01:00:14.689416+00:00 app[web.1]: throw er; // Unhandled 'error' event 2018-10-10T01:00:14.689417+00:00 app[web.1]: ^ 2018-10-10T01:00:14.689419+00:00 app[web.1]: 2018-10-10T01:00:14.689421+00:00 app[web.1]: Error: spawn python3.6 ENOENT 2018-10-10T01:00:14.689424+00:00 app[web.1]: at Process.ChildProcess._handle.onexit (internal/child_process.js:190:19) 2018-10-10T01:00:14.689426+00:00 app[web.1]: at onErrorNT (internal/child_process.js:362:16) 2018-10-10T01:00:14.689428+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:139:11) ``` I tried setting the Python runtime in runtime.txt in the root directory: ``` $ cat runtime.txt python-3.6.0 ```
linked to: http://stackoverflow.com/q/39897505

http://stackoverflow.com/q/52616803
type: AnsweredQuestion
score: -2
tagged with: import
type: Question
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
has title: CSV being read with no rows
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/52619555
has body: I'm trying to read a csv from a web page into pandas but get something saying empty dataframe and an object with 0 rows and 155 columns. I feel like I'm missing a step. Struggling to use data from web as opposed to my machine in general. url ="https://data.world/exercises/data-wrangling-exercise-1/workspace/file?filename=Crime_2015.csv" crimex= pd.read_csv(url) print(crimex) output as follows: Empty DataFrame Columns: [ data.world Loading...?Feedback{"dataset":{"hasError":false, loadedDatasets:{}, usersDatasets:{}, loadedCurrentUsersDatasets:false, usersDatasetsTotalCount:0}, user:{"hasError":false, loadedUsers:{}, userFollows:{}, userLikes:{}, userInvites:null, userRecentComments:{}, groupAuthorizations:{}}, invite:{}, treatments:["showVersions", showWorkspaceTabs, showEntityLinkOptions, paramQueries], currentUser:{"authorizedAccounts":null, requests:[], unDismissedTourCount:2, needsAnalyticsAlias:false, notifications:[], dismissed:[], profile:{"agentid":"", visitorid:"109156be-c4fb-41ea-b1b4-efe1671c580f", displayName:"", email:"", company:"", activeSubscriptionid:"", accountStanding:"good", bio:"", emailVerified:true, location:"", website:"", avatarUrl:"", numFollowers:0, numFollowing:0, numOrganizations:0, allowedRoles:[], relationship:{}, created:"", updated:"", tags:[], abTests:{"buckets":{"landingPageVideo":{"name":"video", value:1}, openAccessTwo:{"name":"normal", value:0}, sidedoorVideo:{"name":"play-video", value:1}}}, orgMode:"", orgDetails:"", level:"", userCapabilities:{}}, requestsFetching:false, authorizedClients:[], isLoggedIn:false, onboardThisSession:false, token:"eyJhbGciOiJIUzUxMiJ9.[binary].9zL3wK5ceD8ylOykw30wuN5JQLPNjArVYo7H-1R85OvTb2hHPTKekcZKYoW-fLhZhnRH22PXTfg23RD__wK3wA"}, discussion:{}, routing:{"locationBeforeTransitions":null}, siteStatus:{"uploadsOperational":true, queryOperational:true, websiteOperational:true, downloadsOperational:true, shouldAskReload:false, shouldForceReload:false, incidentName:"", incidentMessage:"", pageStatus:"n…
accepted answer: http://stackoverflow.com/a/52619555
downvote count: 2

http://stackoverflow.com/comment/92418608
score: 0
type: Comment
has text: The error indicates that you somewhere are trying to delete an item from a tuple. The only place I can fint that tries to delete something from something is `del numsam[syn]` but `numsam = nums` and `nums = list(nums)`. The only way I have been able to reproduce the error is if the argument to the function `num_expression()` is a tuple, which gives the result I described above. Try to print `nums` on the first line of the function to see what it looks like.
comment on: http://stackoverflow.com/a/52732531
type: AnswerComment

http://stackoverflow.com/comment/92398659
has text: Did you understand why you got the error in the first place? Whatever dataframe you have, its values are ```float``` type. But you are calling the string function ```split``` on them. How do you expect it to work? Either convert your coloumn or have a check so that split skips columns with float type.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52736900
score: 2

http://stackoverflow.com/q/52642360
answer count: 2
tagged with: python
has body: Is it possible to do something like that: class ParentClassName(object): name = camel_case_to_underscore(cls.__name__) class ChildClassName(Parent): pass assert Parent().name == "parent_class_name" assert Child().name == "child_class_name" assert Child.name == "child_class_name" assert getattr(Child, 'name') == "child_class_name" I would like to make a class, from which other classes can inherit and have got their name set basing on their class name. Is it possible in python 3?
score: 0
has title: Set class attribute after inheritance
tagged with: metaprogramming
upvote count: 1
accepted answer: http://stackoverflow.com/a/52642575
downvote count: 1
tagged with: inheritance
has comment: http://stackoverflow.com/comment/92217294
has comment: http://stackoverflow.com/comment/92218885
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52642456
has answer: http://stackoverflow.com/a/52642456
favorite count: 0
has answer: http://stackoverflow.com/a/52642575
type: Question

http://stackoverflow.com/q/52665935
type: Question
has comment: http://stackoverflow.com/comment/92261808
accepted answer: http://stackoverflow.com/a/52666053
answer count: 2
possible better answer: http://stackoverflow.com/a/52666051
has answer: http://stackoverflow.com/a/52666051
downvote count: 0
has comment: http://stackoverflow.com/comment/92261926
has comment: http://stackoverflow.com/comment/92262023
has comment: http://stackoverflow.com/comment/92261750
favorite count: 0
has body: I'm new in Python and I have a problem about the decimal library. Some questions require that all zeros after the decimal point located behind the last non-zero digit must be discarded.UVA11821 Such as 0.1230000 is an illegal answer .It should be converted into 0.123. I plan to do this question in python and decimal.However, I am not able to do the convert job. And here is my code. from decimal import * a=eval(input()) con=getcontext() con.prec=100 for i in range(0,a): summ=Decimal('0') while 1: num=Decimal(input()) if num==0: break; summ=summ+num print(summ)
has comment: http://stackoverflow.com/comment/92261877
has title: How to discard useless zero digits from decimals?
has answer: http://stackoverflow.com/a/52666053
tagged with: python
has comment: http://stackoverflow.com/comment/92261886
score: 2
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/comment/92241120
score: 0
comment on: http://stackoverflow.com/q/52654805
type: QuestionComment
has text: provide a [mcve]. How do you add the icons? Do you use a relative or absolute path or do you use qresource?
type: Comment

http://stackoverflow.com/comment/119303227
type: Comment
has text: Welcome to Stack Overflow. While this code may solve the question, [including an explanation](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
comment on: http://stackoverflow.com/a/67494888
score: 1
type: AnswerComment

http://stackoverflow.com/q/52698468
has title: Error when feeding numpy sequence to bidirectional LSTM in Keras
type: AnsweredQuestion
tagged with: lstm
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52736058
score: 2
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52736058
has body: I am trying to feed the features extracted from 2 fine-tuned VGG16 (each on a different stream), then for each sequence of 9 data pairs, concatenate their numpy arrays and feed the sequence of 9 outputs (concatenated) to a bi-directional LSTM in Keras. The problem is that I am running into an error when trying to build the LSTM part. The following shows the generator I wrote to read both RGB and Optical flow streams, extract features and concatenate each pair : def generate_generator_multiple(generator,dir1, dir2, batch_rgb, batch_flow, img_height,img_width): print("Processing inside generate multiple") genX1 = generator.flow_from_directory(dir1, target_size = (img_height,img_width), class_mode = 'categorical', batch_size = batch_rgb, shuffle=False ) genX2 = generator.flow_from_directory(dir2, target_size = (img_height,img_width), class_mode = 'categorical', batch_size = batch_flow, shuffle=False ) while True: imgs, labels = next(genX1) X1i = RGB_model.predict(imgs, verbose=0) imgs2, labels2 = next(genX2) X2i = FLOW_model.predict(imgs2,verbose=0) Xi = [] for i in range(9): Xi.append(np.concatenate([X1i[i+1],X2i[i]])) Xi = np.asarray(Xi) if np.array_equal(labels[1:],labels2)==False: print("ERROR !! problem of labels matching: RGB and FLOW have different labels") yield Xi, labels2[2] I am expecting the generator to yield a sequence of 9 arrays, so the shape of Xi when I force the loop to run twice is: (9, 14, 7, 512) When I use while True (like in the code above) and try to call the method to check what it returs, after 3 iterations I get the error: ValueError: too many values to unpack (expected 2) Now, assuming that there is no problem with the generator, I try to feed the data returned by the generator to the bidirectional LSTM like the following: n_frames = 9 seq = 100 Bi_LSTM = Sequential() Bi_LSTM.add(Bidirectional(LSTM(seq, return_sequences=True, dropout=0.25, recurrent_dropout=0.1),input_shape=(n_frames,14,7,512))) Bi_LSTM.add(GlobalMaxPool1D()) Bi_LSTM.add(Ti…
upvote count: 2

http://stackoverflow.com/comment/92376485
has text: I read it as *any one* sublist of `b`, i.e. a test for each one. But looking back it's not completely clear. Taking OP's example, `Here a[0] consist of 4 elements that is in b[0]`, this seems to be the implication.
comment on: http://stackoverflow.com/a/52722752
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/54460915
upvote count: 7
has body: An other solution would be to read your csv with the attribute index_col=0 to not take into account the index column : df = pd.read_csv(Location, index_col=0).
answers question: http://stackoverflow.com/q/52730814
type: Answer
downvote count: 0
score: 7

http://stackoverflow.com/q/52670115
tagged with: python
has comment: http://stackoverflow.com/comment/92273133
accepted answer: http://stackoverflow.com/a/52671784
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52671693
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92273075
has answer: http://stackoverflow.com/a/52671784
type: Question
has comment: http://stackoverflow.com/comment/92272465
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/92273039
has body: I'd like to create a correlation with one variable as the independent, and multiple additional variables as the dependent, and then turn it into a heat map. I'm following these directions. My code: df_corr_interest = df[df.columns[0:11]].corr()['impact_action_yn'][:-1] #set fig size fig, ax = plt.subplots(figsize=(20,15)) #plot matrix sns.heatmap(df_corr_interest, square=True,annot=True, annot_kws={'size':12},cmap="GnBu") plt.show(); I'm getting the following error: KeyError: 'impact_action_yn' Dataframe: ExternalReference interest_el interest_pl interest_ad interest_ol commitment_elected commitment_policy commitment_advocacy commitment_organizing timeline_elected ... Policy Organizing Engagement Parent Veteran first_gen_american first_gen_college ri_region LGBTQ Gender 0 0034000001RHCU0AAP 1 1 1 1 0 0 0 0 0 ... 0 0 1 0 0 0 0 0 0 Woman 1 00340000015yDbOAAU 1 1 1 2 0 0 0 2 0 ... 0 1 2 0 0 0 0 1 0 Man 2 0034000000y3QjMAAU 1 2 2 2 0 2 3 4 0 ... 5 2 3 0 0 0 0 1 0 Man 3 0034000001qcNXRAA2 1 1 1 3 0 0 0 3 0 ... 0 1 6 0 0 0 0 1 0 Woman 4 0034000001DVPedAAH 1 1 1 1 0 0 0 0 0 ... 0 0 1 0 0 0 0 0 0 Woman Thoughts? Updated with full list of vars: ExternalReference object interest_el int64 interest_pl int64 interest_ad int64 interest_ol int64 commitment_elected int64 commitment_policy int64 commitment_advocacy int64 commitment_organizing int64 timeline_elected int64 timeline_policy int64 timeline_advocacy int64 timeline_organizing int64 interest_appointed float64 interest_vol_organizing float64 interest_school_organizing float64 impact_action_yn float64 impact_action_public_action float64 impact_action_testified float64 impact_action_met_el float64 impact_action_lobbied float64 impact_action_bill float64 impact_action_other float64 impact_action_other_text object impact_topic_charter_schools float64 impact_topics_ece float64 impact_topics_postsecondary float64 impact_topics_school_choice float64 impact_topics_student_achv float64 impact_topics_district_perf float64 impact_topic…
linked to: http://stackoverflow.com/q/34896455
has comment: http://stackoverflow.com/comment/92273099
tagged with: pandas
has comment: http://stackoverflow.com/comment/92272394
favorite count: 0
tagged with: correlation
has title: Pandas df.corr - one variable across multiple cols
has comment: http://stackoverflow.com/comment/92271635
has answer: http://stackoverflow.com/a/52671693

http://stackoverflow.com/comment/92237792
comment on: http://stackoverflow.com/q/52652397
type: Comment
score: 1
type: QuestionComment
has text: For the expected output on row 6, shouldn't that be `NaN`? The reason being is that row six has a signal value of one, thus creating a new group where the current row is ignored. I realize that the value was set due to the signal on row 5, but my question is really how you intend to handle conflicts such as this.

http://stackoverflow.com/comment/92387247
has text: Why don't you only groupby `Company name` if you want to iterate over it?
type: QuestionComment
comment on: http://stackoverflow.com/q/52721807
score: 0
type: Comment

http://stackoverflow.com/q/52639892
tagged with: python
type: AnsweredQuestion
score: 3
has title: Changing x-axis labels in errorbar plot: no attribute 'get_xticklabels'
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/92215256
has answer: http://stackoverflow.com/a/52641060
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92213577
has comment: http://stackoverflow.com/comment/92212528
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52641060
has body: I am trying to plot some data the main plot information is ax1 = plt.errorbar(df1.index, df1['Mean'], yerr=df1['SD'], color='black', linestyle='-') ax2 = plt.errorbar(df2.index, df2['Mean'], yerr=df2['SD'], color='grey', linestyle='-') The problem is each data frame index is 5% increments of a whole (i.e. df1 index is 0,5,10...100 as is df2) the result is the plot is trying to cram 40 labels on the x-axis I have tried a few different approaches but none have worked so far. For example trying to rotate the labels and reduce font size, e.g.: plt.setp(ax1.get_xticklabels(), rotation='vertical', fontsize=7) returns AttributeError: 'ErrorbarContainer' object has no attribute 'get_xticklabels' I get the same error if I try to alter the x axis of ax1 and ax2 using tick_params I think it may be because the plot is seeing the x-axis as categorical but I'm stumped on how to fix it? Ideally I would like to just show the 0, 25, 50, 75 and 100% labels for ax1 and ax2, but at this point I'd be happy with just rotating them so they look better.
upvote count: 3

http://stackoverflow.com/a/52723084
answers question: http://stackoverflow.com/q/52722817
has comment: http://stackoverflow.com/comment/92371467
downvote count: 0
score: 1
has body: Well their is a function in the api - ia.get_movie_release_dates(episodeid) This will fetch the release date of that episode in all the countries. Then you can just fetch the country and its release date according to your need.
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52722817
type: Answer

http://stackoverflow.com/comment/92379606
comment on: http://stackoverflow.com/a/52727083
has text: I accidentally tagged this as python3, but it is python 2. Your code is doing the exact same thing that my code does.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52687199
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92301675
tagged with: python-3.x
has body: So I have been playing around with linear congruential generators but I am stuck on the idea that once a script has been run, it always generates the same way. If I run a script such as this; import random print(random.randrange(0,9)) It will generate a new random number each time the script is run. I'm wondering how it does this. So this is what I have gotten so far; from collections import Counter class linearCongruentialGenerator(object): def __init__(self, lowBound, highBound, length): self.lowBound, self.highBound, self.length = lowBound, highBound, length self.modulus = 20226231145#modulus self.multiplier = 104743412357321567#multiplier self.increment = 1049592131123467#increment self.seed = 43123211114#seed def __iter__(self): while self.length &gt; 0: self.length -= 1 self.seed = (self.multiplier*self.seed + self.increment) % self.modulus yield (self.seed % self.highBound) def linearCongruentialGenerator(self, first, last): self.seed = (self.multiplier*self.seed + self.increment) % self.modulus return self.seed def binary(self): self.seed = (self.multiplier*self.seed + self.increment) % self.modulus self.seedLength = len(str(seed)) return (self.seed // 10**1 % 10) % 2 if __name__ == "__main__": random = linearCongruentialGenerator(0, 9, 100) random1 = linearCongruentialGenerator(0, 9, 100) list1 = [] list2 = [] for i in random: list1.append(i) for j in random1: list2.append(j) print(Counter(list1)) print(len(set(list1))) print(Counter(list2)) print(len(set(list2))) This script counts the numbers generated by the linearCongruentialGenerator class then prints the distribution: number:count. I want the script to generate new values every time I run the script. Without using the random class that comes with python. Because that is cheating :D Not sure how to approach this, any tips?
tagged with: python
accepted answer: http://stackoverflow.com/a/52687283
score: 2
has title: How does the Random module generate a new number in python
type: AnsweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/52687283
type: Question
has comment: http://stackoverflow.com/comment/92301653
has comment: http://stackoverflow.com/comment/92301745
upvote count: 3
has comment: http://stackoverflow.com/comment/92301808
has comment: http://stackoverflow.com/comment/92301910

http://stackoverflow.com/comment/92320548
comment on: http://stackoverflow.com/a/52696818
type: Comment
score: 0
has text: @Brock Updated the timings.
type: AnswerComment

http://stackoverflow.com/comment/92145499
score: 0
type: Comment
type: AnswerComment
has text: Thank you for your answer! Does this work as well if dataframe B already has an id column with a NaN value? Does this overwrite that id to an id from dataframe A?
comment on: http://stackoverflow.com/a/52605625

http://stackoverflow.com/comment/92341510
has text: @sascha but the way I have modeled that uses constraint(compatible values), however that's why I think as it is.. Also I have such more constraints to add for this, for the convenience I asked one one initially..
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52706839
type: QuestionComment

http://stackoverflow.com/comment/92387461
comment on: http://stackoverflow.com/q/52730200
score: 0
has text: Welcome to StackOverflow. Your question does not quite meet the standards that StackOverflow expects. Your question in its current state will likely not get accepted. I would highly suggest that you edit your question following the guidelines of [this StackOverflow article](https://stackoverflow.com/help/how-to-ask)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92206424
type: QuestionComment
has text: The function *recurses*, calls itself again to handle a subset of the problem.
comment on: http://stackoverflow.com/q/52636650
score: 0
type: Comment

http://stackoverflow.com/a/52610527
downvote count: 0
score: 1
has body: You can call sorted() on the file (because opened text files act like a list of lines when iterated over) with a function that takes a single line and extracts the thing between the brackets as the key= parameter import re def extract_presentation_index(line): return int(re.search(&quot;\[\s*(\d+)\s*\]$&quot;, line).group(1)) # alternatively, you don't have to use regex #return int(line.split('[')[2].split(']', 1)[0].strip()) with open('/path/to/your/file') as f: sorted_lines = sorted(f, key=extract_presentation_index) print(''.join(sorted_lines), end='') The end='' is just so you aren't adding an extra newline character (\n) at the end.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52609724

http://stackoverflow.com/q/52667764
has comment: http://stackoverflow.com/comment/92265742
score: 1
has comment: http://stackoverflow.com/comment/92265679
type: Question
tagged with: discord.py
has title: Discord.py rewrite multi server data
linked to: http://stackoverflow.com/q/52612358
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/56904087
favorite count: 0
tagged with: python
tagged with: discord
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
has body: So I've been working with discord.py for a while now and recently switched over to discord.py-rewrite. I can't seem to find anything really about how to do this. But I would like to have like per guild data. For example if the bot is in Server 1 and Owner1 does -prefix !! it would add that to their prefixes but only in their guild. So it would not be a prefix in Server2. Any help would be great. I've been told I can do this with JSON files but can't find anything on it for what I want.
linked to: http://stackoverflow.com/q/51915962

http://stackoverflow.com/q/52671564
score: 1
tagged with: pyspark
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/92272955
favorite count: 0
has body: I am getting an error using pyspark on Anaconda Python 3.6. The error message is SparkException: Job aborted due to stage failure: Task 59 in stage 5.0 failed 1 times. This a full traceback: --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) &lt;ipython-input-9-aa2b9549c767&gt; in &lt;module&gt;() 1 import pyspark.sql.functions as F ----&gt; 2 categ = df.select('Event').distinct().rdd.flatMap(lambda x:x).collect() ~\AppData\Local\conda\conda\envs\xgboost\lib\site-packages\pyspark\rdd.py in collect(self) 812 """ 813 with SCCallSiteSync(self.context) as css: --&gt; 814 sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) 815 return list(_load_from_socket(sock_info, self._jrdd_deserializer)) 816 ~\AppData\Local\conda\conda\envs\xgboost\lib\site-packages\py4j\java_gateway.py in __call__(self, *args) 1255 answer = self.gateway_client.send_command(command) 1256 return_value = get_return_value( -&gt; 1257 answer, self.gateway_client, self.target_id, self.name) 1258 1259 for temp_arg in temp_args: ~\AppData\Local\conda\conda\envs\xgboost\lib\site-packages\pyspark\sql\utils.py in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---&gt; 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() ~\AppData\Local\conda\conda\envs\xgboost\lib\site-packages\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name) 326 raise Py4JJavaError( 327 "An error occurred while calling {0}{1}{2}.\n". --&gt; 328 format(target_id, ".", name), value) 329 else: 330 raise Py4JError( Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 59 in stage 5.0 failed 1 times, most recent failure: Lost task 59.0 in stage 5.0 (TID 64, localhost, executor driver): org.apache.spark.api.python.PythonException: Traceback (most recent call last…
has comment: http://stackoverflow.com/comment/92273045
tagged with: python
has title: Error occured when creating dummy variables-SparkException: Job aborted due to stage failure: Task 59 in stage 5.0 failed 1 times
tagged with: python-3.x
answer count: 0
linked to: http://stackoverflow.com/q/46528207
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/92286874
type: AnswerComment
has text: oh.. i see. but, how to add the range of the map? i use "n" as the first argument to give the range of map
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52679091

http://stackoverflow.com/comment/92486857
comment on: http://stackoverflow.com/a/52720802
has text: I haven't actually put it all together, but I figure the best way to do it is to handle each os separately. I think I can merge the answer you provided me for windows with the linux version with some sort of conditional if I really need to. Thanks for the windows solution!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52724487
upvote count: 1
has comment: http://stackoverflow.com/comment/92374571
type: Question
score: 1
has comment: http://stackoverflow.com/comment/92374478
has title: Custom renderer breaking site
answer count: 1
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52724883
has body: I'm new to the DJango world, having just started up my first Python job a few months ago (PHP dev for the last decade). I'm working with Django REST API on an endpoint where I need to return an XML string, but from looking around, seems like none of the built in renderers allow you to simply pass a string to be returned as is? I saw that `HTTPResponse` works, but `Response` doesn't, and a coworker told me that `Response` is a better choice and to create a renderer. I thought it seemed pretty simple based on source code, with basically this being the bare minimum: class PassThroughRenderer(BaseRenderer): media_type = None format = None def render(self, data, accepted_media_type=None, renderer_context=None): return data My view (trimmed a bit, but only some model storage): def post(self, request): original_soap = request.body try: parsed_soap = xmltodict.parse(original_soap) except xml.parsers.expat.ExpatError: return Response(dicttoxml({'invalid_xml': True}), content_type='text/xml', status=422) parsed_soap = self.strip_sf_prefix(parsed_soap) config = yaml.load(settings.SALESFORCE_CRED) organization_id = config['organization_id'] if parsed_soap['soapenv:Envelope']['soapenv:Body']['notifications']['OrganizationId'] != organization_id: return Response(dicttoxml({'unauthorized': True}), content_type='text/xml', status=401) return Response(SALESFORCE_RESPONSE, content_type='text/xml') Unfortunately, when I run that (having added renderer_classes = (utils.PassThroughRenderer,) to my APIView class), I get 'Request' object has no attribute 'accepted_renderer' and a traceback that doesn't seem to hit any code I've written.
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/52725910
has comment: http://stackoverflow.com/comment/98841953
has comment: http://stackoverflow.com/comment/92380295
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/92382463
has body: I am trying to add a conditional formatting rule to a workbook with the openpyxl module in Python. I want to format ONLY the right border of a cell, if I do so, it removes all the other borders which I want to set to default, so that it doesn't overwrite borders which are already set/activated in the sheet. Look at the following example which should only add a right border: import openpyxl from openpyxl.styles import Border, Side from openpyxl.formatting.rule import FormulaRule border = Border(right=Side(color='FF000000', border_style="thick")) worksheet.conditional_formatting.add('$A$1:$A$2', FormulaRule(formula=['A1="test"'], stopIfTrue=True, border=border)) the code removes all the other borders... this is my desired result which I cannot achieve with openpyxl: I couldn't find any Classes, variables or values which I could assign to the other parameters -> borders so that they wouldn't get erased. I appreciate any tips.
answer count: 0
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/98766699
has comment: http://stackoverflow.com/comment/92381325
upvote count: 1
has title: Excel Conditional Formatting with openpyxl in Python - Borders
favorite count: 0

http://stackoverflow.com/comment/92169085
comment on: http://stackoverflow.com/a/52617244
type: Comment
has text: it was: `out_put = K.concatenate(branch_outputs)`, I removed the `K.`and worked. Your answer helped me understand it, so if you want you can add it to your answer and i'll accept it
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92183547
score: 0
type: AnswerComment
has text: It seems the reason NOT to do it is mostly from bad performance if I plan to do computations on that column? is that correct? or any computation on the rest of the dataframe will be slow too? My main reason for wanting to set the lists in cells is so I could sort the dataframe based on other columns, and then extract the lists in the order needed
type: Comment
comment on: http://stackoverflow.com/a/52625146

http://stackoverflow.com/q/52740893
has comment: http://stackoverflow.com/comment/92406883
tagged with: python
tagged with: timestamp
type: AnsweredQuestion
has title: Python Timestamp Dataframe Only Number/Decimal Filtering
accepted answer: http://stackoverflow.com/a/52741151
score: 0
tagged with: dataframe
type: Question
answer count: 1
tagged with: filter
has answer: http://stackoverflow.com/a/52741151
has body: I have a dataframe df['Timestamp'] 153917800000 Applying .iso8601 returns as an object in the format %Y-%m-%dT%H:%M:%S.%f I presume. df['Timestamp'] 2018-10-10T12:52:00.000Z I would like to filter/remove/replace the dashes "-", and ":", and Timezones: "Z" to "" Desired Output: df['Timestamp'] 20181010125200000 dtype:float Desired Application: Manual function that requires float input Attempts df['Timestamp'] = pd.to_datetime(df['Timestamp'], format='%Y-%m-%dT%H:%M:%S.%f').dt.strftime('%Y%m%d').astype(float) df['Timestamp'] = (df['Timestamp'].filter(_.isdigit()))

transpose
tags question: http://stackoverflow.com/q/52680963
tag name: transpose
type: Tag

http://stackoverflow.com/comment/92199356
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52632500
type: Comment
has text: how do i add "my_dict={i:['test'] for i in my_list}" into my code so i can test to see if it works? by the way "splitlines" does not exist for some reason and i don't know why. it returns attribute error

http://stackoverflow.com/comment/92314888
comment on: http://stackoverflow.com/a/52692779
type: Comment
score: 0
has text: @slashdotblake I see what you mean. I've added a possible solution without using dictionaries. The advantage of the second solution is that it does not use any additional space for a dict. While this is a good exercise, if space is not an issue, I would still encourage you to use a counter object for more readable code in real world applications.
type: AnswerComment

http://stackoverflow.com/comment/92393988
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52734263
has text: Yes. Geometric mean of height by Category.
score: 0

http://stackoverflow.com/q/52704808
has comment: http://stackoverflow.com/comment/92336347
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52705085
has title: Python *args returns tuple rather than pandas dataframes
has comment: http://stackoverflow.com/comment/92336437
score: 0
has answer: http://stackoverflow.com/a/52705118
tagged with: pandas
has comment: http://stackoverflow.com/comment/92336266
possible better answer: http://stackoverflow.com/a/52705118
tagged with: args
has comment: http://stackoverflow.com/comment/92336272
has answer: http://stackoverflow.com/a/52705085
tagged with: python
type: AnsweredQuestion
has body: Have a function that returns a series of dataframes. def frames(): bla bla return df1, df2, df3, df4 I would like to write a function that will append these frames together without my having to list the count so that I can have more or fewer frames in future def appender(*args): condition goes here append things that are true I'd like to be able to call it such that appender(frames()) will return a full frame of frames that passed the condition. Right now the frames() function returns a tuple of four frames. Is there any easy fix to unpack the tuple? Thanks for any help! Clem UPDATE Here's an example def frames(): df1 = pd.DataFrame() df2 = pd.DataFrame() df3 = pd.DataFrame(['not', 'empty']) df4 = pd.DataFrame(['not', 'empty']) return df1, df2, df3, df4 def appender(*args): main_frame = pd.DataFrame() for arg in args: if arg.empty != True: assignment_frame = assignment_frame.append(arg) return assignment_frame appender(frames()) gives AttributeError Traceback (most recent call last) in () ----> 1 appender(frames()) in appender(*args) 2 main_frame = pd.DataFrame() 3 for arg in args: ----> 4 if arg.empty != True: 5 assignment_frame = assignment_frame.append(arg) 6 AttributeError: 'tuple' object has no attribute 'empty'

http://stackoverflow.com/a/52717322
has comment: http://stackoverflow.com/comment/135423652
accepted answer of: http://stackoverflow.com/q/52717176
type: Answer
upvote count: 3
has body: If you do it like this it should work fine in 2.7: from xml.etree.ElementTree import Element, SubElement, tostring parent = Element('parent') ch = SubElement(parent, 'child') ch.set('name', 'George') print tostring(parent, method='html') # print tostring(child, method='html') #
downvote count: 0
score: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52717176

http://stackoverflow.com/q/52670685
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/52671018
tagged with: python
has title: Web scraping issue while scraping from one table using beautifulsoup
score: 0
has body: import requests from bs4 import BeautifulSoup page = requests.get('http://www.freejobalert.com/ap-govt-jobs/144586/') c = page.content soup = BeautifulSoup(c,"html5lib") row = soup.find_all("table")[0].find_all('tr') dict = {} for i in row: for title in i.find_all('span', attrs={'style':'color: #008000;'}): dict['Title'] = title.text for link in i.find_all('a',title=True, href=True): dict['Link'] = link['href'] print(dict) Here i am getting empty data: I am expecting: {'Link': 'http://www.freejobalert.com/wp-content/uploads/2018/08/Detailed-Notification-Directorate-of-Public-Health-Family-Welfare-Vijayawada-Civil-Assistant-Surgeon-Posts.pdf', 'Title': 'Detailed Notification'} {'Link': 'http://www.freejobalert.com/wp-content/uploads/2018/08/Notification-Directorate-of-Public-Health-Family-Welfare-Vijayawada-Civil-Assistant-Surgeon-Posts.pdf', 'Title': 'Notification '} {'Link': 'http://cfw.ap.nic.in/', 'Title': ' Official Website'} Here i am scraping data from only first table. but it is giving me data from all the tables.. I want only important links from first table. but it is giving me both. please have a look into my code.
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52671018
answer count: 1

http://stackoverflow.com/q/52666736
answer count: 0
has comment: http://stackoverflow.com/comment/92264170
type: Question
tagged with: python-multiprocessing
tagged with: multiprocessing
score: 0
tagged with: bash
has title: Difference of executing python script with multprocessing lib and in bash with &-operator
tagged with: linux
type: UnansweredQuestion
has body: I have a python script that makes some DB reads and writes and calculates something - let's say calculating.py. It takes a lot of time depending on the number of DB entries and therefore I thought I could speed it up by multiple executing of the script. I've read some good articles about the multiprocessing lib for python and think that's how I can do it (I've also read about threading). If I wrap my code of calculating.py in a function, it could be something like this: from multiprocessing import Process def calculate(): #do something print("that's it") if __name__ == '__main__': p1 = Process(target=calculate) p2 = Process(target=calculate) p3 = Process(target=calculate) p4 = Process(target=calculate) p1.start() p2.start() p3.start() p4.start() p1.join() p2.join() p3.join() p4.join() print('all done') I'm curious, what's the difference to just doing multiple executions as subprocesses in bash, like: #!/bin/bash python3 calculate.py &amp; python3 calculate.py &amp; python3 calculate.py &amp; python3 calculate.py &amp; I don't have the server setup now, but if I would have 2 CPU cores with 4 threads I would expect a 4 times faster speed as a single execution/process of calculating.py. How do both ways differ, multiple executions as a subprocess and using the multiprocessing lib, technically which is faster and more efficient regarding resources?
tagged with: python
has comment: http://stackoverflow.com/comment/92263276
has comment: http://stackoverflow.com/comment/92592330
has comment: http://stackoverflow.com/comment/93247097

http://stackoverflow.com/a/52689127
has comment: http://stackoverflow.com/comment/92305247
has comment: http://stackoverflow.com/comment/92305751
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52688645
type: Answer
has comment: http://stackoverflow.com/comment/92305717
downvote count: 0
has body: The reason why this does not work is because the %H parameter only accepts values in the range of 00 to 23 (both inclusive). This thus means that 24:00 is - like the error says - not a valid time string. I think therefore we have not much other options than convert the string to a valid format. We can do this by first replacing 24:00 with 00:00, and then later increment the day for these timestamps. Like: from datetime import timedelta import pandas as pd df['datetime_zero'] = df['datetime'].str.replace('24:00', '0:00') df['datetime_er'] = pd.to_datetime(df['datetime_zero'], format='%d/%m/%Y %H:%M') selrow = df['datetime'].str.contains('24:00') df['datetime_obj'] = df['datetime_er'] + selrow * timedelta(days=1) The last line thus adds one day to the rows that contain 24:00, such that '10/11/2006 24:00' gets converted to '11/11/2006 24:00'. Note however that the above is rather unsafe since depending on the format of the timestamp this will/will not work. For the above it will (probably) work, since there is only one colon. But if for example the datetimes have seconds as well, the filter could get triggered for 00:24:00, so it might require some extra work to get it working.
score: 3
has comment: http://stackoverflow.com/comment/92305772
has comment: http://stackoverflow.com/comment/92305697
has comment: http://stackoverflow.com/comment/92305369
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92305228
answers question: http://stackoverflow.com/q/52688645

http://stackoverflow.com/a/52694455
has comment: http://stackoverflow.com/comment/92316443
has comment: http://stackoverflow.com/comment/92315996
type: Answer
has comment: http://stackoverflow.com/comment/92316155
downvote count: 0
score: 1
has body: For this we could designate kw(keyword) as river then we can use list comprehension to grab all of the items that contain this kw, note some sentences contain rivers so kw in will not work. From here now we can construct a dictionary using dictionary comprehension, we would use j representing each word in i.split() and i.count(j) to represent the count of each word in each item, we will also throw in if j != kw so we don't include river in our list. Finally we can print using for k, v in dicta.items() and if we want can add sorting method to this to get our results alphabetically in order. kw = 'river' lista = [i for i in temp for j in i.split() if j == kw] dicta = {j: i.count(j) for i in lista for j in i.split() if j != kw} for k, v in sorted(dicta.items(), key=lambda x: x[0]): print('{}: {}'.format(k, v)) atlantic: 1 branch: 1 commonplace: 1 considering: 1 contrary: 1 country: 1 ... twenty-eight: 1 uses: 1 vast: 1 water: 1 ways: 1 world: 1 world--four: 1 Expanded loops: lista = [] for i in temp: for j in i.split(): if j == kw: lista.append(i) dicta = {} for i in lista: for j in i.split(): dicta[j] = i.count(j) Addtional Request: Read all entire file into one variable as string all_words = 'some string' all_words = all_words.split() unique = set(all_words) for i in unique: kw = i temp = list of sentences to check against rest of existing code maybe instead of printing the final statement append the dictionaries created to a list
has comment: http://stackoverflow.com/comment/92316135
has comment: http://stackoverflow.com/comment/92316402
has comment: http://stackoverflow.com/comment/92316098
has comment: http://stackoverflow.com/comment/92316052
has comment: http://stackoverflow.com/comment/92316550
has comment: http://stackoverflow.com/comment/92316115
accepted answer of: http://stackoverflow.com/q/52694400
upvote count: 1
answers question: http://stackoverflow.com/q/52694400
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92315945

http://stackoverflow.com/a/52716389
has body: with open ('line.txt') as file: f = open('output.txt','w') for line in file.read().split("\n")[1::3]: outputline=line f.write(outputline) f.close()
answers question: http://stackoverflow.com/q/52715972
score: 0
type: Answer

http://stackoverflow.com/comment/92357918
comment on: http://stackoverflow.com/q/52716267
has text: No, you will have to use an html parser (eg BeautifulSoup) for that
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/92190336
type: QuestionComment
comment on: http://stackoverflow.com/q/52627904
type: Comment
score: 1
has text: Totally unrelated, but you will have serious issues with `today` being defined as a global - it means it will only be defined once per process at process start time and never change until the next restart. Given how django server processes are usually handled on a typical production setup this will be a lot of fun to debug xD

http://stackoverflow.com/comment/92282265
has text: @tehhowch To be fair, the Questioner is running Google's same code [word-for-word](https://developers.google.com/sheets/api/quickstart/python). I have not doubt that `oauth2client` is deprecated but you implied that the questioner would/should know that ("_after all_"), and I don't know how someone who is running Google's own tutorial code might have been expected to know that.
score: 0
comment on: http://stackoverflow.com/q/52667908
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52595723
has answer: http://stackoverflow.com/a/52596238
has comment: http://stackoverflow.com/comment/92127116
has title: Replacing text from one file from another file
possible better answer: http://stackoverflow.com/a/52595905
linked to: http://stackoverflow.com/q/254350
has comment: http://stackoverflow.com/comment/92126278
score: 0
has answer: http://stackoverflow.com/a/52595905
answer count: 2
has comment: http://stackoverflow.com/comment/92126244
favorite count: 0
accepted answer: http://stackoverflow.com/a/52596238
has comment: http://stackoverflow.com/comment/92126640
has comment: http://stackoverflow.com/comment/92126343
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92126267
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92126249
has body: The f1.write(line2) works but it does not replace the text in the file, it just adds it to the file. I want the file1 to be identical to file2 if they are different by overwriting the text from file1 with the text from file2 Here is my code: with open("file1.txt", "r+") as f1, open("file2.txt", "r") as f2: for line1 in f1: for line2 in f2: if line1 == line2: print("same") else: print("different") f1.write(line2) break f1.close() f2.close()
downvote count: 1
type: Question

http://stackoverflow.com/q/52647318
favorite count: 0
tagged with: python
has body: I have a dataframe including a certain condition, a counter of how many consecutive times the condition occurs, and a certain value, that looks like this: date condition count Value1 Value2 01,01,2018 08:00 A 1 0 0 01,01,2018 08:01 A 2 0 0 01,01,2018 08:02 A 3 0 0 01,01,2018 08:03 B 1 1 1 01,01,2018 08:04 B 2 0 1 01,01,2018 08:05 B 3 0 1 01,01,2018 08:06 B 4 0 0 01,01,2018 08:07 C 1 0 0 01,01,2018 08:08 C 2 0 0 01,01,2018 08:09 C 3 0 0 01,01,2018 08:10 C 4 0 0 01,01,2018 08:11 C 5 0 0 01,01,2018 08:12 A 1 0 0 01,01,2018 08:13 A 2 0 0 01,01,2018 08:14 B 1 0 0 01,01,2018 08:15 B 2 0 1 01,01,2018 08:16 B 3 0 1 01,01,2018 08:17 C 1 0 0 I would like to add another column "error" which has value 1 under the condition: if value1=1 and condition=B when count=1, then assign error=1 as long as value2=1. It should look like: date condition count Value1 Value2 error 01,01,2018 08:00 A 1 0 0 0 01,01,2018 08:01 A 2 0 0 0 01,01,2018 08:02 A 3 0 0 0 01,01,2018 08:03 B 1 1 1 1 01,01,2018 08:04 B 2 0 1 1 01,01,2018 08:05 B 3 0 1 1 01,01,2018 08:06 B 4 0 0 0 01,01,2018 08:07 C 1 0 0 0 01,01,2018 08:08 C 2 0 0 0 01,01,2018 08:09 C 3 0 0 0 01,01,2018 08:10 C 4 0 0 0 01,01,2018 08:11 C 5 0 0 0 01,01,2018 08:12 A 1 0 0 0 01,01,2018 08:13 A 2 0 0 0 01,01,2018 08:14 B 1 0 0 0 01,01,2018 08:15 B 2 0 1 0 01,01,2018 08:16 B 3 0 1 0 01,01,2018 08:17 C 1 0 0 0 Please note that the second time the condition B occurs, value1 never gets equal to 1, so even if value2=1 there is no error. I have tried things like: df['error']=np.where(((df['value1']==1) &amp; (df['condition']=='B') &amp; df['value2']==1)) | ((df['error'].shift(1)=='1')&amp;(df['value2']==1))),'1', 0) but it gives me key error, because I am calling df['error'].shift(1)=='1' in the where-conditions while the column itself "doesn't exist yet". Any idea? thank you in advance for your help!
has comment: http://stackoverflow.com/comment/92226905
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52648122
accepted answer: http://stackoverflow.com/a/52648122
has title: Pandas: assign values to a column, as long as a condition persists and a certain value appears in another column
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92227548
type: Question
has comment: http://stackoverflow.com/comment/92226834
tagged with: python-2.7
tagged with: pandas
upvote count: 1
answer count: 1

http://stackoverflow.com/q/52607135
accepted answer: http://stackoverflow.com/a/52607429
possible better answer: http://stackoverflow.com/a/52607639
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52607639
favorite count: 0
tagged with: text-files
tagged with: mod-rewrite
has comment: http://stackoverflow.com/comment/92148644
has answer: http://stackoverflow.com/a/52607429
type: AnsweredQuestion
has body: I am trying to open a text file, read it and after using a regex function to find which lines to edit, modify my text file. However what happens is that after finding the lines and edit them i can not write the modified Content in the text file again. remove_commas = re.compile("House") answer = {} global line1 with open("\DEMO_houses.txt", "r") as inp: for line in inp: if remove_commas.match(line): line1 = line.replace(',', '') print line1 with open("DEMO_houses.txt", "w") as document1: document1.write(line1) What happens is that it just delets my text file, and writes only the first line modified. Text file is something like this: Street : Blue, Red House: Big, enough Garden : green, not green And in the new text file i Need something like: Street : Blue, Red House: Big enough Garden : green, not green If anyone could help me I would really appreciate it. Thanks
upvote count: 5
has title: How to read and write a text file in the same time in python?
type: Question
answer count: 2
score: 5
downvote count: 0

http://stackoverflow.com/comment/92276249
type: QuestionComment
has text: @NielsNet It's a little confusing here, but doesn't "not copy" means "share"?
comment on: http://stackoverflow.com/q/52673223
score: 0
type: Comment

http://stackoverflow.com/comment/92401590
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52725323
type: Comment
has text: The "hack" I propose does work. BTW hack? :) ... the difference with yours is that you are only accounting for bigger variance of Y with respect to X, and it fails when it is the other way around (try the script I posted as solution, you will see that your solution starts failing when var(X)> var(Y)).

http://stackoverflow.com/a/52667415
score: 1
upvote count: 1
downvote count: 0
has body: You've decorated both functions with the base route "/". As it stands, this means that Flask will only run the first function when you hit the base route of your URL. If you want to keep distance() as a separate function, remove the @app.route decorator, modify it to return the value you want to display on the page, and then call this function from within your tempReading() function, adding the return value to your templateData dictionary.
answers question: http://stackoverflow.com/q/52665888
type: Answer

http://stackoverflow.com/q/52624875
has comment: http://stackoverflow.com/comment/92183530
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52626602
has body: How do we get a list of scripts running in crontab between particular time say 4:00PM to 8:00PM using python crontab I am getting list of all the jobs running in crontab by that user but not able to get at that particular time. tried this way: getting list of all scripts. from crontab import CronTab import datetime import croniter cron = CronTab("user") for j in cron: print j tried for between that particular timings: from crontab import CronTab import datetime import croniter cron = CronTab("pfmuser") for j in cron: hour = int(j.split()[1]) minutes = int(j.split()[0]) if hour &gt;= 16 and hour &lt;= 20: print('fond a job running between 16 and 20') got error:AttributeError: 'CronItem' object has no attribute 'split' error is done but ***but now i have: 1) 10 0 * * 5 2) 0 3 1 * * 3) 0 0 * * * 4) 0 1 * * * 5) 0 10 * * * now if have some problem and the cron scripts didnt run then if i am running for 0-10th hour then i need only 3) 0 0 * * * 4) 0 1 * * * 5) 0 10 * * * these scripts only should run 1) 10 0 * * 5 (only friday) 2) 0 3 1 * * (only 1st month) these should not run how to keep this may be can i use datetime and get that particular details later compare with the cron info.How do i go*** edited script with the suggestions given below: from crontab import CronTab import datetime from croniter import croniter as ci cron = CronTab("pfmuser") for cronitem in cron: cronitemstr = str(cronitem) hour = cronitemstr.split()[1] minutes = cronitemstr.split()[0] minutesint = None hourint = None try: hourint = int(hour) minutesint = int(minutes) except ValueError as e: print e.message if hourint &gt;= 16 and hourint &lt;= 20: cronitemstr = cronitemstr[:cronitemstr.index(cronitemstr.split()[5])] min=cronitemstr.split()[0] dom=cronitemstr.split()[2] mon=cronitemstr.split()[3] dow=cronitemstr.split()[4] date_time=datetime.datetime.now() try: if(min=='*' and dom=='*' and mon=='*' and dow=='*' ): print cronitemstr print cronitem else: print "none" except Exception as e: print "e…
downvote count: 0
answer count: 1
favorite count: 0
has title: Crontab to get list of scripts at particular intervals
tagged with: cron
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52624483
tagged with: c#
has body: Requirement: Invoke Python script (on server) via C#, e.g. via webapi. Here restful endpoint receives parameter (e.g. via GET request) and results from Python execution is returned (e.g. as JSON). I am aware of this: How do I run a Python script from C#? I have used this approach in the past. For data exchange I used: C# writes data to file system (e.g. from GET request's query strings) C# invokes Python, which picks up data from file system and writes results to file system C# reads data from file system and returns (e.g. as JSON) Just wondering are there neater ways to integrate 'pure' Python these days?
has comment: http://stackoverflow.com/comment/92183689
score: 0
tagged with: asp.net-web-api2
has comment: http://stackoverflow.com/comment/92183874
tagged with: .net
tagged with: asp.net-web-api
has comment: http://stackoverflow.com/comment/92189200
has comment: http://stackoverflow.com/comment/92183998
has comment: http://stackoverflow.com/comment/92183801
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/11779143
has comment: http://stackoverflow.com/comment/92184783
tagged with: python
has comment: http://stackoverflow.com/comment/92184035
answer count: 0
has comment: http://stackoverflow.com/comment/92184158
has title: Integrate 'pure' Python with .Net
type: Question
has comment: http://stackoverflow.com/comment/92185041

function
tags question: http://stackoverflow.com/q/52617498
tags question: http://stackoverflow.com/q/52747036
tag name: function
tags question: http://stackoverflow.com/q/52632522
tags question: http://stackoverflow.com/q/52664372
tags question: http://stackoverflow.com/q/52730675
tags question: http://stackoverflow.com/q/52638031
tags question: http://stackoverflow.com/q/52704241
tags question: http://stackoverflow.com/q/52692602
tags question: http://stackoverflow.com/q/52617814
tags question: http://stackoverflow.com/q/52710901
tags question: http://stackoverflow.com/q/52673075
tags question: http://stackoverflow.com/q/52651270
tags question: http://stackoverflow.com/q/52618197
tags question: http://stackoverflow.com/q/52669426
tags question: http://stackoverflow.com/q/52669368
tags question: http://stackoverflow.com/q/52725125
tags question: http://stackoverflow.com/q/52598527
type: Tag
tags question: http://stackoverflow.com/q/52652066
tags question: http://stackoverflow.com/q/52601778
tags question: http://stackoverflow.com/q/52618507
tags question: http://stackoverflow.com/q/52711980
tags question: http://stackoverflow.com/q/52717452
tags question: http://stackoverflow.com/q/52690801
tags question: http://stackoverflow.com/q/52629354
tags question: http://stackoverflow.com/q/52665487
tags question: http://stackoverflow.com/q/52693477
tags question: http://stackoverflow.com/q/52682614
tags question: http://stackoverflow.com/q/52740724
tags question: http://stackoverflow.com/q/52600980
tags question: http://stackoverflow.com/q/52692222
tags question: http://stackoverflow.com/q/52688356
tags question: http://stackoverflow.com/q/52599925
tags question: http://stackoverflow.com/q/52620995
tags question: http://stackoverflow.com/q/52610160
tags question: http://stackoverflow.com/q/52675402
tags question: http://stackoverflow.com/q/52690131
tags question: http://stackoverflow.com/q/52725195
tags question: http://stackoverflow.com/q/52672369
tags question: http://stackoverflow.com/q/52662805
tags question: http://stackoverflow.com/q/52667343
tags question: http://stackoverflow.com/q/52665955

http://stackoverflow.com/q/52623755
has answer: http://stackoverflow.com/a/52623976
has answer: http://stackoverflow.com/a/52624735
answer count: 2
has title: comparing nested dictionaries with different keys
downvote count: 0
has comment: http://stackoverflow.com/comment/92180927
linked to: http://stackoverflow.com/q/44034600
accepted answer: http://stackoverflow.com/a/52624735
linked to: http://stackoverflow.com/q/4527942
favorite count: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 3
has comment: http://stackoverflow.com/comment/92181042
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/52623976
has body: I am trying to compare certain values from 2 different origin (hence the two dictionaries) with each other, to know which values actually belong together. To illustrate, a shorter version of both my dictionaries with dummy data (enters added for clarity) dict_1 = {'ins1': {'Start': 100, 'End': 110, 'Size': 10}, 'ins2': {'Start': 150, 'End': 250, 'Size': 100}, 'del1': {'Start': 210, 'End': 220, 'Size': 10}, 'del2': {'Start': 260, 'End': 360, 'Size': 100}, 'dup1': {'Start': 340, 'End': 350, 'Size': 10, 'Duplications': 3}, 'dup2': {'Start': 370, 'End': 470, 'Size': 100, 'Duplications': 3}} dict_2 = {'0': {'Start': 100, 'Read': 28, 'Prec': 'PRECISE', 'Size': 10, 'End': 110}, '1': {'Start': 500, 'Read': 38, 'Prec': 'PRECISE', 'Size': 100, 'End': 600}, '2': {'Start': 210, 'Read': 27, 'Prec': 'PRECISE', 'Size': 10, 'End': 220}, '3': {'Start': 650, 'Read': 31, 'Prec': 'IMPRECISE', 'Size': 100, 'End': 750}, '4': {'Start': 370, 'Read': 31, 'Prec': 'PRECISE', 'Size': 100, 'End': 470}, '5': {'Start': 340, 'Read': 31, 'Prec': 'PRECISE', 'Size': 10, 'End': 350}, '6': {'Start': 810, 'Read': 36, 'Prec': 'PRECISE', 'Size': 10, 'End': 820}} What I want to compare are the "Start" and "End" values (and others but not specified here). If they match, I want to make a new dict (dict_3) that looks similar to this: dict_3 = {'ins1': {'Start_d1': 100, 'Start_d2': 100, 'dict_2_ID': '0', etc} {'del1': {'Start_d1': 210, 'Start_d2': 210, 'dict_2_ID': '2', etc}} p.s I need both Start_d1 and Start_d2, because they can differ slightly in number (+-5). I tried several options already on stack overflow, like: Concatenating dictionaries with different keys into Pandas dataframe (which could work I think, but I was having so much trouble with the dataframe format) and: Comparing two dictionaries in Python (which only works if the dictionary does not have a top-layer key (like here ins1, ins2 etc.) Could someone give me a beginning to work further with? I tried so many things already and the nested dict…

http://stackoverflow.com/a/57505012
has body: Here's my solution although it was not fast enough in Google's sandbox: #!/usr/bin/python # Find the number of unique staircases which can be built using 'n' bricks with successive steps being at least one level higher # the-grandest-staircase-of-them-all cnt = 0 def step(x, y): global cnt a = range(x, y) b = a[::-1] # more efficient way to reverse a list lcn = int(len(a)/2) cnt += lcn # we know that till mid way through the arrays, step combo will be vaid (x&gt;y) for i in range(0, lcn): # No need to count more than half way when comparing reversed arrays as a[i] will be &gt;=b[i] nx = a[i]+1 ny = b[i]-nx+1 if(nx &lt; ny): step(nx, ny) else: break def solution(n): if n==200: return 487067745 #Could not get the script to complete fast enough for test case 200. #Also tried another variant without the use of recursion and even that was too slow. #Test case 200 completes in 3:10 minutes on my local PC. step(1, n) return cnt solution(200)
type: Answer
answers question: http://stackoverflow.com/q/52654530
score: 0

http://stackoverflow.com/comment/92261040
comment on: http://stackoverflow.com/a/52665553
has text: Many thanks that works perfectly! While I have your attention how do I include multiple conditions? E.g. latitude and longitude?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52695421
type: Question
has title: Using Keras LSTM to predict 10+ classes: inconsistent label outputs by model.predict
has comment: http://stackoverflow.com/comment/92317401
tagged with: keras
tagged with: lstm
score: 0
has body: I am using keras bi-lstm to predict 14 classes. Here is my label index: label_index=`{'1':0,'2':1,'D':2,'7':3,'8':4,'9':5,'10':6,'11':7,'12':8,'13':9,'14':10,'15':11,'16':12,'17':13}` Here is part of my model setting: model.add(Bidirectional(LSTM(64))) model.add(Dropout(0.5)) model.add(Dense(14, activation='softmax')) model.compile('adam', 'sparse_categorical_crossentropy', metrics=['accuracy']) The "14" in the Dense function is the number of classes. When I looked at the label distribution of pred = model.predict(x_test, verbose=0), I found this: Counter({'1': 54, '10': 88, '11': 5, '12': 2, '13': 6, '14': 5, '3': 65, '4': 5, '5': 3, '6': 28, '7': 10, '8': 3, '9': 3}) Where did this "14" come from???? It's not in my index. And there was no "0"! I guess in the multi-class situation, kera.predict cannot output zero. Should I deduct 1 for every element in my "pred"?
tagged with: multiclass-classification
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92317556
tagged with: python
has comment: http://stackoverflow.com/comment/92317379
tagged with: tensorflow

http://stackoverflow.com/a/52603516
downvote count: 0
has body: Obviously if you replicate each point 100 times, you need to increase the minPts parameter 100x and the minimum cluster size, too. But your main problem likely is KernelPCA - which is sensitive to the amount of samples you have - and not HDBSCAN.
type: Answer
answers question: http://stackoverflow.com/q/52591137
score: 1
upvote count: 1

http://stackoverflow.com/comment/92128029
type: QuestionComment
has text: I don't think there is an error, I just don't think he understands the slice notation. `X = array[:,0:2]` means use all rows denoted by the first `:` before the comma, then `0:2` after the comma means use columns 0 up until 2 (not including 2) so you could also do `[:,:2]` and reproduce the same output.
score: 0
comment on: http://stackoverflow.com/q/52596553
type: Comment

http://stackoverflow.com/q/52600611
has comment: http://stackoverflow.com/comment/92136700
tagged with: knn
has comment: http://stackoverflow.com/comment/92136723
upvote count: 1
tagged with: machine-learning
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52602373
has body: SO I read a csv dataset and then store it using pandas dataframe, I then split the data into training and testing set. What I am trying to accomplish is to train and predict accuracy using only one feature at a time so that I can later see what feature would be best predictor out of the 4. I'm new to python and machine learning, so please bare w me. This is actually the first time I actually try both. I get an error in this line my_knn_for_cs4661.fit(X_train[col], y_train) something about array.reshape(-1,1) I have tried to do X_train[col].reshape(-1,1) but I get some other errors. I am using python 3 on jupyter notebook, sklearn, numpy, and pandas. Below is my code and error from sklearn.model_selection import train_test_split iris_df = pd.read_csv('https://raw.githubusercontent.com/mpourhoma/CS4661/master/iris.csv') feature_cols = ['sepal_length','sepal_width','petal_length','petal_width'] X = iris_df[feature_cols] y = iris_df['species'] predictions= {} X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=6) k = 3 my_knn_for_cs4661 = KNeighborsClassifier(n_neighbors=k) for col in feature_cols: my_knn_for_cs4661.fit(X_train[col], y_train) y_predict = my_knn_for_cs4661.predict(X_test) predictions[col] = y_predict My Error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-41-933eb8b496d8&gt; in &lt;module&gt;() 13 for col in feature_cols: 14 ---&gt; 15 my_knn_for_cs4661.fit(X_train[col], y_train) 16 y_predict = my_knn_for_cs4661.predict(X_test) 17 predictions[col] = y_predict ~\Anaconda3\lib\site-packages\sklearn\neighbors\base.py in fit(self, X, y) 763 """ 764 if not isinstance(X, (KDTree, BallTree)): --&gt; 765 X, y = check_X_y(X, y, "csr", multi_output=True) 766 767 if y.ndim == 1 or y.ndim == 2 and y.shape[1] == 1: ~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_X_y(X, y, accept_sparse, dtype, order, copy, force_all_finite,…
type: Question
possible better answer: http://stackoverflow.com/a/62471698
downvote count: 0
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/62471698
has comment: http://stackoverflow.com/comment/92137057
favorite count: 0
has comment: http://stackoverflow.com/comment/92137211
has answer: http://stackoverflow.com/a/52600848
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52602373
tagged with: python
has title: How to pass a single feature of a data set to train using sklearn KNeighborsClassifier and predict value?

http://stackoverflow.com/q/52706923
tagged with: tensorflow
has body: In the following code, I wanted to train a model in tensorflow. the model is a ResNet model, a deep one, hence the batch should be small for data/all activations to fit in memory. For this reason, I have implemented a custom optimizer that accumulates the gradients over the different fed mini-batchs, and finally apply the gradient descent once. In addition, I have used tf.data api to fetch data from tfrecords which I created. Please note that my input data are video frames; and the detected variable used indicated whether a face is detected in a certain frame or not. Hence, detected is used only for MSE (Just for clarification). import tensorflow as tf import numpy as np import csv import os num_epoch = 100 latent_dim = 100 cell_size = 100 # for each input frame, I have 3 outputs. num_classes = 3 common = "C:/Users/user/Documents/SEWA_db/tfrecords_db/" filenames_train = [] filenames_dev = [] for i in range(1, 35): filenames_train.append(common + "Train_DE_{num:02d}.tfrecords".format(num=i)) for i in range(1, 15): filenames_dev.append(common + "Devel_DE_{num:02d}.tfrecords".format(num=i)) phase_train = tf.placeholder_with_default(True, shape=(), name='phase') train_batch_size = 5 test_batch_size = 5 tf.set_random_seed(123) mseed = 123 # this method is used within the model()... def create_variables(name, shape, initializer=tf.contrib.layers.xavier_initializer(), weight_decay=0.0001): ''' :param name: A string. The name of the new variable :param shape: A list of dimensions :param initializer: User Xavier as default. :param is_fc_layer: Want to create fc layer variable? May use different weight_decay for fc layers. :return: The created variable ''' ## TODO: to allow different weight decay to fully connected layer and conv layer regularizer = tf.contrib.layers.l2_regularizer(scale=weight_decay) new_variables = tf.get_variable(name, shape=shape, initializer=initializer, regularizer=regularizer) return new_variables def model(inputs, n): .... # predictions shape: (batch_…
type: Question
score: 1
upvote count: 1
downvote count: 0
has title: Error Running Tensorflow Model while Using tf.data api and customized optimizer
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/q/52728958
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/139533989
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92730726
has answer: http://stackoverflow.com/a/61861900
tagged with: python
linked to: http://stackoverflow.com/q/60690151
score: 1
has title: How to use Scikit Learn Wrapper around Keras Bi-directional LSTM Model
upvote count: 1
has comment: http://stackoverflow.com/comment/92671959
tagged with: tensorflow
has body: I have created a Keras LSTM model that does sequence classification. I have 27 sequences in the Training set and 18 sequences in the Test set. Each sequence has 4000 time-steps that I have achieved by padding with zeroes. Each sequence is a combination of 2499 parallel series. This means I have 2499 Features. Dimensions of X_Train is (27 x 4000 x 2499) :27-Sequences, 4000 Timesteps in each sequence and 2499 features. Dimension of Y_Train is (27 x 4000 x 1) Dimension of X_Test is (18 x 4000 x 2499) Dimension of Y_Test is (18 x 4000 x 1) I am using Bi-directional LSTM Model with return_sequences set to True My ultimate goal is to get Feature Importances using ELI5 Package's Permutation Importance. Since ELI5 package does not support Keras framework, I want to use a Scikit learn Wrapper around keras to get it to behave like scikit learn. Then I can finally use ELI5 package on my model to get Important features. I have used these parameters: layer1_units = 40 layer1_act = 'tanh' go_backwards = False return_sequences = True merge_mode = 'concat' lr = 0.01 epochs = 2 batch_size = 200 I am going to use this lstm model in the build_fn attribute of KerasClassifier(). model = KerasClassifier(build_fn= lstm_Trial.model(), epochs=3, batch_size=40, verbose=1) Then I am trying to use .fit() method. model.fit(x = X_Train, y = Y_Train_Ori) This throws an error. ValueError Traceback (most recent call last) in () ----> 1 model.fit(x = X_Train, y = Y_Train_Ori) ~/anaconda3/lib/python3.6/site-packages/keras/wrappers/scikit_learn.py in fit(self, x, y, sample_weight, **kwargs) 203 y = np.searchsorted(self.classes_, y) 204 else: --> 205 raise ValueError('Invalid shape for y: ' + str(y.shape)) 206 self.n_classes_ = len(self.classes_) 207 if sample_weight is not None: ValueError: Invalid shape for y: (27, 4000, 1) How do I use KerasClassifier properly so that Ultimately I am able to use ELI5 package?
type: Question
tagged with: lstm
downvote count: 0
answer count: 1
tagged with: scikit-learn

http://stackoverflow.com/comment/92195009
has text: @SergeyBushmanov - Thank you for your suggestion, I reloaded the dataframes, changed the order, ran it, but it still produced the same error
type: QuestionComment
comment on: http://stackoverflow.com/q/52629035
score: 0
type: Comment

http://stackoverflow.com/comment/92150982
score: 0
type: AnswerComment
has text: Thanks. Im not going through all of the columns in the dataframe tough.. otherwise this would be cleaner, no doubt.
type: Comment
comment on: http://stackoverflow.com/a/52608470

http://stackoverflow.com/a/52923305
has body: You can do a def (read comments): def f(df): l=[8]*df[max(df,key=lambda x:df[x].count())].count() df[3]=l+[np.nan]*(len(df)-len(l)) # the above two lines can be just `df[3] = another solution currently for this problem` return df dataFrame = f(pandas.DataFrame(data).transpose()) Then now: print(dataFrame) Returns: 0 1 2 3 0 1.0 1.0 1.0 8 1 2.0 2.0 2.0 8 2 3.0 3.0 3.0 8 3 NaN 4.0 4.0 8 4 NaN 5.0 5.0 8 5 NaN NaN 6.0 8 6 NaN NaN 7.0 8
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52676653

http://stackoverflow.com/a/52629939
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52629767
downvote count: 0
has body: You passed in an invalid parameter, 'auto' for the SVC. The error message tells you what the possible values are: a dict of your classes, balanced, or None. If you want it to use the default behavior, leave it blank or enter None class_weight : {dict, ‘balanced’}, optional Generally when I gridsearch a SVC, I use 'class_weight': [None, 'Balanced] unless I have a specific class balance I want to try
type: Answer

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/52630370
tags question: http://stackoverflow.com/q/52694289
tags question: http://stackoverflow.com/q/52665214
tags question: http://stackoverflow.com/q/52637334
tags question: http://stackoverflow.com/q/52739486
type: Tag

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/52718192
tags question: http://stackoverflow.com/q/52606022
tags question: http://stackoverflow.com/q/52741484
tags question: http://stackoverflow.com/q/52625679
tags question: http://stackoverflow.com/q/52728432
tags question: http://stackoverflow.com/q/52742984
tag name: r
tags question: http://stackoverflow.com/q/52619313
tags question: http://stackoverflow.com/q/52718910
tags question: http://stackoverflow.com/q/52629538
tags question: http://stackoverflow.com/q/52635518
tags question: http://stackoverflow.com/q/52716328
type: Tag
tags question: http://stackoverflow.com/q/52596724
tags question: http://stackoverflow.com/q/52684816
tags question: http://stackoverflow.com/q/52670611

http://stackoverflow.com/a/52612539
downvote count: 1
type: Answer
upvote count: 0
has body: Try to use Firefox Developer Edition instead of standard Firefox. It worked for me in C#. Hope this solution will help you. Also, as I can see in your code you lunch Firefox with a particular profile, so the easiest way is to add your extension manually to your profile and then you don't have to do it programmatically
score: -1
answers question: http://stackoverflow.com/q/52608977

http://stackoverflow.com/comment/92297889
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52685068
type: Comment
has text: @Ghost Use the `%` operator on `i` instead of `number`, of course.

http://stackoverflow.com/comment/123609075
type: Comment
has text: Exists a way to emulate the same process in TF2?
comment on: http://stackoverflow.com/a/57397201
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92133153
score: 0
type: QuestionComment
type: Comment
has text: if i reduce the width of the line, the whole line will be thinner i just want only the tail of the line to be thin (something like sperm cell or a mouse tail) @John Anderson
comment on: http://stackoverflow.com/q/52598998

http://stackoverflow.com/q/52594370
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52610983
has title: Parse Grobid .tei.xml output with Beautiful Soup
answer count: 3
has answer: http://stackoverflow.com/a/76388347
has answer: http://stackoverflow.com/a/79049528
downvote count: 0
favorite count: 0
tagged with: grobid
tagged with: beautifulsoup
has body: I am trying to use Beautiful Soup to extract elements from a .tei.xml file that was generated using Grobid. I can get title(s) using: titles = soup.findAll('title') What is the correct syntax to access the 'lower level' elements? (Author / Affiliation etc) This is a portion of the tei.xml file that is the Grobid output: <?xml version="1.0" encoding="UTF-8"?> <TEI xmlns="http://www.tei-c.org/ns/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.tei-c.org/ns/1.0 /data/grobid-0.5.1/grobid-home/schemas/xsd/Grobid.xsd" xmlns:xlink="http://www.w3.org/1999/xlink"> <teiHeader xml:lang="en"> GROBID - A machine learning software for extracting information from scholarly documents The Role of Artificial Intelligence in Software Engineering <publisher/> <licence/> Mark Harman CREST Centre University College London Malet Place WC1E 6BT London UK The Role of Artificial Intelligence in Software Engineering <date/> Thanks.

http://stackoverflow.com/a/63577080
score: -1
has body: after Serial.begin(9600); write ser.begin(9600);
downvote count: 1
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/52657809
has comment: http://stackoverflow.com/comment/112426245

http://stackoverflow.com/a/52726982
downvote count: 0
has comment: http://stackoverflow.com/comment/92379876
has comment: http://stackoverflow.com/comment/92379334
has body: For saving a figure, the use of blit is not necessary. If that is left out, the figure is saved correctly. However, the figure size change is not taken into account, because the animation is created before that change. Creating the figure and all the axes before creating the animation works perfectly fine though, even with blitting being used. from itertools import tee import numpy as np import matplotlib matplotlib.use('Agg') # noqa from matplotlib.animation import FuncAnimation, FFMpegWriter from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm import matplotlib.pyplot as plt def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) def make_segs(x, y): xs = np.array(list(pairwise(x))) # (n,2) ys = np.array(list(pairwise(y))) # (n,2) segs = np.stack((xs, ys), axis=-1) # (n,2,2) return segs class _AnimationHelper(): def __init__(self, xs, ys, z, colors=['r', 'g']): self.segs = np.array([make_segs(x, y) for x, y in zip(xs, ys)]) self.z = z self.colors = colors self.fig = plt.figure() self.lns = [] m, n = self.segs.shape[:2] self.fig.set_size_inches(m*5, 5, forward=True) self.axes = self.fig.subplots( nrows=1, ncols=m, sharey='row') self.fig.tight_layout() self.ani = FuncAnimation( self.fig, self.update, interval=200, init_func=self.init, frames=self.segs.shape[1], blit=True) def init(self): m, n = self.segs.shape[:2] cmap = ListedColormap(self.colors) norm = BoundaryNorm([0, 0.5, 1], cmap.N) zero = np.zeros(n, dtype=np.int32) for i in range(m): inds = (zero + i) == self.z ln = LineCollection([], cmap=cmap, norm=norm, lw=2, animated=True) ln.set_array(inds) self.lns.append(ln) ax = self.axes[i] ax.add_collection(ln) ax.set_xlim(0, n) #ax.set_axis_off() # &lt;---- HERE self.axes[0].set_ylim(0, 1.1) for i in range(1, m): self.axes[i].tick_params(left=False) return self.lns def update(self, ind): print(ind) m = self.segs.shape[0] for i in range(m): self.lns…
type: Answer
accepted answer of: http://stackoverflow.com/q/52723813
answers question: http://stackoverflow.com/q/52723813
upvote count: 1
has comment: http://stackoverflow.com/comment/92379436
has comment: http://stackoverflow.com/comment/92379269
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/52630372
accepted answer of: http://stackoverflow.com/q/52629423
has body: The problem is how you are Iterating featList = [[Feature() for j in range(3)] for i in range(10)] list of lists of features a = [f for f in [r for r in featList]] a is a list of lists of features (still) you could do it this way a = [ f for r in featList for f in r] an It's a list of f's, so now you can do what you wanted. [ print(str(f)) for r in featList for f in r] If you see the last part of the List Comprehension section at Python's Docs you'll see the have the example, for a case like that (double list comprehension) think of it as a regular for # Regular for for a in A for b in A f(b) # Comprehended Loop a = ( f(b) for a in A for b in a) It's pretty much the same order, except for the statement.
answers question: http://stackoverflow.com/q/52629423
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/92299135
type: AnswerComment
has text: @jedwards That part is indeed redundant.
type: Comment
comment on: http://stackoverflow.com/a/52685826
score: 0

http://stackoverflow.com/a/52708505
answers question: http://stackoverflow.com/q/52708334
downvote count: 1
score: 5
has body: Use can also use np.mean to achieve the same: import numpy as np np.mean(df['Background'].tolist(), axis=1)
type: Answer
upvote count: 6

http://stackoverflow.com/comment/92398105
comment on: http://stackoverflow.com/q/52735322
has text: With all answers, none overcome to export queryset result to json file without issue .. It's pretty strange
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52632210
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52631939
type: Answer
has comment: http://stackoverflow.com/comment/92197709
accepted answer of: http://stackoverflow.com/q/52631939
score: 4
has body: To answer your first question, there may be a less 'kludgey' way, but scatter_matrix(df,c=['r' if i == 1 else 'b' for i in df['Label']]) To answer the second: The scatter matrix can use the pd.hist() api to use hist keywords passed in a dictionary scatter_matrix(df,hist_kwds={'bins':5})
has comment: http://stackoverflow.com/comment/116439433
upvote count: 4

http://stackoverflow.com/q/52597716
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/92130485
has comment: http://stackoverflow.com/comment/92130419
has comment: http://stackoverflow.com/comment/92130232
has comment: http://stackoverflow.com/comment/92130094
favorite count: 0
downvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92130135
tagged with: python
has comment: http://stackoverflow.com/comment/92130183
has comment: http://stackoverflow.com/comment/92130213
has comment: http://stackoverflow.com/comment/92130103
has title: Python 2.x and using formatters like %s, %d etc
has body: I am learning how to code with python using "Learn Python the HARD WAY" 3rd edition. I am on Exercise 6. Im not having to much trouble although the formatters still have me a tad confused. I know the formatter %s is used for strings. But I am confused about when to use others and why to use others like:%r, %d, %x, etc..... Any direction would be very much appreciated!
has comment: http://stackoverflow.com/comment/92130456
has comment: http://stackoverflow.com/comment/92130283
type: Question
has comment: http://stackoverflow.com/comment/92130734
score: -2
has comment: http://stackoverflow.com/comment/92130120
has comment: http://stackoverflow.com/comment/92130270
has answer: http://stackoverflow.com/a/52597852
tagged with: python-2.7

http://stackoverflow.com/comment/92302087
type: Comment
score: 1
has text: The first question is opinion based and not suitable for SO. If opening browser is not necessary you can use headless browser instead.
type: QuestionComment
comment on: http://stackoverflow.com/q/52687351

http://stackoverflow.com/a/52734232
score: 2
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52733745
downvote count: 0
answers question: http://stackoverflow.com/q/52733745
has body: Change your Time_Zone setting to your location specific- As you said yours is Europe/london. Therefore add this setting in your settings.py TIME_ZONE = 'Europe/london'

http://stackoverflow.com/a/52730513
downvote count: 0
has comment: http://stackoverflow.com/comment/92412431
has comment: http://stackoverflow.com/comment/92412057
has comment: http://stackoverflow.com/comment/92410709
has comment: http://stackoverflow.com/comment/92405691
has comment: http://stackoverflow.com/comment/92406647
score: 1
has comment: http://stackoverflow.com/comment/92412113
has comment: http://stackoverflow.com/comment/92387324
accepted answer of: http://stackoverflow.com/q/52729337
has comment: http://stackoverflow.com/comment/92387700
upvote count: 1
has comment: http://stackoverflow.com/comment/92413178
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52729337
has comment: http://stackoverflow.com/comment/92410871
has body: IIUC, take this sample dataframe (you have conflicting ones in your OP): import pandas as pd import numpy as np df = pd.DataFrame([ ['t1', 'm1', 1], ['t2', 'm2', 7], ['t3', 'm1', 4], ['t4', 'm2', 8], ['t5', 'm3', 5], ['t6', 'm3', 2], ['t7', 'm3', 11], ['t8', 'm4', 9]], columns=['Col1', 'Col2', 'Col3']) Yields: Col1 Col2 Col3 0 t1 m1 1 1 t2 m2 7 2 t3 m1 4 3 t4 m2 8 4 t5 m3 5 5 t6 m3 2 6 t7 m3 11 7 t8 m4 9 Then define your function with your logic: def my_function(x, val): if x.shape[0]==1: if x.iloc[0]&gt;val: return 'high' else: return 'low' if x.iloc[0]&gt;val and any(i&lt;=val for i in x.iloc[1:]): return 'high' elif x.iloc[0]&gt;val: return 'med' elif x.iloc[0]&lt;=val: return 'low' else: return np.nan Now apply that function to your sorted and grouped dataframe, using 4 as your sample input for x as stated in your OP: df['Col4'] = df.sort_values(['Col2','Col1']).groupby('Col2')['Col3'].transform(my_function, (4)) df = df.sort_values(['Col2','Col1']).groupby('Col2').first().reset_index() This yields: Col2 Col1 Col3 Col4 0 m1 t1 1 low 1 m2 t2 7 med 2 m3 t5 5 high 3 m4 t8 9 high
has comment: http://stackoverflow.com/comment/92409919
type: Answer
has comment: http://stackoverflow.com/comment/92405591

http://stackoverflow.com/a/52670266
has comment: http://stackoverflow.com/comment/92270437
answers question: http://stackoverflow.com/q/52670014
has body: The reason of your problem is next: you should use different names for your variables instead of using function names (min_ and max_ instead of min and max which are functions names). Also it is a good practise to return a value by your script if it is successful (or failure) run. import other import sys items = [] def main(): for _ in range(1, 15): a = other.myfunction() items.append(a) min_ = min(items) max_ = max(items) print(min_) print(max_) return 0 if __name__ == "__main__": sys.exit(main())
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/52670014
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/52698072
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52698796
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/52698414
has body: I am trying to write a simple record classifier. I want to add a column whose value classifies a record. I want to codify my classification rules in a yaml, or similar file for maintenance purposes. I am using Pandas as that seems to be the best way to do this with csv records in python. I am open to other suggestions. I am new to pandas and my python skills are politely described as "why does this look like perl?" I've gotten a dataframe (trans) and I want to apply my rules as follows: trans['class'][(trans['foo'] &gt; 5) &amp; (trans['bar'].str.contains(re.compile('baz|one|two', re.I))] = 'Record Type 1' This works interactively. I would like to be able to generate the classifying index, "(trans['foo'] &gt; 5) &amp; (trans['bar'].str.contains(re.compile('baz|one|two', re.I))" dynamically from each rule in my yaml file. I have successfully built strings such that I have things like: slice = "(trans['foo'] &gt; 5) &amp; (trans['bar'].str.contains(re.compile('baz|one|two', re.I))" trans['class'][slice] = 'Record Type 1' This doesn't work. What should I be doing instead?
linked to: http://stackoverflow.com/q/48541444
tagged with: indexing
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/52698414
has answer: http://stackoverflow.com/a/52698796
has title: Dynamically building indexes to classify records in pandas
type: Question
answer count: 2
downvote count: 0
tagged with: string
favorite count: 0
tagged with: series

http://stackoverflow.com/comment/92323272
comment on: http://stackoverflow.com/q/52698363
has text: You just want the `'cell'` value?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/52700944
type: Answer
score: 3
upvote count: 3
has body: for x in range(0, 5): ohlc_list[x] = [open , high , low, close] This does not do what you think it does. It creates 5 references to the same 4 lists and keep these references under different keys. This can be shown with this loop: for value in ohlc_list.values(): print([id(inner_list) for inner_list in value]) # [2446702057416, 2446702057544, 2446692440648, 2446702057480] # [2446702057416, 2446702057544, 2446692440648, 2446702057480] # [2446702057416, 2446702057544, 2446692440648, 2446702057480] # [2446702057416, 2446702057544, 2446692440648, 2446702057480] # [2446702057416, 2446702057544, 2446692440648, 2446702057480] We see that all inner lists have the same id, which mean they all reference the same place in memory (overly simplified on purpose). What you want is 5 copies of these lists. You can either use an empty slice ([:]) or copy to achieve this: for x in range(0, 5): ohlc_list[x] = [open[:], high[:], low[:], close[:]] If we print all the ids of the inner lists again, we see that now we actually got different lists in memory: # [2592165177544, 2592165177480, 2592165177416, 2592165177352] # [2592165177672, 2592165177736, 2592165177800, 2592165177864] # [2592165177992, 2592165178056, 2592165178120, 2592165178184] # [2592165178312, 2592165178376, 2592165178440, 2592165178504] # [2592165178632, 2592165178696, 2592165178760, 2592165178824]
downvote count: 0
has comment: http://stackoverflow.com/comment/92330487
answers question: http://stackoverflow.com/q/52700825

http://stackoverflow.com/a/52590688
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52590564
has comment: http://stackoverflow.com/comment/92124867
type: Answer
has body: This should give you the common key: set(book_title.split()).intersection(set(LANGUAGE_TO_ISO.keys())) which you can lookup into the dictionary to get the corresponding value. in response to comment from OP, including a snippet of the output on the shell: In [4]: LANGUAGE_TO_ISO = { ...: "en": "en", ...: "eng": "en", ...: "english": "en", ...: "es": "es", ...: "spanish": "es", ...: } In [5]: book_title = "The Dark Tower - english" In [6]: set(book_title.split()).intersection(set(LANGUAGE_TO_ISO.keys())) Out[6]: {'english'}
upvote count: 1
has comment: http://stackoverflow.com/comment/92125902
has comment: http://stackoverflow.com/comment/92116076

http://stackoverflow.com/q/52608995
possible better answer: http://stackoverflow.com/a/52609047
duplicate of: http://stackoverflow.com/q/37974199
type: Question
answer count: 2
score: -2
has comment: http://stackoverflow.com/comment/92152219
has answer: http://stackoverflow.com/a/52609070
accepted answer: http://stackoverflow.com/a/52609070
tagged with: python-2.7
downvote count: 2
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/37974199
has body: I have a stable working project with python. It's running on python 2.7. I upgraded it to python 3.x. So, it's not working on Python3. The logic is writing values to csv file. Broken code is that: csv = io.BytesIO() csv.write('fiscalYear\t' 'VKN\t' 'recordPeriod\t' 'enteredBy\t' 'entredDate\t' 'entryNumber\t' 'entryComment\t' 'batchID\t' 'batchDescription\t' 'totalDebit\t' 'totalCredit\t' 'amountOriginalExchangeRate\t' 'amountOriginalExchangeRateSource\t' 'amountOriginalExchangeRateComment\n' ) return csv.getvalue() My problem is that: Expected type 'union[bytes, bytearray], got 'str' instead Python log error: TypeError: a bytes-like object is required, not 'str' I need your help!
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52609047
type: AnsweredQuestion
upvote count: 0
tagged with: odoo
has title: Python3 | Expected type 'union[bytes, bytearray], got 'str' instead

http://stackoverflow.com/comment/92355776
type: QuestionComment
has text: Are you going to average (or use some other filter) the colors and see what you end up with? That's what I get from "merging".
comment on: http://stackoverflow.com/q/52714845
score: 0
type: Comment

http://stackoverflow.com/a/52689991
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52689171
type: AcceptedAnswer
has body: Since you're using pandas anyway, you can use the built-in table processing, like this: pandas.read_html('https://projects.fivethirtyeight.com/soccer-predictions/premier-league/', attrs = { 'class': 'forecast-table' }, header = 1)
accepted answer of: http://stackoverflow.com/q/52689171

http://stackoverflow.com/comment/92221168
type: QuestionComment
has text: yeah I support @VaibhavVishal you should also insall it in venv so if you mess something wont mess your system
comment on: http://stackoverflow.com/q/52644408
score: 1
type: Comment

http://stackoverflow.com/q/52646982
has answer: http://stackoverflow.com/a/73496266
accepted answer: http://stackoverflow.com/a/52647150
has answer: http://stackoverflow.com/a/52647031
possible better answer: http://stackoverflow.com/a/52647031
has comment: http://stackoverflow.com/comment/92226121
answer count: 4
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: bz2
type: Question
tagged with: python
has body: I need to compress multiple files into one bz2 file in python. I'm trying to find a way but I can't can find an answer. Is it possible?
has answer: http://stackoverflow.com/a/52647150
has answer: http://stackoverflow.com/a/57844626
has title: compress multiple files into a bz2 file in python
upvote count: 1

http://stackoverflow.com/a/76994912
has body: Falcon 3 has built-in support for custom HTTP methods. You can either use the environment variable FALCON_CUSTOM_HTTP_METHODS which is a comma-delimited list of custom methods: export FALCON_CUSTOM_HTTP_METHODS=EXAMPLE,PURGE or add it programmatically to the COMBINED_METHODS constant: import falcon.constants falcon.constants.COMBINED_METHODS += ['EXAMPLE', 'PURGE']
answers question: http://stackoverflow.com/q/52688122
score: 0
type: Answer

http://stackoverflow.com/comment/92223410
comment on: http://stackoverflow.com/a/52644886
type: AnswerComment
score: 0
type: Comment
has text: @raffa_sa - Or `df1 = dfs[0]`, `df2 = dfs[1]`

http://stackoverflow.com/a/52685054
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52684993
has comment: http://stackoverflow.com/comment/92301678
has comment: http://stackoverflow.com/comment/92311145
has comment: http://stackoverflow.com/comment/92332185
answers question: http://stackoverflow.com/q/52684993
score: 58
type: Answer
has comment: http://stackoverflow.com/comment/92316873
has comment: http://stackoverflow.com/comment/92307632
has comment: http://stackoverflow.com/comment/92342949
has body: A list in Python is implemented as an array of pointers1. So, what's really happening when you create the list: ["perry", 1, 23.5, "s"] is that you are actually creating an array of pointers like so: [0xa3d25342, 0x635423fa, 0xff243546, 0x2545fade] Each pointer "points" to the respective objects in memory, so that the string "perry" will be stored at address 0xa3d25342 and the number 1 will be stored at 0x635423fa, etc. Since all pointers are the same size, the interpreter can in fact add 3 times the size of an element to the address of li[0] to get to the pointer stored at li[3]. 1 Get more details from: the horse's mouth (CPython source code on GitHub).
has comment: http://stackoverflow.com/comment/92343881
upvote count: 58
downvote count: 0
has comment: http://stackoverflow.com/comment/92301497
has comment: http://stackoverflow.com/comment/92343748
has comment: http://stackoverflow.com/comment/92336222

http://stackoverflow.com/q/52728192
tagged with: python-2.7
answer count: 3
has comment: http://stackoverflow.com/comment/92381779
downvote count: 1
tagged with: range
has comment: http://stackoverflow.com/comment/92381575
has body: I am trying to print the even integers and then add and print the odd integers in this range of numbers. I have been stuck for a while and cant seem to figure out what I need to do. first = int(raw_input("Input the lower integer : ")) second = int(raw_input("Input the higher integer : ")) def calc(even,odd): for even in range(first, second+1): if(even % 2 == 0): print even for odd in range(first, second+1): if(odd % 2 &gt; 0): print odd calc(first,second)
tagged with: python
has comment: http://stackoverflow.com/comment/92382091
has comment: http://stackoverflow.com/comment/92381688
has answer: http://stackoverflow.com/a/52728353
favorite count: 0
tagged with: addition
accepted answer: http://stackoverflow.com/a/52728233
has answer: http://stackoverflow.com/a/52728429
has comment: http://stackoverflow.com/comment/92381668
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/52728233
score: -1
tagged with: loops
possible better answer: http://stackoverflow.com/a/52728353
type: Question
has title: Adding a range of numbers python 2.7
has comment: http://stackoverflow.com/comment/92381869
has comment: http://stackoverflow.com/comment/92381967

http://stackoverflow.com/a/52635776
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52635717
has body: use lambda + startswith soup.find_all('td', id=lambda x: x and x.startswith('name')) or regex soup.find_all('td', id=re.compile('^name'))
score: 1
accepted answer of: http://stackoverflow.com/q/52635717
type: AcceptedAnswer

http://stackoverflow.com/q/52603467
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52603575
tagged with: pandas
tagged with: python
has body: I have dataset in given form time color height weight value 1 t1 red hr1 wr1 vr1 2 t1 red hr1 wr1 vr1 3 t1 blue hb1 wb1 vb1 4 t1 blue hb1 wb1 vb1 5 t1 green hg1 wg1 vg1 6 t1 green hg1 wg1 vg1 7 t2 blue hb2 wb2 vb2 8 t2 green hg2 wg2 vg2 9 t2 red hr2 wr2 vr2 10 t2 red hr2 wr2 vr2 11 t3 red hr3 wr3 vr3 12 t3 red hr3 wr3 vr3 13 t3 green hg3 wg3 vg3 14 t3 green hg3 wg3 vg3 15 t3 blue hb3 wb3 vb3 16 t3 blue hb3 wb3 vb3 I would like to drop the measurements of time where the color do not have same count value of 2 for each red, blue green. In the given snippet, t1 and t3 should be retained and all rows for t3 measurements should be dropped. The result should be: time color height weight value 1 t1 red hr1 wr1 vr1 2 t1 red hr1 wr1 vr1 3 t1 blue hb1 wb1 vb1 4 t1 blue hb1 wb1 vb1 5 t1 green hg1 wg1 vg1 6 t1 green hg1 wg1 vg1 7 t3 red hr3 wr3 vr3 8 t3 red hr3 wr3 vr3 9 t3 green hg3 wg3 vg3 10 t3 green hg3 wg3 vg3 11 t3 blue hb3 wb3 vb3 12 t3 blue hb3 wb3 vb3 Thank you,
favorite count: 0
upvote count: 2
has title: conditional selection on pandas dataframe
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52603618
accepted answer: http://stackoverflow.com/a/52603618
possible better answer: http://stackoverflow.com/a/52603575
type: Question

http://stackoverflow.com/comment/92336266
comment on: http://stackoverflow.com/q/52704808
type: Comment
type: QuestionComment
has text: You should probably include sample data and expected output. Also, your condition needs greater detail.
score: 0

http://stackoverflow.com/a/52690733
has body: A dictionary uses a series of unique keys to identify a single or set of values. How you have your dictionary defined above will only return the second instance of the 0 and 1 keys. Your value can have repeated data, but not your key. https://docs.python.org/3/tutorial/datastructures.html Additionally, your dictionary values are lists, not tuples. It is important to know the difference as tuples are immutable objects, and lists are mutable objects. my_tuple = ('value1', 'value2') my_list = ['value1', 'value2'] If you wanted to create a new dictionary using the key and value: my_old_dict = { '0':[0, 0], '1':[2, 1], } my_new_dict = {} for key, value in my_old_dict.items(): if key == '1': my_new_dict[key] = value print(my_new_dict) #&lt;-- PRINTS {'1': [2, 1]} ADDITIONAL INFO: You code above: for item in dictionaryofinputs.values(): if key[0] == '1' #&lt;-- THERE IS NO KEY, YOU DID NOT UNPACK ONE. locationcoor = locationcoor + key[1] is not complete, and one of the biggest reasons it is not working is because you are not unpacking a key with your values. It should be for key, value in dictionaryofinputs.items(): if key == '1': locationcoor[key] = value assuming that locationcoor is a dictionary.
answers question: http://stackoverflow.com/q/52690406
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/52638661
tagged with: string
has answer: http://stackoverflow.com/a/52638703
favorite count: 0
upvote count: 2
answer count: 5
type: UnansweredQuestion
tagged with: python
tagged with: list
downvote count: 2
has answer: http://stackoverflow.com/a/52638717
has title: How to replace parts of strings in a list
has answer: http://stackoverflow.com/a/52638727
has answer: http://stackoverflow.com/a/52639482
type: Question
has answer: http://stackoverflow.com/a/52638777
has body: i am not so familiar with python, and i don't know how to do this.. So I have a list that looks like this: animal_id = ['id01', 'id02', 'id03', 'id04', 'id05'] and I would like to make a new list from the list above, using string manipulation. and the new list should look like this: animal_list = ['a01', 'a02', 'a03', 'a04', 'a05'] i think i would have to make a for loop, but i dont know what methods (in string) to use to achieve the desired output
tagged with: replace
score: 0

http://stackoverflow.com/comment/92437130
comment on: http://stackoverflow.com/a/52734252
has text: @AnkitSingh You can insert `.filter(class_set__isnull=False)`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92121298
type: Comment
comment on: http://stackoverflow.com/q/52592829
has text: @ImportanceOfBeingErnest Thanks. (1) I knew you could combine multiple images and then show them but I was wondering if there is a specific method for that. (3) By browser, I meant more like Jypter notebook
score: 0
type: QuestionComment

http://stackoverflow.com/a/52623912
answers question: http://stackoverflow.com/q/52623204
accepted answer of: http://stackoverflow.com/q/52623204
has comment: http://stackoverflow.com/comment/132098565
has comment: http://stackoverflow.com/comment/132104173
has body: With Python 3.6, the built-in typing package will do the job. from typing import List def validate(self, item:dict, attrs:dict)-&gt; List[str]: ... The notation is a bit weird, since it uses brackets but works out pretty well. Edit: With the new 3.9 version of Python, you can annotate types without importing from the typing module. The only difference is that you use real type names instead of defined types in the typing module. def validate(self, item:dict, attrs:dict)-&gt; list[str]: ... NOTE: Type hints are just hints that help IDE. Those types are not enforced. You can add a hint for a variable as str and set an int to it like this: a:str = 'variable hinted as str' a = 5 # See, we can set an int Your IDE will warn you but you will still be able to run the code. Because those are just hints. Python is not a type strict language. Instead, it employs dynamic typing.
has comment: http://stackoverflow.com/comment/137460543
has comment: http://stackoverflow.com/comment/104497824
type: AcceptedAnswer
downvote count: 0
score: 106
has comment: http://stackoverflow.com/comment/104517711
type: Answer
upvote count: 106

http://stackoverflow.com/comment/132746756
type: Comment
comment on: http://stackoverflow.com/q/52679038
score: 0
type: QuestionComment
has text: Update: effbot has vanished, but you can find the pages at [archive.org](https://web.archive.org/web/20201112023803/http://effbot.org/tkinterbook/text.htm).

http://stackoverflow.com/comment/92284897
score: 0
type: Comment
has text: the location of the year is fine. But is there a way to sub divide this by 12 for every year? in my plot the whole width per year is shaded using `axvspan` so it would be nice to have a little mark per month
type: AnswerComment
comment on: http://stackoverflow.com/a/52677912

http://stackoverflow.com/q/52714232
linked to: http://stackoverflow.com/q/1520234
linked to: http://stackoverflow.com/q/51553668
has answer: http://stackoverflow.com/a/52714999
score: 0
has answer: http://stackoverflow.com/a/52715656
answer count: 2
type: UnansweredQuestion
has body: I used How do I check which version of NumPy I'm using? to learn how to get the version of numpy. However, when I run conda list | grep numpy, I get: numpy 1.15.2 py36ha559c80_0 numpy-base 1.15.2 py36h8128ebf_0 numpydoc 0.8.0 py36_0 However, when I run version from IPython shell, I get: import numpy as np np.__version__ Out: '1.13.3' np.version.version Out: '1.13.3' np.version.full_version Out: '1.13.3' Why are the two versions different? Which one should I trust? Thanks for any help. Please note that I am not using venv (i.e. virtual environment). I am directly accessing Anaconda's packages. So, there is no issue about versioning. Here's what PyCharm is showing me: As per Conda's version information on package doesn't correspond to __version__, here's __file__ and sys.path. Please note that I have hidden my name for privacy issues.
tagged with: python
linked to: http://stackoverflow.com/q/9386048
type: Question
tagged with: numpy
has title: Different numpy version in Anaconda and numpy.__version__ in IPython Shell
linked to: http://stackoverflow.com/q/45597201

http://stackoverflow.com/comment/92334326
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52698854
has text: This method is helpful, thanks @ Willem Van Onsem

http://stackoverflow.com/a/52739144
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52739143
type: Answer
has body: Even I had the same problem, and the solution was quiet easy. Remember 1 thing, if the RGB values of your image lie in the range of 0-255, make sure the values are not of data type 'float'. As OpenCV considers float only when values range from 0-1. If it finds a float value larger than 1 it clips off the value thinking floats only exists between 0-1. Hence such errors generated. So convert the data type to uint8 if values are from 0-255. image = image.astype('uint8') Check this Kaggle Kernel to learn more about it
upvote count: 21
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52739143
score: 20

http://stackoverflow.com/comment/92199133
has text: this is somewhat helpful, for me this is very hard to understand but i think i got it after staring at it long enough. so i figured out you could type in shell and it actually returns some values. (i tried doing mylists["bingo"] in the actual code instead of python lol)
comment on: http://stackoverflow.com/a/52632714
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92397496
comment on: http://stackoverflow.com/q/52736154
score: 1
has text: Possible duplicate of [Checking images for similarity with OpenCV](https://stackoverflow.com/questions/11541154/checking-images-for-similarity-with-opencv)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52605769
tagged with: nginx
tagged with: flask
has answer: http://stackoverflow.com/a/52607160
answer count: 1
score: 1
favorite count: 0
tagged with: gunicorn
has body: Can you please help? I am stuck. My server is crashing at @return redirect(url_for(‘login’)) ,when I run it using gunicorn i.e. $gunicorn — bind 127.0.0.1:5000 -w 4 wsgi:app. Same issue arises when I run it using supervisor. The code is working fine when I run it normally i.e. python app.py Appreciate any suggestions.
tagged with: python
accepted answer: http://stackoverflow.com/a/52607160
type: AnsweredQuestion
upvote count: 2
downvote count: 1
type: Question
has title: Flask app running with gunicorn and nginx is crashing at redirecting point

http://stackoverflow.com/q/52590757
has comment: http://stackoverflow.com/comment/92116423
has body: I have a model named tranasaction. class transactions(models.Model): id = models.AutoField(primary_key=True) date = models.DateTimeField(default=datetime.now, blank=True) saleduser = models.ForeignKey('UserData',on_delete=models.CASCADE, related_name='vclouduser_data', blank=True, null=True) brand = models.CharField(max_length=50,blank=True) type = models.CharField(max_length=50,blank=True) quantity = models.DecimalField(blank=True,null=True,max_digits=20,decimal_places=2) amount = models.DecimalField(blank=True,null=True,max_digits=20,decimal_places=2) And I need to create a summary report, so I create a new Model. class SaleSummary(transactions): class Meta: proxy = True verbose_name = 'Sale Summary' verbose_name_plural = 'Sales Summary' what i need that i need to get the total amount of each type as a new model. please help me to solve this. Thanks in advance.
tagged with: django-models
has comment: http://stackoverflow.com/comment/92116782
answer count: 1
has comment: http://stackoverflow.com/comment/92116474
has answer: http://stackoverflow.com/a/74839665
has comment: http://stackoverflow.com/comment/92116515
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92116759
tagged with: django
has title: How do i create a new proxy model based on another model in django?
tagged with: python
score: 0
type: Question

http://stackoverflow.com/comment/92254937
has text: Sorry. I am working in an excel file. By using Python3 I have created all these groups and saved in a separate file. now I am writing different program so I need to extract the data from my previously saved excel sheet. that's why I have posted this question. I have saved all data from the workbook in different dataframe and now I need to extract the data from each `df`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52661690
type: Comment

http://stackoverflow.com/comment/92356266
comment on: http://stackoverflow.com/q/52715103
type: Comment
type: QuestionComment
has text: ok, i did not stop experimenting and [this post](https://stackoverflow.com/questions/52128188/using-a-custom-pyside2-widget-in-qt-designer), with some memories of posts i've been reading yesterday, helped me getting in the good track. very soon i will be able to answer my own question : - )
score: 0

http://stackoverflow.com/comment/92283034
type: Comment
has text: Can you please provide more details on what EONET is exactly, a link perhaps? Many of us here will not be familiar with it.
comment on: http://stackoverflow.com/q/52676479
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92380564
comment on: http://stackoverflow.com/q/52727547
type: Comment
type: QuestionComment
has text: This would help: https://stackoverflow.com/questions/10195139/how-to-retrieve-sql-result-column-value-using-column-name-in-python
score: 0

http://stackoverflow.com/comment/92112703
type: Comment
type: QuestionComment
has text: @Graipher meaning size=(int(1e6),3) would be 1 million of 3 flips?
comment on: http://stackoverflow.com/q/52588867
score: 0

http://stackoverflow.com/a/52622698
answers question: http://stackoverflow.com/q/52622488
score: 0
has comment: http://stackoverflow.com/comment/92179232
type: Answer
has comment: http://stackoverflow.com/comment/92179250
has body: I am assuming your input data structure is python dict (Associative array). And you are trying to print list of keys and values inside this dict. Below code snippet will print keys and values input = {0: 70, 1: 60, 2: 66, 3: 62, 4: 72, 5: 82, 6: 83, 7: 86, 8: 95, 9: 96, 10: 98, 11: 98, 12: 96, 13: 94, 14: 66, 15: 62, 16: 60, 17: 66, 18: 67, 19: 67, 20: 64, 21: 66, 22: 66, 23: 69} # Below is the output with keys, values print(input.keys()) print(input.values())

http://stackoverflow.com/q/52658729
tagged with: python-3.x
has title: Export regression results as a csv file when using summary_out
tagged with: python
has answer: http://stackoverflow.com/a/52702912
accepted answer: http://stackoverflow.com/a/52702912
type: AnsweredQuestion
tagged with: statsmodels
downvote count: 0
score: 1
tagged with: regression
type: Question
has body: I am running multiple regressions using financial data from Yahoo! Finance and Fama-French factors from http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/f-f_factors.html Single factor regression: CAPM = sm.ols( formula = 'Exret ~ MKT', data=m).fit(cov_type='HAC',cov_kwds={'maxlags':1}) Three factor regression: FF3 = sm.ols( formula = 'Exret ~ MKT + SMB + HML', data=m).fit(cov_type='HAC',cov_kwds={'maxlags':1}) I then utilise summary_col to create a table with significance stars: dfoutput = summary_col([CAPM,FF3],stars=True,float_format='%0.4f', model_names=['GOOG','GOOG'],info_dict={'N':lambda x: "{0:d}".format(int(x.nobs)),'Adjusted R2':lambda x: "{:.2f}".format(x.rsquared_adj)}, regressor_order = ['Intercept', 'MKT', 'SMB', 'HML']) Output dfoutput Out[311]: &lt;class 'statsmodels.iolib.summary2.Summary'&gt; """ ================================= GOOG I GOOG II --------------------------------- Intercept -0.0009*** -0.0010*** (0.0003) (0.0003) MKT 0.0098*** 0.0107*** (0.0003) (0.0003) SMB -0.0033*** (0.0006) HML -0.0063*** (0.0006) N 1930 1930 Adjusted R2 0.37 0.42 ================================= Standard errors in parentheses. * p&lt;.1, ** p&lt;.05, ***p&lt;.01 I have the following two questions: Is it possible to change the standard errors in parentheses to t-stats? Is it possible to export the results of the summary_col function to Excel as a csv file?
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92395952
comment on: http://stackoverflow.com/q/52735559
score: 1
type: Comment
type: QuestionComment
has text: What is your question?

http://stackoverflow.com/comment/92161445
comment on: http://stackoverflow.com/a/52613270
type: Comment
has text: This is more of a comment than an answer. If this is *correct*, then the question is a duplicate of many previous problems in reusing `list`.
score: 1
type: AnswerComment

http://stackoverflow.com/q/52658033
tagged with: python-3.x
tagged with: python
has title: How to clean data by removing invalide values from dictionary
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/52658190
has body: ID,age,salary,suburb,language P1,eighty two,60196.0,Toorak,English P2,49,-16945514.0,St. Kilda,Chinese P3,54,49775.0,Neverland,Italian I have the above dictionary. In the age column, some ages are written in words. I want to replace them with None. Similarly in second column salary is negative or more than Max-salary that needs to be replaced by None, and there are invalid suburbs name that need to be changed to None as well.
has comment: http://stackoverflow.com/comment/92246675
type: Question
answer count: 2
score: -2
has answer: http://stackoverflow.com/a/52658190
has comment: http://stackoverflow.com/comment/92246596
downvote count: 2
has answer: http://stackoverflow.com/a/52658230
has comment: http://stackoverflow.com/comment/92246669
accepted answer: http://stackoverflow.com/a/52658230
favorite count: 0

http://stackoverflow.com/comment/92358435
type: QuestionComment
type: Comment
has text: I just use curl to simulator client access and test my application, not use curl in my application to visit API, do I need use gevent-curl?
comment on: http://stackoverflow.com/q/52715471
score: 0

joystick
type: Tag
tag name: joystick
tags question: http://stackoverflow.com/q/52673030

http://stackoverflow.com/q/52673780
has answer: http://stackoverflow.com/a/52674003
has answer: http://stackoverflow.com/a/52674144
answer count: 3
upvote count: 1
tagged with: genfromtxt
tagged with: types
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52674014
tagged with: python
has body: i have an data.txt like that 16.37.235.153|119.222.242.130|38673|161|17|62|4646| 16.37.235.153|119.222.242.112|56388|161|17|62|4646| 16.37.235.200|16.37.235.153|59009|514|17|143|21271| I want to get a list with the form: list=[['16.37.235.153','119.222.242.130',38673,161,17,62,4646] ['16.37.235.153','119.222.242.112',56388,161,17,62,4646] ['16.37.235.200','16.37.235.153',59009,514,17,143,21271]] I tried to use numpy.genfromtxt with dtype=None, but then i get: VisibleDeprecationWarning: Reading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default. list = numpy.genfromtxt('results.rw', dtype=None, delimiter = '|') And this as list: [['8.254.200.14' 'False'] ['8.254.200.14' 'False'] ['8.254.200.46' 'False'] ... ['217.243.224.144' 'False'] ['217.243.224.144' 'False'] ['217.243.224.144' 'False']] Appreciate every help, thank you in advance. Greetings :)
has title: (Python) Using numpy.genfromtxt for filling list with data (different datatypes)
tagged with: list
downvote count: 0
score: 1
type: Question
tagged with: numpy

http://stackoverflow.com/a/52705977
answers question: http://stackoverflow.com/q/52705767
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92339118
has comment: http://stackoverflow.com/comment/92339432
type: Answer
upvote count: 3
has body: Use subprocess.Popen and don't use the pipe | because it requires shell=True which security risk. So, use the subprocess.PIPE and use that with subprocess.check_output without pipe thats the correct method. So, you can try something like: command = subprocess.Popen(("hadoop", "fs", "-count", "/user/a909983/sample_data/") , stdout=subprocess.PIPE) output = subprocess.check_output(("awk '{print $2}'"), stdin=command.stdout) In Case You want to try Shell commands by enabling shell=True: cmd = "hadoop fs -count /user/a909983/sample_data/ | awk '{print $2}'" command = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) output = command.communicate()[0] print(output)
has comment: http://stackoverflow.com/comment/92339218
has comment: http://stackoverflow.com/comment/92339142
accepted answer of: http://stackoverflow.com/q/52705767
score: 3

http://stackoverflow.com/q/52744150
accepted answer: http://stackoverflow.com/a/52776453
tagged with: dataframe
tagged with: multi-index
answer count: 1
downvote count: 0
favorite count: 0
has title: Pandas: how to add data to a MultiIndex empty DataFrame?
tagged with: pandas
has comment: http://stackoverflow.com/comment/92450102
tagged with: python
has answer: http://stackoverflow.com/a/52776453
score: 2
has comment: http://stackoverflow.com/comment/92413274
upvote count: 2
has body: I would like to use a MultiIndex DataFrame to easily select portions of the DataFrame. I created an empty DataFrame as follows: mi = mindex = {'input':['a','b','c'],'optim':['pareto','alive']} mi = pd.MultiIndex.from_tuples([(c,k) for c in mi.keys() for k in mi[c]]) mc = pd.MultiIndex(names=['Generation','Individual'],labels=[[],[]],levels=[[],[]]) population = pd.DataFrame(index=mi,columns=mc) which seems to be good. However, I do not know how to insert a single data to start populating my DataFrame. I tried the followings: population.loc[('optim','pareto'),(0,0)]=True where I tried to define a new column double index (0,0) leading to a NotImplementedError. I also tried with (0,1), which gave a ValueError. I tried also with no columns indexes: population.loc[('optim','pareto')]=True Which gave no error...but no change in the DataFrame either... Any help? Thanks in advance. EDIT To clarify my question, once populated, my DataFrame should look like this: Generation 1 2 Individual 1 2 3 4 5 6 input a 1 1 2 ... b 1 2 2 ... c 1 1 2 ... optim pareto True True False ... alive True True False ... EDIT 2 I found out that what I was doing works if I define my first column at the DataFrame creation. In particular with: mc = pd.MultiIndex.from_tuples([(0,0)]) I get a first column full of nan and I can add data as I wanted to (also for new columns): population.loc[('optim','pareto'),(0,1)]=True I still do not know what is wrong with my first definition...
has comment: http://stackoverflow.com/comment/92437319
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/127443301
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/62849678
has text: Any significance to the three different ways to invoke pip? (pip, python -m pip, pip3)
type: Comment

http://stackoverflow.com/a/52607512
has comment: http://stackoverflow.com/comment/92149135
answers question: http://stackoverflow.com/q/52607438
type: Answer
has body: Have you tried: set(index_object.tolist()) I suspect this will return you a set of timestamp objects rather than strings so depends on your use case whether this is something you want if it's the strings you want you can modify the code as follows: set(index_object.dt.strftime("%Y-%m-%d").tolist()) For your specific format (which I don't necessarily approve of!) you can try this: import itertools string_lists = col2.apply(lambda x: x.dt.strftime("%Y-%m-%d").tolist()) unique_set = set(itertools.chain.from_iterable(string_lists.tolist()))
score: 0

http://stackoverflow.com/a/52674263
type: Answer
has comment: http://stackoverflow.com/comment/92278237
has body: You've forgotten to add a + sign. This line should work: dump.pbd='pdb' + pdbFile + '' + 'res' + residMin + '' + residMax + '.pdb' There must be a + sign between '_' and residMax as this is the Python concatenating strings syntax.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92278084
answers question: http://stackoverflow.com/q/52674248
upvote count: 1

http://stackoverflow.com/q/52702261
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/93729892
has answer: http://stackoverflow.com/a/61105060
score: 3
upvote count: 3
tagged with: androguard
type: Question
downvote count: 0
tagged with: yara
has body: I tried installing Yara 3.8.1 with androguard module. During the installation, I faced this issue, so I applied the patch given by @reox to the androguard.c file and it solved the problem. After that I tried a simple Yara rule with import "androguard" using command-line and it worked perfectly. Then I tried to use Yara rules inside my python app so I installed yara-python and used it in this way: import yara dex_path = './classes.dex' my_rule = './rule.yar' json_data = load_json_data() rule = yara.compile(my_rule) matches = rule.match(filepath=dex_path, modules_data={'androguard': json_data}) print(matches) The match function works good when using Yara rules without import "androguard" module but when I want to apply a rule which imports androguard, the match function gives an error : yara.Error: could not map file "./classes.dex" into memory I'm applying a simple rule to an small file, in order of KB. I think that the problem is with the androguard module since when I remove the import "androguard", it works correctly. Any idea?
has title: Memory error when using androguard module in Yara Rules
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/93728266

input
tags question: http://stackoverflow.com/q/52601252
tags question: http://stackoverflow.com/q/52600980
tags question: http://stackoverflow.com/q/52672369
tags question: http://stackoverflow.com/q/52682436
tags question: http://stackoverflow.com/q/52606875
tags question: http://stackoverflow.com/q/52607943
tags question: http://stackoverflow.com/q/52692643
tag name: input
type: Tag

http://stackoverflow.com/comment/92233229
type: Comment
comment on: http://stackoverflow.com/q/52650583
type: QuestionComment
score: 1
has text: The `dict(zip` version makes two function calls (albeit they're C calls, so faster than Python calls). But `zip` has to build a bunch of tuples, and although that's a cheap operation the dict comp avoids that.

http://stackoverflow.com/q/52670151
tagged with: bluetooth
has title: scoket programming for wifi/Bluetooth (python 3.3>)
has answer: http://stackoverflow.com/a/52706793
tagged with: python
has comment: http://stackoverflow.com/comment/92312905
type: Question
score: 0
tagged with: sockets
answer count: 1
has body: new to programming.. i need little help on how to achieve this specific task in python .. i need to transfer data between pc to andriod.. i tried socket.. it only works on an active internet connection(i used client /server methodology) .. i want to try it with bluetooth or wifi, if i try pybluez for bluetooth.. andriod deos not support it.. and it kind of only works on linux, for wifi i have no idea how to begin/where to begin, any suggestions are welcome i run python scripts on andriod using python idle3 from play store(python 3.6>).,on windows i have python 3.6 interpreter
has comment: http://stackoverflow.com/comment/92501446
has comment: http://stackoverflow.com/comment/92286509
tagged with: wifi
has comment: http://stackoverflow.com/comment/92270135
type: UnansweredQuestion

http://stackoverflow.com/comment/92340390
type: Comment
has text: Index B A A>0 & B >0.8 A>0 & as soon as B>0.8 2127 0.551354566 0 0 0 2128 0.66838571 0 0 0 2129 0.809306329 1 1 1 2130 0.812775762 1 1 1 2131 0.81319083 1 1 1 2132 0.814134565 1 1 1 2133 0.814281433 1 1 1 2134 0.812157799 1 1 1 2135 0.810377385 1 1 1 2136 0.808989447 1 1 1 2137 0.806981847 1 1 1 2138 0.800548453 1 1 1 2139 0.792510453 1 0 0 2140 0.785009569 1 0 0 2141 0.777099821 1 0 0 2142 0.768469301 1 0 0 2143 0.762370584 1 0 0 2144 0.754136153 1 0 0 2145 0.74586568 1 0 0 2146 0.74058505 1 0 0 2147 0.733714521 1 0 0
comment on: http://stackoverflow.com/a/52668666
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92294498
has text: We need a complete [mcve]. We can't just look at one column in isolation and know what the problem is. Also, it's still not clear what you expect. Are the red and blue columns supposed to be a fixed size? What about the right column with the green and pink -- is that supposed to be a fixed size, or should it grown and shrink in proportion?
comment on: http://stackoverflow.com/q/52681613
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92406749
type: QuestionComment
has text: You just add a mirrored version of your image to the left top bottom and right. So if one row of your image was [0, 1, 2 ,3], mirrored it would look: [3, 2, 1, 0, 1, 2, 3, 2, 1, 0)]. That is a common technique in image processing, but in your case I would say that adding 0s instead of mirroring is better, because it describes the situation better.
comment on: http://stackoverflow.com/q/52738605
score: 0
type: Comment

multi-gpu
type: Tag
tags question: http://stackoverflow.com/q/52677861
tag name: multi-gpu

http://stackoverflow.com/comment/92131634
has text: again I did :). If I put print(parent) before while, i get 4 2 1 0 0 1 0 0.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52598059

http://stackoverflow.com/comment/92289262
has text: I hadn't thought about the number of function calls. One way I had thought of was using `np.moveaxis` to make it 100 x 2 x 2 and then calling `map()` with `np.linalg.inv`, more pythonic, but still 100 calls.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52680125
type: AnswerComment

http://stackoverflow.com/a/60424352
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52612286
has body: As others have already pointed out, it is not clear what you are trying to achieve with the print('args', args, **args) line. But, anyways the python's print function has a syntax of (ref): print(object(s), separator=separator, end=end, file=file, flush=flush) and given the **&lt;variableName&gt; will confuse the function, hence spiting the error out. If you have a dictionary of kwargs and you want to print the values, you may use the syntax of *kwargs.values(). For example: args = [1, 2] kwargs = {'a':3, 'b':4} print(*args, *kwargs.values()) will print 1 2 3 4 and other combinations are: print(kwargs) # --&gt; {'a': 3, 'b': 4} print(*kwargs) # --&gt; a f print(kwargs.values()) # --&gt; dict_values([3, 4]) print(*kwargs.values()) # --&gt; 3 4 the more relevant discussion here in this post.

http://stackoverflow.com/comment/92154963
type: Comment
comment on: http://stackoverflow.com/a/52610263
score: 1
type: AnswerComment
has text: what is the different between this and mine

http://stackoverflow.com/q/52646045
favorite count: 0
has answer: http://stackoverflow.com/a/52694725
tagged with: python
has comment: http://stackoverflow.com/comment/92224049
has body: I'm working on a Supermarket Billing system. So far, I got this: # Supermarket Billing a = 0 b = 0 c = 0 while True: item = input('Item: ') amount = input('Amount: ') a = int(amount) price = input('Price: ') b = int(price) c += a * b next_item = input('Is there another item? ') if next_item != 'Yes': print('Please choose between Yes or No') if next_item == 'No': break print('Total: ', c) It works all fine. But I want to omit the price. If the user types in 'Mango' it should automatically get the price from the code and multiply the amount with the price to get a total. I tried before with: if item == 'Mango' final_price_mango = a * 23.0 #Let's say price is 23.0 So for every item I would have to give the price of the item in different block of code making the code lengthy. Is there no generic way? Say, putting the prices in a list [23.0, 43.02, 5.6, 100.75] And so automatically it'll be like Mango's price is 23.0, Flour is 43.02 and calculate accordingly?
upvote count: 0
has title: Get price of an item from a menu of many items
type: UnansweredQuestion
type: Question
score: -1
answer count: 1
downvote count: 1

http://stackoverflow.com/q/52730753
answer count: 3
downvote count: 0
favorite count: 0
tagged with: fft
has comment: http://stackoverflow.com/comment/92386692
tagged with: python
has answer: http://stackoverflow.com/a/52731424
upvote count: 6
accepted answer: http://stackoverflow.com/a/52731566
has title: How to get frequency axis from an fft function?
type: AnsweredQuestion
has body: So, I am probably missing something obvious, but I have searched through lots of tutorials and documentation and can't seem to find a straight answer. How do you find the frequency axis of a function that you performed an fft on in Python(specifically the fft in the scipy library)? I am trying to get a raw EMG signal, perform a bandpass filter on it, and then perform an fft to see the remaining frequency components. However, I am not sure how to find an accurate x component list. The specific signal I am working on currently was sampled at 1000 Hz and has 5378 samples. Is it just creating a linear x starting from 0 and going to the length of the fft'd data? I see a lot of people creating a linspace from 0 to sample points times the sample spacing. But what would be my sample spacing in this case? Would it just be samples/sampling rate? Or is it something else completely?
score: 6
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/78191784
has answer: http://stackoverflow.com/a/78191784
has answer: http://stackoverflow.com/a/52731566

http://stackoverflow.com/comment/92388392
score: 0
has text: @user2357112 Ah it worked, I didn't know naming a .py after a module/package could be the problem, Thank you I thought it was because I installed two different version of numpy causes it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52726406

http://stackoverflow.com/comment/92238995
type: Comment
has text: Also, possibly your answer should go here: [Translate every element in numpy array according to key](https://stackoverflow.com/questions/16992713/translate-every-element-in-numpy-array-according-to-key). Where it's likely to generate more views + upvotes :).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52653438

http://stackoverflow.com/q/52739143
type: Question
accepted answer: http://stackoverflow.com/a/52739144
downvote count: 0
has title: OpenCV Error: (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in function 'CvtHelper'
favorite count: 0
has answer: http://stackoverflow.com/a/58844497
has body: Traceback (most recent call last): File "demo.py", line 132, in `result = find_strawberry(image)` File "demo.py", line 63, in find_strawberry `image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)` cv2.error: OpenCV(3.4.2) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/color.hpp:253: error: (-215:Assertion failed) VScn::contains(scn) &amp;&amp; VDcn::contains(dcn) &amp;&amp; VDepth::contains(depth) in function 'CvtHelper' I personally have spent a lot of time on this question, hence thought relevant to post it on Stackoverflow. Question taken from: llSourcell/Object_Detection_demo_LIVE
has answer: http://stackoverflow.com/a/52739144
answer count: 5
tagged with: color-space
has comment: http://stackoverflow.com/comment/105847751
tagged with: python
upvote count: 16
has answer: http://stackoverflow.com/a/59856446
has answer: http://stackoverflow.com/a/58240183
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77662433
score: 16
possible better answer: http://stackoverflow.com/a/58240183

http://stackoverflow.com/q/52668563
has comment: http://stackoverflow.com/comment/92267288
has title: How to return the single in a dataframe cell while maintaining datatype
type: UnansweredQuestion
tagged with: indexing
tagged with: dataframe
type: Question
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/92266976
has comment: http://stackoverflow.com/comment/92266997
has answer: http://stackoverflow.com/a/52669048
answer count: 1
has body: So I have a dataframe that basically contains a dictionary in each cell. My index values are list of tuples like this [(10,0),(10,),(30,0),(25,2)] and the columns are just numbered starting at 1 and increasing from there. I want to try and look up an index value and column number and have it return just the dictionary stored in that cell but maintain the dictionary data type. I've tried: df.loc[[(10,0),(10,),(30,0),(25,2)],[1]].iloc[0] But it looks like thats just returning a series and i'm just getting the first item in the series. Edit: Edit I was trying to keep it as simple as possible but I realize that might've been more convoluted. I have two datadrames. 1 contains values and 2 contains a dictionary of results. I'm want to take the highest value from each column in df 1 and return the corresponding dictionary located at the same index value in df2. so for example: column 1's highest value is .3818 located at ix val: [(10,), (3,), (0,), (0, 10)] So id like to return just the dictionary stored in column 1 at that index value in df2 so just: {'Total Net Profit': 1449.99999999996, 'Max Dr..} here is what df1 and df2 look like: 1 2 ... 4 5 [(10,), (2,), (0,), (0, 10)] -0.712821 -0.716000 ... -0.392000 -0.952703 [(10,), (3,), (0,), (0, 10)] 0.381818 0.209091 ... 1.427273 0.115578 [(15,), (2,), (0,), (0, 10)] -0.929577 -0.527426 ... 0.033755 -0.219409 [(15,), (3,), (0,), (0, 10)] -1.000000 -0.768392 ... -0.316076 -0.662125 [(20,), (2,), (0,), (0, 10)] -0.863118 -0.535948 ... -0.513072 -0.735294 1 ... 5 [(10,), (2,), (0,), (0, 10)] {'Total Net Profit': -750.0000000001708, 'Max ... ... {'Total Net Profit': -9900.00000000016, 'Max D... [(10,), (3,), (0,), (0, 10)] {'Total Net Profit': 1449.99999999996, 'Max Dr... ... {'Total Net Profit': -7400.000000000018, 'Max ... [(15,), (2,), (0,), (0, 10)] {'Total Net Profit': 200.00000000003115, 'Max ... ... {'Total Net Profit': -3800.0000000000255, 'Max... [(15,), (3,), (0,), (0, 10)] {'Total Net Profit': -1400.0000000000769, 'Ma…
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/52637852
upvote count: 2
has comment: http://stackoverflow.com/comment/92228069
type: Answer
answers question: http://stackoverflow.com/q/52635798
score: 2
has comment: http://stackoverflow.com/comment/92230574
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92242726
has comment: http://stackoverflow.com/comment/92233289
has body: I played around with the parameters and managed to detect all circles (Ubuntu 16.04 LTS x64, Python 3.7, numpy==1.15.1, python-opencv==3.4.3): circles = cv2.HoughCircles( gray, cv2.HOUGH_GRADIENT, 1.7, minDist=100, param1=48, param2=100, minRadius=2, maxRadius=100 )
accepted answer of: http://stackoverflow.com/q/52635798

http://stackoverflow.com/a/52692256
has body: This can be done using lambda and sorted. When using sorted with lambda we set first key=lambda x:. Now you can think of that x representing a list index, so to sort by assignment_1 we are going to want to go x['assignments'] this will take us to the assignments, then the next step, if our assignment is assignment_1 we know that that is the 0 index of assignments so together it would be key=lambda x: x['assignments'][0]. Now we can also sort a secondary option and that will be our tie breaker, we will use x[id] and will be in a tuple with our primary sorting factor. Of course we should use reverse = True to get descending scores, but since we want our tiebreaker to be in ascending order we can offset the reverse on id using -(x['id']) Altogether the sort looks like this : lista = sorted(students, key=lambda x: (x['assignments'][0], -(x['id'])), reverse = True) The tricky part would be choosing the proper assignment index for the passed assignment, for that you could use .split('_')[1] (when using .split('_') on 'assignment_1' we generate a new list that is ['assignemnt', '1'] in this case we can take now the [1] index of .split() which is 1 as an int and subtract 1 to get 0 which is the corresponding index, as well as for the rest being that all are off 1 from their index. def highest_n_grades(students, assignment_name, n): y = int(assignment_name.split('_')[1]) - 1 lista = sorted(students, key=lambda x: (x['assignments'][y], 'id'), reverse = True) return lista [:n] print(highest_n_grades(student_list, 'assignment_1', 3)) # [{'id': 12345, 'first_name': 'Ed', 'last_name': 'Enders', 'assignments': [('assignment_1', 4), ('assignment_2', 1), ('assignment_3', 3)]}, {'id': 12344, 'first_name': 'Didi', 'last_name': 'Dawson', 'assignments': [('assignment_1', 3), ('assignment_2', 0), ('assignment_3', 2)]}, {'id': 12343, 'first_name': 'Carl', 'last_name': 'Cape', 'assignments': [('assignment_1', 2), ('assignment_2', 4), ('assignment_3', 1)]}] Demonstration of tie-breaker case…
downvote count: 0
has comment: http://stackoverflow.com/comment/92311578
has comment: http://stackoverflow.com/comment/92311855
has comment: http://stackoverflow.com/comment/92389177
has comment: http://stackoverflow.com/comment/92311553
type: Answer
answers question: http://stackoverflow.com/q/52691083
has comment: http://stackoverflow.com/comment/92312037
has comment: http://stackoverflow.com/comment/92311905
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92312282
has comment: http://stackoverflow.com/comment/92312165

http://stackoverflow.com/comment/92318726
type: Comment
comment on: http://stackoverflow.com/a/52695959
score: 0
type: AnswerComment
has text: After that you have to save the new df to csv file

http://stackoverflow.com/q/52724530
type: Question
has comment: http://stackoverflow.com/comment/92375140
has body: I have a class: Each member of the class has a value that corresponds to two coordinates (x, y) class Building: h_armory = (284, 384) h_dependance = (176, 320) h_villa = (244, 188) h_library = (410, 168) h_storage = (504, 152) h_garage = (624, 159) h_workshop = (674, 211) h_caveau = (562, 132) h_entry = (693, 354) h_wall = (401, 442) h_guard = (612, 393) Now, in a function i have a for cycle. How can i access to the class members values using a syntax like this: def myFunction(): cc = 0 for x in (Building): coord = x[cc] cc = cc + 1
tagged with: python-2.7
has title: How to access to a class member value?
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/52725016
favorite count: 0
has comment: http://stackoverflow.com/comment/92374736
has comment: http://stackoverflow.com/comment/92374622
has comment: http://stackoverflow.com/comment/92374602
has comment: http://stackoverflow.com/comment/92375286
has answer: http://stackoverflow.com/a/52725016
tagged with: python
has comment: http://stackoverflow.com/comment/92374509
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/28685828
has comment: http://stackoverflow.com/comment/92374638
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92375422
has comment: http://stackoverflow.com/comment/92374814

http://stackoverflow.com/comment/92342324
comment on: http://stackoverflow.com/q/52707891
score: 0
type: Comment
type: QuestionComment
has text: I'm not sure how to use this website and format it

http://stackoverflow.com/comment/92173536
comment on: http://stackoverflow.com/a/52619812
has text: it gives the same error in this code divs = div.find_all('div', class_ = 'text show-more__control').text
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92337984
type: QuestionComment
has text: I just added some more text and it crashed... Again.
score: 0
comment on: http://stackoverflow.com/q/52681359
type: Comment

http://stackoverflow.com/a/52600311
answers question: http://stackoverflow.com/q/52600215
upvote count: 1
has body: If you're using a pre-defined model topology, you look up the training period (in epochs or steps) in the documentation that comes with the model. If you've made your own model, you determine the training period by watching the test results. When the accuracy reaches an acceptable level and then starts to drop, you're likely over-training. Back up to the high point of accuracy. Repeat this experiment a few times to determine the "sweet spot" for your model.
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/116299995
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/65746752
type: Comment
has text: Official python's flask documentation: https://flask.palletsprojects.com/en/1.1.x/quickstart/

http://stackoverflow.com/comment/93966611
type: AnswerComment
has text: I guess you should ask for more clarifications in the comments (not as an answer).
type: Comment
score: 1
comment on: http://stackoverflow.com/a/53549954

http://stackoverflow.com/a/52653445
score: 1
has body: You can create an index that matches your criteria, and then use it to set the expected output to 1. It is not clear how to treat the expected output when the rules conflict. For example, on row 6, the expected output would be 1 because it satisfied the signal criteria from row five and fits 'the subsequent three rows where value 1 &lt; value 2'. However, it possibly conflicts with the rule that the first signal row is ignored. idx = (df .assign( grp=df['Signal'].eq(1).cumsum(), cond=df.eval('Value1 &lt; Value2')) .pipe(lambda df: df[df['grp'] &gt; 0]) # Ignore data preceding first signal. .groupby(['Group', 'grp'], as_index=False) .apply(lambda df: df.iloc[1:4, :]) # Ignore current row, get rows 1-3. .pipe(lambda df: df[df['cond']]) # Find rows where condition is met. .index.get_level_values(1) ) df['Expected_Output'] = np.nan df.loc[idx, 'Expected_Output'] = 1 &gt;&gt;&gt; df Group Signal Value1 Value2 Expected_Output 0 1 0 3 1 NaN 1 1 1 4 2 NaN 2 1 0 7 4 NaN 3 1 0 8 9 1.0 4 1 0 5 3 NaN 5 2 1 3 6 NaN 6 2 1 1 2 NaN # &lt;&lt;&lt; Intended difference vs. "expected" 7 2 0 3 4 1.0
answers question: http://stackoverflow.com/q/52652397
upvote count: 1
has comment: http://stackoverflow.com/comment/92242072
type: Answer
downvote count: 0

http://stackoverflow.com/q/52603324
has answer: http://stackoverflow.com/a/52603878
type: AnsweredQuestion
has title: Docker Flask ModuleNotFoundError: No module named 'flask'
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52603933
type: Question
has comment: http://stackoverflow.com/comment/92141333
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/92141174
score: 4
accepted answer: http://stackoverflow.com/a/52603933
has body: I'm getting the following error when executing docker-compose up --build web_1 | Traceback (most recent call last): web_1 | File "glm-plotter.py", line 4, in &lt;module&gt; web_1 | from flask import Flask, render_template, request, session web_1 | ModuleNotFoundError: No module named 'flask' glm-plotter_web_1 exited with code 1 I tried changing "Flask" to "flask" in the requirements.txt Dockerfile FROM continuumio/miniconda3 RUN apt-get update &amp;&amp; apt-get install -y python3 RUN apt-get install -y python3-pip RUN apt-get install -y build-essential COPY requirements.txt / RUN pip3 install --trusted-host pypi.python.org -r /requirements.txt ADD ./glm-plotter /code WORKDIR /code RUN ls . CMD ["python3", "glm-plotter.py"] docker-compose.yml version: "3" services: web: volumes: - ~/.aws:/root/.aws build: . ports: - "5000:5000" requirements.txt click==6.6 Flask==0.11.1 itsdangerous==0.24 Jinja2==2.8 MarkupSafe==0.23 numpy==1.11.1 pandas==0.18.1 python-dateutil==2.5.3 pytz==2016.4 six==1.10.0 Werkzeug==0.11.10 glm-plotter.py from flask import Flask, render_template, request, session import os, json import GLMparser ...
tagged with: flask
possible better answer: http://stackoverflow.com/a/52603878
tagged with: docker
upvote count: 4

http://stackoverflow.com/q/52623815
tagged with: pandas
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/52624129
favorite count: 0
has body: Assuming I have the following pandas.DataFrame: df = pd.DataFrame({'id': [1, 2, 3], 'val': [5, 5, 10], 'trig_aaa': [1, 0, 1], 'trig_bbb': [0, 1, 1], 'trig_ccc': [0, 0, 1]}) print(df) id val trig_aaa trig_bbb trig_ccc 0 1 5 1 0 0 1 2 5 0 1 0 2 3 10 1 1 1 I'd like to turn it to the following df: id val trig 0 1 5 [aaa] 1 2 5 [bbb] 2 3 10 [aaa, bbb, ccc] is there an elegant (hopefully, functionality pre-built) in Pandas/Python/Numpy? EDIT 1: After looking at jpps' comment, a better processing to the DataFrame would looks like so: id val trig 0 1 5 aaa 1 2 5 bbb 2 3 10 aaa 3 3 10 bbb 4 3 10 ccc
tagged with: python
has comment: http://stackoverflow.com/comment/92181917
has answer: http://stackoverflow.com/a/52624129
has title: Pandas - revert many hot encoded (dummy variables)
downvote count: 0
score: 1
type: Question
type: AnsweredQuestion
tagged with: numpy

http://stackoverflow.com/q/52694166
type: Question
has comment: http://stackoverflow.com/comment/92315095
has body: I am manually authenticating clients by management interface over a Unix domain socket (well by a python script). while True: # get something of queue and parse it command = "client-auth-nt " + data[2] + " " + data[3] + "\r\n" out.write(command) out.flush() This only works for one client, once. After I have connected once and successfully authenticated I cannot connect with any other client or reconnect unless I restart the OpenVPN server. ERROR: client-auth command failed What is going on? This is giving me headaches.
score: -1
has comment: http://stackoverflow.com/comment/92317769
has answer: http://stackoverflow.com/a/52707167
has comment: http://stackoverflow.com/comment/92340517
upvote count: 0
answer count: 1
favorite count: 0
tagged with: openvpn
has title: Authenticating only works once
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/92331485
has comment: http://stackoverflow.com/comment/92317803
type: UnansweredQuestion
downvote count: 1

http://stackoverflow.com/q/52668309
accepted answer: http://stackoverflow.com/a/52668492
answer count: 1
favorite count: 0
tagged with: python
tagged with: plot
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92269821
linked to: http://stackoverflow.com/q/13784201
has answer: http://stackoverflow.com/a/52668492
tagged with: loops
type: Question
has body: UPDATE: I now get the subplots in the right positions and with the right data displayed! There is, however, a problem left, and that is that I can't give the subplots their own title and colorbar. Actually, I'd rather have just one colorbar to the right of all the plots, but that doesn't seem to work either. Here is my new code along with some sample data (with is extremely uninsightful, but just for testing purposes): import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors import cartopy.crs as ccrs lons = np.arange(-180,180,1) lats = np.arange(-80,80,1) dens = np.zeros((12, len(lons), len(lats))) for i in range(12): dens[i,:,:] = i def plotTitle(yr): letter = chr(yr-2002+97) return '(' + letter + ') ' + str(yr) def DensityPlot(yr, lon, lat, dens, ax): Lat, Lon = np.meshgrid(lat, lon) density = ax.pcolormesh(Lon, Lat, dens, cmap = 'jet') #cbar = ax.colorbar(density, orientation='vertical', shrink=0.5, extend='both') # this gives an error: ''GeoAxesSubplot' object has no attribute 'colorbar'' ax.coastlines() plt.title(plotTitle(yr),fontsize=14,fontweight='bold') # this only works for the last plot. ax.title doesn't work, gives the error ''Text' object is not callable' fig, axes = plt.subplots(nrows=6, ncols=2, figsize=(35,35), subplot_kw={'projection': ccrs.PlateCarree()}) ## check figsize i=0 for ax in axes.flat: densdata = dens[i,:,:] density = DensityPlot(i+2002, lons, lats, densdata, ax) i=i+1 #ax.title(plotTitle(i+2002)) # this gives the same error as mentioned before: ''Text' object is not callable' #cbar = plt.colorbar(density, orientation='vertical', shrink=0.5, extend='both') # this gives the following RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf). fig.subplots_adjust(right=0.5) How can I make sure every subplot has its own title, and there is a colorbar next to all the subplots? I have a problem creating a set of subplot…
has title: Calling other function in making subplots in Python
score: 5
tagged with: subplot
upvote count: 5
tagged with: matplotlib
downvote count: 0

http://stackoverflow.com/q/52619164
has title: i want to solve the equations: x**2*y**2 + x**2 -10*x*y + 4*y**2 + 9.0=0,Is there any way to get the real solutions?
has comment: http://stackoverflow.com/comment/92172420
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52733637
tagged with: math
score: -1
has comment: http://stackoverflow.com/comment/92172676
type: Question
has body: I am trying to use python to solve the equations: x**2*y**2 + x**2 -10*x*y + 4*y**2 + 9.0=0, due to the equations equal to (x*y-3)**2+(x-2*y)**2=0 ,so hoping to get the real solution: x = 2*sqrt（3.0/2),y = sqrt(3.0/2)&amp;&amp; x = -2*sqrt（3.0/2),y = -sqrt(3.0/2) Is there any way to get this solutions? from sympy import * x = symbols("x") y = symbols("y") expression = x**2*y**2 + x**2 - 10*x*y + 4*y**2 + 9 solve(expression,(x,y)) above code only get the solution: [((5*y + I*(-2*y**2 + 3))/(y**2 + 1), y), ((5*y + I*(2*y**2 - 3))/(y**2 + 1), y)],thanks for your help and advice
answer count: 2
has answer: http://stackoverflow.com/a/52619209
tagged with: sympy
has comment: http://stackoverflow.com/comment/92184150
favorite count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/92184164
tagged with: python
upvote count: 0

http://stackoverflow.com/comment/92337507
has text: see the desired output in the answer..
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52704126

http://stackoverflow.com/comment/92415384
score: 0
has text: i'm sorry, i need edit the question
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52745211

http://stackoverflow.com/q/52650814
has comment: http://stackoverflow.com/comment/92234647
has comment: http://stackoverflow.com/comment/92235404
upvote count: 1
has comment: http://stackoverflow.com/comment/92244028
tagged with: python
has body: I have a python program that edits the XML in a .docx file. I'd like to edit the XML with ETree. When I read the XML from the .docx file, it begins like this: b'&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;\r\n&lt;w:document xmlns:wpc="http://schemas.micro'... This is in a variable called data. I create the element tree with: import xml.etree.ElementTree as ElementTree tree = ElementTree.XML(data) I convert it back with: data = ElementTree.tostring(tree) However, there have been subtle changes to the XML. It now looks like this: b'&lt;ns0:document xmlns:ns0="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:ns1="ht... Word won't read this, even though it is standard XML. EDIT: I tried adding the string to my XML, just to get it to round-trip: XML_HEADER=b'&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;\r\n' tree = ElementTree.XML(data) data = XML_HEADER + ElementTree.tostring(tree) But I still get the error: We're sorry. We can't open &lt;filename&gt;.docx because we found a problem with its contents. Details: The XML data is invalid according to the schema. Location: Part: /word/document.xml, Line: 0, Column:0 I can't fix word. I've got to generate XML that looks exactly like the XML that I started with. How do I get ETree to generate that?
has title: Write Open Office XML (e.g. docx) with XML that matches the OOXML namespace
tagged with: ms-word
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/92242033
answer count: 0
linked to: http://stackoverflow.com/q/19889132
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92237768
downvote count: 0
has comment: http://stackoverflow.com/comment/92239754
score: 1
has comment: http://stackoverflow.com/comment/92242009
has comment: http://stackoverflow.com/comment/92242053
type: Question
has comment: http://stackoverflow.com/comment/92242061
has comment: http://stackoverflow.com/comment/92241861

http://stackoverflow.com/comment/92155264
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52610492
has text: What is the _full_ error traceback?

http://stackoverflow.com/a/52710840
has body: Let's take a look at what is happening in these lines: tri = open('triangles.txt','r') tri_2 = tri.readlines() If you examine what is in tri_2, you should see something like this: tri_2[0] = "403 203 586" tri_2[1] = "794 919 542" … This means that tri_2 will have a size of 25 (or however many lines there are in your file), making input_numbers also have 25 entries, and then you end up passing 25 arguments to is_triangle. As others have pointed out, you should instead go line by line, extract the numbers from each line, then call is_triangle. It should be similar to this: ... ans_line = [] for line in tri_2: split_line = line.split() input_numbers = map(int, split_line) result = is_triangle(*input_numbers) ans_line.append(result) ...
answers question: http://stackoverflow.com/q/52710650
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/92348324
upvote count: 2

http://stackoverflow.com/comment/92175908
score: 0
comment on: http://stackoverflow.com/q/52620995
type: Comment
type: QuestionComment
has text: @mgracer How do i provide the parameters?

http://stackoverflow.com/q/52663976
linked to: http://stackoverflow.com/q/42614426
linked to: http://stackoverflow.com/q/38678371
tagged with: tensorflow
type: Question
tagged with: hadoop
linked to: http://stackoverflow.com/q/37800605
has body: I am trying to read from external hadoop from tensorflow on my mac. I have built tf with hadoop support from source, and also build hadoop with native library support on my mac. I am getting the following error , hdfsBuilderConnect(forceNewInstance=0, nn=192.168.60.53:9000, port=0, kerbTicketCachePath=(NULL), userName=(NULL)) error: java.lang.NoSuchFieldError: LOG at org.apache.hadoop.ipc.ClientCache.getClient(ClientCache.java:62) at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.&lt;init&gt;(ProtobufRpcEngine.java:145) at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.&lt;init&gt;(ProtobufRpcEngine.java:133) at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.&lt;init&gt;(ProtobufRpcEngine.java:119) at org.apache.hadoop.ipc.ProtobufRpcEngine.getProxy(ProtobufRpcEngine.java:102) at org.apache.hadoop.ipc.RPC.getProtocolProxy(RPC.java:579) at org.apache.hadoop.hdfs.NameNodeProxies.createNNProxyWithClientProtocol(NameNodeProxies.java:418) at org.apache.hadoop.hdfs.NameNodeProxies.createNonHAProxy(NameNodeProxies.java:314) at org.apache.hadoop.hdfs.NameNodeProxies.createProxy(NameNodeProxies.java:176) at org.apache.hadoop.hdfs.DFSClient.&lt;init&gt;(DFSClient.java:678) at org.apache.hadoop.hdfs.DFSClient.&lt;init&gt;(DFSClient.java:619) at org.apache.hadoop.hdfs.DistributedFileSystem.initialize(DistributedFileSystem.java:149) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373) at org.apache.hadoop.fs.FileSystem$1.run(FileSystem.java:162) at org.apache.hadoop.fs.FileSystem$1.run(FileSystem.java:159) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformat…
has answer: http://stackoverflow.com/a/52807801
downvote count: 0
tagged with: hdfs
favorite count: 0
has title: Tensorflow Read from HDFS mac : java.lang.NoSuchFieldError: LOG
answer count: 1
tagged with: macos
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2

sorting
tags question: http://stackoverflow.com/q/52590393
tags question: http://stackoverflow.com/q/52622323
tags question: http://stackoverflow.com/q/52635572
tags question: http://stackoverflow.com/q/52695826
tags question: http://stackoverflow.com/q/52723103
tags question: http://stackoverflow.com/q/52606057
tags question: http://stackoverflow.com/q/52656497
tags question: http://stackoverflow.com/q/52661772
tags question: http://stackoverflow.com/q/52687901
tags question: http://stackoverflow.com/q/52717742
tags question: http://stackoverflow.com/q/52737799
tags question: http://stackoverflow.com/q/52638053
tags question: http://stackoverflow.com/q/52607375
tags question: http://stackoverflow.com/q/52614090
type: Tag
tags question: http://stackoverflow.com/q/52730850
tags question: http://stackoverflow.com/q/52693903
tags question: http://stackoverflow.com/q/52729337
tags question: http://stackoverflow.com/q/52648935
tags question: http://stackoverflow.com/q/52708259
tags question: http://stackoverflow.com/q/52730200
tag name: sorting
tags question: http://stackoverflow.com/q/52686557
tags question: http://stackoverflow.com/q/52694415
tags question: http://stackoverflow.com/q/52609724
tags question: http://stackoverflow.com/q/52658646
tags question: http://stackoverflow.com/q/52744755
tags question: http://stackoverflow.com/q/52654020
tags question: http://stackoverflow.com/q/52657017

http://stackoverflow.com/comment/92939659
type: Comment
comment on: http://stackoverflow.com/a/52759127
type: AnswerComment
has text: To comment on what you call the analytical solution: if I understand correctly, you're fitting a Gaussian, which your true posterior really isn't. This technique is called Laplace approximation and while it minimizes the error of the inferred mean and variance, it won't capture the true posterior's higher moments, like skew and kurtosis. Just be aware that this approach has that limitation. I think this can explain why we see a difference between your plots.
score: 0

http://stackoverflow.com/a/52776453
has body: Even if I do not know why my initial definition was wrong, the following works as expected: mi = {'input':['a','b','c'],'optim':['pareto','alive']} mi = pd.MultiIndex.from_tuples([(c,k) for c in mi.keys() for k in mi[c]]) mc = pd.MultiIndex.from_tuples([(0,0)],names=['Generation','Individual']) population = pd.DataFrame(index=mi,columns=mc) It looks like the solution was to initialize the columns at the DataFrame creation (here with a (0,0) column). The created DataFrame is then: Generation 0 Individual 0 input a NaN b NaN c NaN optim pareto NaN alive NaN which can be then be populated adding values to the current column or new columns/rows.
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52744150
answers question: http://stackoverflow.com/q/52744150

http://stackoverflow.com/a/52599622
type: Answer
has body: You may use re.sub(r'(https?|ftps?)://|/', lambda x: x.group(0) if x.group(1) else '%', s) Details (https?|ftps?):// - matches and captures into Group 1 http/https/ftp/ftps (add more if needed) and then matches :// | - or / - matches / in any other context If Group 1 is matched, the whole match is pasted back, else, the / is replaced with %. See the Python demo: import re s = 'https://example.com/example/page/' print(re.sub(r'(https?|ftps?)://|/', lambda x: x.group(0) if x.group(1) else '%', s)) # =&gt; https://example.com%example%page%
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52599565
answers question: http://stackoverflow.com/q/52599565
upvote count: 2

http://stackoverflow.com/comment/92402731
comment on: http://stackoverflow.com/a/52738406
type: Comment
score: 0
type: AnswerComment
has text: Can u attach both the outputs/screenshots? so that I can understand it.

http://stackoverflow.com/comment/92305609
score: 0
type: Comment
type: QuestionComment
has text: screen_names would be like [daniella, ForceBru, tompearce, jeremeycorbyn, etc] for about 180 users. I want to run through that to pull the last X tweets for them all. Should I move to the chat as it keeps asking!
comment on: http://stackoverflow.com/q/52688864

http://stackoverflow.com/q/52722821
favorite count: 0
has comment: http://stackoverflow.com/comment/92371689
has title: How to be able to select the text in a tkinter Message widget?
has comment: http://stackoverflow.com/comment/92371041
tagged with: tkinter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52724103
has comment: http://stackoverflow.com/comment/92371232
upvote count: 1
tagged with: python
tagged with: tkinter-layout
tagged with: tkinter-menu
score: 1
has body: I have a nice design for my GUI. I would want to be able to select the text displayed in Message widgets. The only suggestions I saw are to either use an Entry widget in the read only mode, but this looks completely different than a Message widget or to use a Text widget which again looks completely different. How can I select the text in a Message widget? If this is not possible, how would I get a Text or Entry widget to look and behave the same as a Message widget?
has comment: http://stackoverflow.com/comment/92371330
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52688693
has title: Accessing Second HTML using selenium and python to extract image
favorite count: 0
tagged with: webdriverwait
has body: I have to extract images from the web using selenium. I have to extract an image that is present inside second html tag. can someone help me in ways to point to image that is present in the second html tag. sample html code. &lt;html&gt; &lt;img class = "img-responsive" src="test.png"&gt; &lt;html&gt; &lt;img src = 'test1.png'&gt; &lt;/html&gt; &lt;html&gt; actual path looks like this : html/body/div/div/div/div/div/iframe.embed-responsive-item/html/body/img i have tried using driver.find_element_by_xpath('//*[@src]') It gives me all the images except the image present in the second html tag.
possible better answer: http://stackoverflow.com/a/52689451
tagged with: python
has answer: http://stackoverflow.com/a/52689451
tagged with: selenium-webdriver
type: AnsweredQuestion
upvote count: 2
tagged with: iframe
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/52692763
answer count: 2
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/52692763

http://stackoverflow.com/comment/92230919
score: 0
has text: Thanks deceze dis helps
type: QuestionComment
comment on: http://stackoverflow.com/q/52649416
type: Comment

http://stackoverflow.com/a/52719192
has body: You can use single quotes in the string and use the parametrized string to substitute with your values. QUERY = """select lat, lon, gender from table_x where x_name = '{namestring}'""" for namestring in list_of_namestrings: cur.execute(QUERY.format(namestring=namestring) This should solve your purpose, you can make the QUERY as complex as you desire, and make the required substitutions using .format()
score: 0
answers question: http://stackoverflow.com/q/52713421
type: Answer

http://stackoverflow.com/q/52677634
possible better answer: http://stackoverflow.com/a/59177578
type: Question
has answer: http://stackoverflow.com/a/77733800
has answer: http://stackoverflow.com/a/63953768
tagged with: python-2.7
has answer: http://stackoverflow.com/a/60889540
accepted answer: http://stackoverflow.com/a/54783328
has answer: http://stackoverflow.com/a/52885983
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/59177578
score: 8
favorite count: 0
has body: I am trying to load a NLP model 'en' from SpaCy in my PyCharm and I am using Python 2.7 . My code to load the 'en' model is nlp = spacy.load('en', disable=['parser', 'ner']) However, I received the following error IOError: [E050] Can't find model 'en'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory. I then realised that I didn't download the model, so I used the terminal provided in PyCharm to download the model, I used python -m spacy download en This was the following output: Requirement already satisfied: en_core_web_sm==2.0.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0. tar.gz#egg=en_core_web_sm==2.0.0 in c:\python27\lib\site-packages You are using pip version 9.0.1, however version 18.0 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. You do not have sufficient privilege to perform this operation. Linking successful C:\Python27\lib\site-packages\en_core_web_sm --> C:\Python27\lib\site-packages\spacy\data\en You can now load the model via spacy.load('en') So I am quite confused... I presume that I was unable to download the 'en' model as I do not have enough privileges to do so, but how was the linking successful? Upon seeing this message, I tried running my Python file again ( since the terminal stated that linking was successful) but the initial error popped out again. Has anybody encountered this problem before, or knows how to solve this error? How am I able to 'escalate' my privileges in PyCharm terminal so that I will be able to download the model?
has answer: http://stackoverflow.com/a/54783328
upvote count: 8
has title: PyCharm can't find Spacy Model 'en'
tagged with: python
tagged with: nlp
has answer: http://stackoverflow.com/a/60896379
type: AnsweredQuestion
tagged with: spacy

http://stackoverflow.com/a/61505259
has body: This error "TypeError: 'NoneType' object is not iterable" is most probably due to an incorrect SQL statement in the query.
answers question: http://stackoverflow.com/q/52699317
score: 0
type: Answer

http://stackoverflow.com/q/52648318
has body: Say I have a table like this INDEX COL_A COL_B 1 Yes 6 2 No 7 3 Yes 6 I can read that with import pandas as pd df = pd.read_table('table', delimiter='\s\s+') as suggested here https://stackoverflow.com/a/43225248/3014199. But this assumes that there are no empty cells. If a cell in the (last) column B is missing I'm in luck and the cell gets filled with None but if a cell in column A is empty all cells to the right of it are shifted one cell left and the None is in column B again. I could do this by hand, infering the indices for slicing from the header and then manually build a df from a list of lists but I was wondering if it could be done with pandas. Update: df = pd.read_fwf('table', index_col=0) does the trick!
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/52651053
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52651053
has comment: http://stackoverflow.com/comment/92228965
type: AnsweredQuestion
score: 2
type: Question
has title: How to read a pretty printed table with empty cells in pandas?
linked to: http://stackoverflow.com/q/43224981
downvote count: 0
upvote count: 2

python-module
tags question: http://stackoverflow.com/q/52675605
type: Tag
tag name: python-module
tags question: http://stackoverflow.com/q/52668290
tags question: http://stackoverflow.com/q/52724222

http://stackoverflow.com/comment/92193340
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52629457
has text: My guess would be it's caused by forking a multithreaded app. Now bnaecker also dropped this ;) I would suggest to try with starting the process with spawn method but since you're on Python 2.7 there's no nice way to do it. You would need to use `subprocess` to spawn it.
score: 0

http://stackoverflow.com/comment/92294292
has text: Hm, so just uninstall Python 3.6?
score: 0
comment on: http://stackoverflow.com/q/52677089
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92253446
comment on: http://stackoverflow.com/q/52661673
type: QuestionComment
type: Comment
has text: This answer might be of help https://stackoverflow.com/questions/23691133/split-pandas-dataframe-based-on-groupby
score: 1

http://stackoverflow.com/comment/92280210
type: QuestionComment
score: 0
has text: you need to define a `return` at the end of your cubeVolume function
comment on: http://stackoverflow.com/q/52675402
type: Comment

http://stackoverflow.com/comment/92197334
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52631694
score: 0
has text: Your function definition is not receiving any argument any argument `text`, that is the reason for your error, I believe

http://stackoverflow.com/a/52720748
has comment: http://stackoverflow.com/comment/92367615
has comment: http://stackoverflow.com/comment/92368225
has comment: http://stackoverflow.com/comment/92366678
has comment: http://stackoverflow.com/comment/92367099
has comment: http://stackoverflow.com/comment/92367029
has comment: http://stackoverflow.com/comment/92367537
accepted answer of: http://stackoverflow.com/q/52720637
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52720637
has comment: http://stackoverflow.com/comment/92368315
has comment: http://stackoverflow.com/comment/92366815
has comment: http://stackoverflow.com/comment/92366702
has body: As specified in the documentation for latest(*fields) [Django-doc]: Returns the latest object in the table based on the given field(s). This example returns the latest Entry in the table, according to the pub_date field: Entry.objects.latest('pub_date') So if you want to obtain the latest object with respect to a field (for example updated_date), you can write this as: selectdate.objects.filter( User=self.request.user ).latest('updated_date') You can however use the latest() without parameters, given you specified the order for this in the Meta class of the model, like: class Foo(models.Model): name = models.CharField(max_length=20) class Meta: get_latest_by = ['name'] In that case Foo.objects.latest() will give the Foo object with the maximum name (if we here compare the names lexicographically).
type: Answer
has comment: http://stackoverflow.com/comment/92368327
has comment: http://stackoverflow.com/comment/92367656
upvote count: 13
has comment: http://stackoverflow.com/comment/92367689
has comment: http://stackoverflow.com/comment/92366790
score: 13
has comment: http://stackoverflow.com/comment/92368247
has comment: http://stackoverflow.com/comment/92367463

http://stackoverflow.com/comment/92366879
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52657547
type: AnswerComment
has text: @cdlane Relatively simple. Please see my recent edit.

delimiter
tags question: http://stackoverflow.com/q/52733087
tags question: http://stackoverflow.com/q/52708315
tag name: delimiter
type: Tag
tags question: http://stackoverflow.com/q/52670635

http://stackoverflow.com/q/52635303
tagged with: python
has comment: http://stackoverflow.com/comment/92203896
has comment: http://stackoverflow.com/comment/92204121
has body: Im quite a newbie to this so bear with me. Im trying to perform a continuous loop of key press and releases on a specific element all the time it is visible. This is what i have: def do something(self): element = driver.find_element_by_xpath(variable) while element.is_displayed(): ActionChains(driver).click_and_hold(element).perform() time.sleep(2) ActionChains(driver).release(element).perform() time.sleep(2) driver.quit() the issue is that is seems to still attempt to perform the action even when the element is no longer visible. The element is expected to disappear after a random amount of time, therefore the loop should end but i always get the error: StaleElementReferenceException: Message: The element reference of &lt;div id="hearing-test-button" class="btn-mega null"&gt; is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
type: Question
has answer: http://stackoverflow.com/a/52735023
score: 0
has comment: http://stackoverflow.com/comment/92334661
has title: while loop not working when element is no longer visible - python
answer count: 1
has comment: http://stackoverflow.com/comment/92394622
has comment: http://stackoverflow.com/comment/92292423
has comment: http://stackoverflow.com/comment/92241957
type: UnansweredQuestion

http://stackoverflow.com/comment/92341487
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52653638
type: Comment
has text: @BetterEnglish "I think it does not make sense to define predict_prob only on the classification layer." I see your point that you might be able define posterior probability in case of a regression task but it might differ from task to task. And I guess that's why it is not supported in the first place. However, in case of a classification task actually the outputs of the model are directly probabilities (at least this is the presumption) and therefore [`model.predict()` is equivalent to `model.predict_proba()`](https://github.com/keras-team/keras/blob/master/keras/engine/sequential.py#L231).

http://stackoverflow.com/comment/114491522
type: AnswerComment
has text: The problem is I am not reading from disk! I am taking image from camera and I want to convert it immediately to grayscale without saving it on disk!
type: Comment
comment on: http://stackoverflow.com/a/52844422
score: 0

http://stackoverflow.com/comment/92283923
type: QuestionComment
has text: Well, I haven't show all my .txt files, but it consists of multiple lines!
comment on: http://stackoverflow.com/q/52676396
score: 0
type: Comment

http://stackoverflow.com/a/63306162
score: 1
type: Answer
upvote count: 1
has body: I was able to do this in my views.py to generate a QR code dynamically. import segno from django.views.generic.base import TemplateView from .models import MyModel class QRCodeView(TemplateView): template_name = "my_template.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) param = self.kwargs['param'] # this is how to grab something from the url pattern # scale=10 changes size of saved image # svg_data_uri (or png_data_uri) is saved in memory and easily put in html # .make_qr forces a non-micro QR code qr_code = segno.make_qr(f"MY {param} DATA").svg_data_uri(scale=10) context['qrcode'] = qr_code return context Now I can access this in my template.html I prefer this to using a buffer because there is no need to convert to/from Byte/Image, no other libraries needed.
answers question: http://stackoverflow.com/q/52739363
downvote count: 0

http://stackoverflow.com/a/52681737
has comment: http://stackoverflow.com/comment/92310384
score: 0
answers question: http://stackoverflow.com/q/52680729
type: Answer
has body: Your traceback comes from Python 2.7 while you refer to python3-pysnmp-4.4.6. Please make sure you are using pysnmp version which is compatible with the examples. As a side note, the example script you are running will not respond to SNMP v1 queries unless you add: config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (1, 3, 6, 5)) call to it.
has comment: http://stackoverflow.com/comment/92310462

http://stackoverflow.com/comment/92225125
type: QuestionComment
score: 0
has text: Category class has slugs!
comment on: http://stackoverflow.com/q/52627282
type: Comment

http://stackoverflow.com/comment/92277108
score: 0
has text: @roganjosh is correct. `np.vectorize` simply provides the abiluty to apply a function to an entire array, rather than to each element, it does not avoid iteration. From the docs: "The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop."
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52673285

http://stackoverflow.com/a/52612696
upvote count: 1
has comment: http://stackoverflow.com/comment/92164063
type: AcceptedAnswer
downvote count: 0
has body: Consider using pd.DataFrame.eval with pd.DataFrame.pipe: def refactored(df, oldcol, dftest, replace, mod_col, series_col): # ...some logic... test = df.eval(dftest).replace([np.inf, -np.inf], np.nan) # ... some more logic... df.loc[mask, mod_col] = df.eval(series_col) return df df = df.pipe(refactored, 'col1', 'colX / colZ / colY / colX', np.nan, 'col1_mod', '(colX - colZ) / colY')\ .pipe(refactored, 'col2', 'colA / colY / colA', 0.0, 'col2_mod', 'colA / colY') In general, you should never need to pass series as function arguments.
accepted answer of: http://stackoverflow.com/q/52612526
answers question: http://stackoverflow.com/q/52612526
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/92164780

http://stackoverflow.com/a/52655873
type: Answer
has comment: http://stackoverflow.com/comment/92243348
score: 0
has body: You need to install matplotlib/mpl_finance at https://github.com/matplotlib/mpl_finance git clone https://github.com/matplotlib/mpl_finance.git mpl_finance.git cd mpl_finance.git python setup.py install
answers question: http://stackoverflow.com/q/52655847

parameters
tags question: http://stackoverflow.com/q/52690801
tags question: http://stackoverflow.com/q/52671593
type: Tag
tags question: http://stackoverflow.com/q/52747036
tag name: parameters
tags question: http://stackoverflow.com/q/52623323

http://stackoverflow.com/q/52694063
has answer: http://stackoverflow.com/a/52694157
upvote count: 2
has title: Product Process Order
possible better answer: http://stackoverflow.com/a/52694157
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92314890
has comment: http://stackoverflow.com/comment/92314927
has body: I want to make a simple process order like : You filled an order for 1 antacid for a total of $5.33 You filled an order for 3 sour bites for a total of $6.99 My code is: total = 0 def process_order(x_list): for x in len(x_list): print(f"You filled an order for{x[1]} {x[0]} for a total of {x[1]* x[2]}") x = [("oranges", 4, 3.22),("gummy bears",1,1.99),("sour bites", 3, 2.33), ("antacid", 1, 5.33)] while(len(x)&gt;0): process_order(x) print("Total price: ${:.2f}".format(total)) But I got error TypeError: 'int' object is not iterable
accepted answer: http://stackoverflow.com/a/52694134
has comment: http://stackoverflow.com/comment/92315016
type: Question
has comment: http://stackoverflow.com/comment/92314932
downvote count: 0
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/52694207
tagged with: python
has answer: http://stackoverflow.com/a/52694134
has comment: http://stackoverflow.com/comment/92314934
tagged with: python-3.x
score: 2

http://stackoverflow.com/q/52601345
favorite count: 0
has answer: http://stackoverflow.com/a/52602459
type: UnansweredQuestion
tagged with: python
tagged with: pandas-to-sql
score: 1
linked to: http://stackoverflow.com/q/48006551
has body: I am trying to use Pandas' to_sql method to upload multiple csv files to their respective table in a SQL Server database by looping through them. fileLoc = r'C:\Users\hcole\Downloads\stats.csv\\' dfArray = ['file1', 'file2', 'file3', 'file4'] for name in dfArray: df = pd.read_csv(fileLoc + name + '.csv') df.columns = df.columns.str.replace(' ', '') df.to_sql(name, engine, if_exists = 'append', index = False) My connection string and database connection is working fine; I make it through the first few (and small) files just fine. But as soon as I hit file4, which contains ~135k rows, it takes nearly an hour to upload all of the data to the database. I've tried downgrading to Pandas version 0.22 after reading documentation on the "chunksize" argument of to_sql, but have had no luck with that speeding up the process. Any tips on how to improve the speed would be appreciated. Thank you.
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/59407226
tagged with: sql-server
has title: Speeding up Pandas to_sql method
answer count: 2
tagged with: pandas
tagged with: sql
downvote count: 0

http://stackoverflow.com/comment/92191690
comment on: http://stackoverflow.com/a/52618257
type: Comment
has text: I don't understand why next is needed. why isn't just choices enough?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92323473
type: QuestionComment
comment on: http://stackoverflow.com/q/52697884
score: 0
has text: For some reason, the problem comes from the difference between `scatter()` and `plot()`, if you were to replace `plt.scatter` by `plt.plot()` in Fig4, your two figures should come out identical. I don't know why the limits of the axes are chosen poorly in one case and not the other unfortunately.
type: Comment

http://stackoverflow.com/q/52707533
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52707719
duplicate of: http://stackoverflow.com/q/15753701
has body: i need to use shell command to run python script but the args is a list the python script: #!/usr/bin/env python # -*- coding: UTF-8 -*- import sys def main(task_list): print('task_list:',task_list) if __name__=='__main__': main(sys.argv[1]) when i use the shell python python scrpit.py [("store", "IDCODE", 18116485, 88779)] the system show: "(' have a error" how can i trans the list into script ? the ("store", "IDCODE", 18116485, 88779) is a arg
tagged with: python
has answer: http://stackoverflow.com/a/52708055
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52708591
possible better answer: http://stackoverflow.com/a/52708055
upvote count: 1
accepted answer: http://stackoverflow.com/a/52707719
has title: shell command run python script with args which is a list
type: Question
answer count: 3
linked to: http://stackoverflow.com/q/15753701
downvote count: 0
tagged with: shell
tagged with: command
favorite count: 0

http://stackoverflow.com/comment/92225187
comment on: http://stackoverflow.com/a/52641941
type: Comment
has text: how can i write the 583 'PRG' results in the third column of csv?
type: AnswerComment
score: 0

http://stackoverflow.com/a/52822673
type: Answer
answers question: http://stackoverflow.com/q/52681365
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/52681365
has body: Thanks for the advice. However, I was advised specifically not to install Anaconda -- can't quite remember the reason but I think it's because, basically, if I ever decided I wanted to use something else then it would be a real headache to switch. I'm happy to hear your reasoning if you disagree with that. I ended up solving the issue by uninstalling every package both within the virtual environment and the larger computer system, then re-installing it in both places. It worked, but I'm sort of confused as to what the point of a virtual environment is, if I still had to install everything twice.

http://stackoverflow.com/comment/92193899
type: AnswerComment
has text: Your method give me a shape of (240,5) (using 10 dim) I need something like (10,24,5)
type: Comment
comment on: http://stackoverflow.com/a/52630001
score: 0

http://stackoverflow.com/a/52663589
has comment: http://stackoverflow.com/comment/92276464
type: Answer
accepted answer of: http://stackoverflow.com/q/52663518
answers question: http://stackoverflow.com/q/52663518
has comment: http://stackoverflow.com/comment/98039800
score: 34
has body: I have the feeling the text parameter has been added in 3.7, not 3.6. Relevant part of the doc: Changed in version 3.7: Added the text parameter, as a more understandable alias of universal_newlines. Added the capture_output parameter.
upvote count: 34
has comment: http://stackoverflow.com/comment/98068999
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92291992
has text: A general rule in programming is **Simple is better than complicated** so if you can do it with only one loop instead of two, most of the time it is better to use only one. But for a more general case, sometime it is necessary to use nested loops, even if the lesser the better.
type: Comment
comment on: http://stackoverflow.com/a/52681750
score: 0
type: AnswerComment

http://stackoverflow.com/a/52675100
upvote count: 0
answers question: http://stackoverflow.com/q/52675084
type: Answer
downvote count: 1
score: -1
has body: Calling .read() and iterating with for ... in ... both consume the contents of the file. You can't do both unless you call .seek(0) in between. Alternatively, instead of calling .read(), you could capture the lines in your for loop (maybe switch to .readlines()) and then not worry about it.

http://stackoverflow.com/comment/92320656
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52690451
has text: But yes, I want more since for now, you still did not share a canoncial answer. Somehow you did not only give a pars-pro-toto answer, but also a pars-pro-toto link :) Perhaps I should have been more specific, can you provide a *canonical* link that specifies that the shortest answer is the best?

window
tags question: http://stackoverflow.com/q/52698395
tag name: window
type: Tag
tags question: http://stackoverflow.com/q/52691720

http://stackoverflow.com/comment/92387813
type: AnswerComment
has text: I figured everything out except my initial question. When their are two or more ties in a row, it is supposed to count those cards up and give the winner however many ties there was and the loser is supposed to lose that many cards. I can't figure out how to do that. That was the initial question.
type: Comment
comment on: http://stackoverflow.com/a/52731124
score: 0

http://stackoverflow.com/comment/92225277
type: Comment
has text: @jeremydevera - I know how write to 3 column of DataFrame, `use df.iloc[:, 2] = PRG`, `2` is because pythoun counts from 0
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52641941

http://stackoverflow.com/q/52718194
has comment: http://stackoverflow.com/comment/92362481
tagged with: python
has answer: http://stackoverflow.com/a/52718431
has comment: http://stackoverflow.com/comment/92361899
tagged with: big-o
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92361941
tagged with: list-comprehension
has title: Python - Big(O) Runtime: List Comprehension & For Loop
type: Question
has answer: http://stackoverflow.com/a/52718290
answer count: 2
tagged with: for-loop
has body: In CTCI(Python version), the runtime of the code below is described to be O(N) # O(N) def unique(string): # Assuming character set is ASCII (128 characters) if len(string) &gt; 128: return False char_set = [False for _ in range(128)] for char in string: val = ord(char) if char_set[val]: # Char already found in string return False char_set[val] = True return True This really confuses me as I see a list comprehension in the formation of char_set and another for loop right after... shouldn't the run-time be O(N ^ 2)? Edit: I'm also confused as to why Laakman uses len(string) > 128 to check for ascii char. Wouldn't that just give the length of the string in question and not the character value which the ord method in Python gives? Edit1: Can the same be achieved if she doesn't use val = ord(char) ? That would change the next line to if char_set[char]:
score: 0

http://stackoverflow.com/comment/92388010
type: Comment
type: QuestionComment
score: 0
has text: did you tried 'import pypdf2' lowcase? Did you try install it by downloading from PyPI, then running setup.py install?
comment on: http://stackoverflow.com/q/52731358

http://stackoverflow.com/comment/92172476
has text: `data.groupby('id')['day'].diff().fillna(0).gt(1).astype(int)` might also work.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52599143
score: 1

http://stackoverflow.com/a/68267834
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52684331
has body: The problem lies in the too large value of the parameter C. I once faced exactly the same problem myself, and it was solved by decreasing C. Note that C is a regularization parameter, there is absolutely no point in such large values. (Refer to https://stats.stackexchange.com/questions/31066/what-is-the-influence-of-c-in-svms-with-linear-kernel). And it seems that as C increases, the computation time grows exponentially. In fact in my experience, values ​​greater than 10 will consistently degrade the performance of the model.

http://stackoverflow.com/a/52604167
upvote count: 1
score: 1
downvote count: 0
has body: You will need to convert the strings to datetime objects using the strptime method.
type: Answer
answers question: http://stackoverflow.com/q/52600125

http://stackoverflow.com/comment/92141969
comment on: http://stackoverflow.com/q/52603071
type: Comment
type: QuestionComment
has text: @brunodesthuilliers The intention is apparently to allow the user to have a choice between calling the original function and calling the decorated version easily.
score: 1

http://stackoverflow.com/q/52632522
accepted answer: http://stackoverflow.com/a/52632575
has body: So I am trying to make a function where a user is asked for a text to input and the result should print an encrypted version of the text. The way it should work is that all symbols not matching any symbol in this variable: alphabet = "abcdefghijklmnopqrstuvwxyz ?" should be replaced with a question mark '?'. So for example: 'THIS is a t#est' would result in '???? is a t?est'. This is what I got so far. alphabet = "abcdefghijklmnopqrstuvwxyz ?" xalphabet = list(alphabet) code = input('Please enter the text you want to code: ') xcode = list(code) def clean_text(xcode): for xcode in xalphabet: if xcode == xalphabet: continue else: xcode.replace(xcode, '?') return xcode def main (): print(clean_text(xcode)) if __name__ == "__main__": main() What I got only prints '?'
has title: How can I replace all occurences of symbols that do not appear in a predefined string/list?
downvote count: 0
possible better answer: http://stackoverflow.com/a/52632619
has answer: http://stackoverflow.com/a/52632619
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52632575
score: 1
has comment: http://stackoverflow.com/comment/92198442
has comment: http://stackoverflow.com/comment/92198417
type: Question
answer count: 2
tagged with: function

http://stackoverflow.com/comment/92454959
type: Comment
score: 1
has text: I made mistake in the way the string input was being used. I had to add single quotes before I passed into the script to get the other columns I needed.
type: AnswerComment
comment on: http://stackoverflow.com/a/52738642

http://stackoverflow.com/q/52722520
tagged with: python
has title: Remove every third element from a list
duplicate of: http://stackoverflow.com/q/32925532
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92370460
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/32925532
score: -1
accepted answer: http://stackoverflow.com/a/52722611
upvote count: 0
has body: In this code piece I print the index numbers in a list. x = '1 2 3 4 67 8' x = list(map(int, x.split())) # something here with modulo?? print(x) Output: [1, 2, 3, 4, 67, 8] I want to output [1, 2, 4, 67] So the 3th element, 6th, 9th etc...
answer count: 1
has answer: http://stackoverflow.com/a/52722611
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/92223045
type: QuestionComment
has text: You don't have lists of questions there.
comment on: http://stackoverflow.com/q/52645142
score: 0
type: Comment

http://stackoverflow.com/comment/92219351
has text: @BlackBeard, I think you misunderstand. It's *not* what you **want**, it's what you **use** that matters.
comment on: http://stackoverflow.com/a/52643105
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52715499
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52718488
has comment: http://stackoverflow.com/comment/99980971
tagged with: python
has body: I have spent several hours trying to set up Tensorflow serving of the Tensorflow-hub module, "Universal Sentence Encoder." There is a similar question here: How to make the tensorflow hub embeddings servable using tensorflow serving? I have been doing this on a Windows machine. This is the code I used to build the model: import tensorflow as tf import tensorflow_hub as hub MODEL_NAME = 'test' VERSION = 1 SERVE_PATH = './models/{}/{}'.format(MODEL_NAME, VERSION) with tf.Graph().as_default(): module = hub.Module("https://tfhub.dev/google/universal-sentence- encoder/1") text = tf.placeholder(tf.string, [None]) embedding = module(text) init_op = tf.group([tf.global_variables_initializer(), tf.tables_initializer()]) with tf.Session() as session: session.run(init_op) tf.saved_model.simple_save( session, SERVE_PATH, inputs = {"text": text}, outputs = {"embedding": embedding}, legacy_init_op = tf.tables_initializer() ) I have gotten to the point where running the following line: saved_model_cli show --dir ${PWD}/models/test/1 --tag_set serve --signature_def serving_default gives me the following result: The given SavedModel SignatureDef contains the following input(s): inputs['text'] tensor_info: dtype: DT_STRING shape: (-1) name: Placeholder:0 The given SavedModel SignatureDef contains the following output(s): outputs['embedding'] tensor_info: dtype: DT_FLOAT shape: (-1, 512) name: module_apply_default/Encoder_en/hidden_layers/l2_normalize:0 I have then tried running: saved_model_cli run --dir ${PWD}/models/test/1 --tag_set serve --signature_def serving_default --input_exprs 'text=["what this is"]' which gives the error: File "<string>", line 1 [what this is] ^ SyntaxError: invalid syntax I've tried changing the format of the part 'text=["what this is"]', but nothing worked for me. Regardless of if this part works, the main goal is to set up the module for serving and create a callable API. I've tried with docker, the following line: docker run -p 8501:8501 --name tf-serve…
linked to: http://stackoverflow.com/q/52671138
tagged with: tensorflow-hub
type: AnsweredQuestion
upvote count: 14
linked to: http://stackoverflow.com/q/50788080
tagged with: tensorflow
type: Question
score: 14
tagged with: tensorflow-serving
has answer: http://stackoverflow.com/a/52718488
has comment: http://stackoverflow.com/comment/100005591
has title: How to serve a tensorflow-module, specifically Universal Sentence Encoder?

http://stackoverflow.com/q/52619276
tagged with: vips
has comment: http://stackoverflow.com/comment/92779618
has comment: http://stackoverflow.com/comment/92934698
has body: I'm using Pillow (version 5.2.0) on Python3 to open both PNG and BMP images, and display them with a Tkinter GUI. The PNG images display correctly with no issues, however, I'm encountering an IOError ("Unsupported BMP compression") with some of the BMP images, when Pillow's BmpImagePlugin.py is used. Using the bitmap plugin's source and some print statements, I found that the exception is thrown at line 193, and that the images causing the exception are compressed using RLE8 (denoted by the dictionary on line 63); all others work because they're a RAW format. It would seem to me that if a compression type is listed in that dictionary it should be supported, but apparently that isn't the case. My question: is anyone aware of a workaround in Pillow or of any other python library that can open RLE8 bitmap images? Here's an image displaying my PATH environment, as well as the command-line error described in a comment below. Path issues
tagged with: python
accepted answer: http://stackoverflow.com/a/52936728
tagged with: bitmap
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92309643
has comment: http://stackoverflow.com/comment/92781317
tagged with: python-imaging-library
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52936728
type: Question
has comment: http://stackoverflow.com/comment/92176354
has comment: http://stackoverflow.com/comment/92339138
has title: RLE8 image support/decompression with Pillow (PIL fork)
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/92935781
favorite count: 0

http://stackoverflow.com/comment/92414727
comment on: http://stackoverflow.com/a/52745005
has text: @G_M Op was casting `int` to the input without accounting for `non-int`s being entered, so I didn't want to add another element that they were either not concerned about or not up to speed with
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92366349
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52720552
score: 0
has text: Low quality dupe candidate for a low quality question: [Python - accessing values nested within dictionaries](//stackoverflow.com/q/11700798)

http://stackoverflow.com/comment/92144509
type: Comment
has text: @ΝικόλαοςΒέργος does that help in any way?
comment on: http://stackoverflow.com/a/52604909
score: 0
type: AnswerComment

http://stackoverflow.com/q/52602257
tagged with: python-docx
accepted answer: http://stackoverflow.com/a/52602365
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92138820
has body: I can use this code to insert an image into docx file from docx import Document document = Document() p = document.add_paragraph() r = p.add_run() r.add_picture('/tmp/foo.jpg') But if I have the image as a StringIO object. How can I do it without saving it as a file? P:S: Library I'm using is python-docx
has comment: http://stackoverflow.com/comment/92139043
has title: Python-docx: How to add StringIO image to a docx file?
type: Question
has answer: http://stackoverflow.com/a/52602365
has comment: http://stackoverflow.com/comment/92138789
score: 0
has comment: http://stackoverflow.com/comment/92138984
answer count: 1

http://stackoverflow.com/a/52682825
accepted answer of: http://stackoverflow.com/q/52682600
has body: You should use driver.find_element_by_xpath instead of driver.find_elements_by_xpath driver.find_element_by_xpath returns single webelement so you can perform the action like click or sendkeys driver.find_elements_by_xpath returns list of webelement So you need to iterate the list to extract the webelement one by one
answers question: http://stackoverflow.com/q/52682600
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92294133
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/92407687
comment on: http://stackoverflow.com/a/52741120
type: Comment
has text: Thank you! That worked! So basically if it gives that and you know the files are OK, it is because Python isn't recognising what type of file they are?
score: 0
type: AnswerComment

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/52650611
tags question: http://stackoverflow.com/q/52633391
tags question: http://stackoverflow.com/q/52644626
tags question: http://stackoverflow.com/q/52668140
tags question: http://stackoverflow.com/q/52598998
tags question: http://stackoverflow.com/q/52717486
tags question: http://stackoverflow.com/q/52666308
tags question: http://stackoverflow.com/q/52704023
tags question: http://stackoverflow.com/q/52637309
tag name: kivy-language

http://stackoverflow.com/q/52590363
possible better answer: http://stackoverflow.com/a/52590721
tagged with: python
has answer: http://stackoverflow.com/a/52590721
type: AnsweredQuestion
tagged with: subprocess
downvote count: 0
score: 1
type: Question
has title: Python subprocess to execute remote server commands
tagged with: python-2.7
tagged with: bash
answer count: 2
upvote count: 1
tagged with: shell
has body: I have to execute python script that reside in remote machine and I am using below script: from subprocess import call ip = 1.1.1.1 call(["ssh", ip, "\"cd scripts; python -u get_details.py --web_server\""]) getting below error: bash: cd scripts; python -u get_details.py --web_server: command not found running in bash command line directly : ssh 1.1.1.1 "cd scripts; python -u get_details.py --web_server" Asking below input and returning output 1. USA 2. UK Choose input: 1 www.cisco_us.com is up Please let me how fix or any other better way to achive this in python
has answer: http://stackoverflow.com/a/52590679
accepted answer: http://stackoverflow.com/a/52590679
favorite count: 0

http://stackoverflow.com/a/52678730
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52678589
has body: You can add a List contain the same elements as L and count them using count try this : L = [] e = [] for x in range(0, 10): L.append([]) for y in range(0, 3): a = random.randint(0, 45) + 1 L[x].append(a) e.append(a) for z in e : print (z,e.count(z))

http://stackoverflow.com/a/52785785
upvote count: 1
answers question: http://stackoverflow.com/q/52630920
score: -1
has comment: http://stackoverflow.com/comment/107155099
type: Answer
has body: Found the issue. The requirement.txt file was place in the wrong directory causing Django not to install.
downvote count: 2

hostapd
tag name: hostapd
tags question: http://stackoverflow.com/q/52629543
type: Tag

http://stackoverflow.com/q/52691926
has comment: http://stackoverflow.com/comment/92311867
score: 0
has body: Please help! I want to open several webdrivers and for each do different actions, for example for first opened webdriver do login, for second registration etc. I try to use Pool library, but it doesn't work correctly, it opens webdrivers not paraller. from multiprocessing import Pool from selenium import webdriver from selenium.webdriver.chrome.options import Options class C: def log(self, url): print("1") chrome_options = Options() chrome_options.add_argument("--start-maximized") driver = webdriver.Chrome("C:/Users/path") driver.get(url) def reg(self, url): print("2") chrome_options = Options() chrome_options.add_argument("--start-maximized") driver = webdriver.Chrome("C:/Users/path") driver.get(url) def f(self, *name): return name def run(self): pool = Pool(processes=2) pool.map(self.f, (self.log("someurl?form=sign_in"), self.reg("someurl?form=sign_up"))) if __name__ == '__main__': c = C() c.run()
tagged with: pool
has comment: http://stackoverflow.com/comment/92311409
accepted answer: http://stackoverflow.com/a/66228106
tagged with: ui-testing
answer count: 1
has comment: http://stackoverflow.com/comment/92311659
has title: How can I open async several selenium webdriver using python
has comment: http://stackoverflow.com/comment/92311641
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66228106
has comment: http://stackoverflow.com/comment/92311745
tagged with: selenium
type: Question

http://stackoverflow.com/q/52633376
tagged with: pandas
has body: I have an excel file that contains 1000+ company names in one column and about 20,000 company names in another column. The goal is to match as many names as possible. The problem is that the names in column one (1000+) are poorly formatted, meaning that "Company Name" string can look something like "9Com(panynAm9e00". I'm trying to figure out the best way to solve this. (only 12 names match exactly) After trying different methods, I've ended up with attempting to match 4-5 or more characters in each name, depending on the length of each string, using regex. But I'm just struggling to find the most efficient way to do this. For instance: Column 1 1. 9Com(panynAm9e00 2. NikE4 3. Mitrosof2 Column 2 1. Microsoft 2. Company Name 3. Nike Take first element in Column 1 and look for a match in Column 2. If no exact match, then look for a string with 4-5 same characters. Any suggestions?
has answer: http://stackoverflow.com/a/52633504
score: 1
favorite count: 0
type: Question
answer count: 2
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/31806695
downvote count: 0
type: UnansweredQuestion
has title: Match similar column elements using pandas and fuzzwuzzy
tagged with: fuzzywuzzy
has answer: http://stackoverflow.com/a/52633498

http://stackoverflow.com/q/52607375
has body: I am merging multiple dataframes, which have the same columns. I am using concat since it is more efficient than append apparently. The dataframes have indexes from 0 to n-1, that is why I put ignore_index to True so that the combined dataframe will have indexes from 0 to n-1. df=pd.concat(dfs,ignore_index=True) dfs is a python list of multiple dataframes. I get this warning. C:/Users/XXX/Documents/XX/XXX/test/football.py:512: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version of pandas will change to not sort by default. To accept the future behavior, pass 'sort=False'. To retain the current behavior and silence the warning, pass 'sort=True'. df=pd.concat(dfs,ignore_index=True) I am not sure what exactly it means. The dataframes have different amount of rows, but the columns should be the same. non-concatenation axis is not aligned Is these saying that the columns are not same in all of the dataframes? If so what does sort do?
answer count: 0
tagged with: sorting
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/50501787
type: Question
tagged with: pandas
has title: Pandas dataframe concat non-concatenation axis are not aligned
has comment: http://stackoverflow.com/comment/92149094
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/92154545
linked to: http://stackoverflow.com/q/50501787
tagged with: concatenation

http://stackoverflow.com/a/52677783
downvote count: 0
answers question: http://stackoverflow.com/q/52662203
has body: Try something along self.set_service("554") in your GstServer class. Note that you will need to run this with elevated privileges as the port is &lt; 1024 and also the reason why it defaults to 8554.
has comment: http://stackoverflow.com/comment/92300766
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52662203
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/92127583
type: Comment
type: QuestionComment
has text: pd.concat(dataframes, ignore_index = True, axis = 1)
comment on: http://stackoverflow.com/q/52596332
score: 0

http://stackoverflow.com/comment/92204378
comment on: http://stackoverflow.com/a/52635417
type: AnswerComment
has text: If you want both of them to be in the list, you just need to replace `any` with `all`.
type: Comment
score: 1

nested
tags question: http://stackoverflow.com/q/52710734
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/52619696
tags question: http://stackoverflow.com/q/52708730
tags question: http://stackoverflow.com/q/52635793
tags question: http://stackoverflow.com/q/52682419
tags question: http://stackoverflow.com/q/52606753
tags question: http://stackoverflow.com/q/52675678
tags question: http://stackoverflow.com/q/52654882
tags question: http://stackoverflow.com/q/52729503
tags question: http://stackoverflow.com/q/52624019
tags question: http://stackoverflow.com/q/52706958
tags question: http://stackoverflow.com/q/52711467
tags question: http://stackoverflow.com/q/52694555
tags question: http://stackoverflow.com/q/52695227
tags question: http://stackoverflow.com/q/52664136

http://stackoverflow.com/q/52686268
upvote count: 2
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: Multiprocessing pool in python spitting out bus 10 error
type: Question
has body: I'm working on a Google Image Crawler. I've got page sources, and extracted the parts where href is embedded. The source codes are as below: links = soup.find_all("a", class_="rg_l") try: pool = Pool(8) pool.map(web_crawl.download_image, links) finally: pool.close() pool.join() My attempt was to pass each element of the links(which is list) to download_image function and request for the image by http protocol. But it keeps spitting out a Bus 10 error. Any advice would be appreciated. (I've checked that pool.map() is causing this error) download_image function looks like this: def download_image(link): ua = UserAgent() headers = {"User-Agent": ua.random} # Get the image link try: r = requests.get("https://www.google.com" + link.get("href"), headers=headers) except: print("Cannot get link.") title = str(fromstring(r.content).findtext(".//title")) links = title.split(" ")[-1] # Download the image print("At : " + os.getcwd() + ", Downloading from " + links) try: if links.split(".")[-1] == ('jpg' or 'png' or 'jpeg'): urllib.request.urlretrieve(links, links.split("/")[-1]) except: pass
downvote count: 0
has comment: http://stackoverflow.com/comment/92300080
tagged with: pool
score: 2
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/92300047

http://stackoverflow.com/comment/92415746
comment on: http://stackoverflow.com/q/52744713
score: 0
type: Comment
type: QuestionComment
has text: I'm not getting any errors when I run this... can you show the full command you use to run the file? What version of python & mypy are you using?

http://stackoverflow.com/q/52691569
tagged with: tensorflow
type: Question
score: 5
has answer: http://stackoverflow.com/a/55140535
upvote count: 5
downvote count: 0
tagged with: keras
answer count: 1
favorite count: 0
has title: keras model.fit() fed with initializable iterator of tf.Dataset object
type: UnansweredQuestion
tagged with: python
has body: I am using the tf.keras API to build my CNN model with the use of the tf.Dataset API to create a input pipeline for my model. The mnist dataset from the tf.keras.datasets is used for testing and prepared in the memory by executing the code: (train_images,train_labels),(test_images,test_labels) = tf.keras.datasets.mnist.load_data() and also some preprocessing to be compatible with my keras model: Train_images = np.expand_dims(train_images,3).astype('float')/255.0 Test_images = np.expand_dims(test_images,3).astype('float')/255.0 Train_labels = tf.keras.utils.to_categorical(train_labels) Test_labels = tf.keras.utils.to_categorical(test_labels) Those data are stored in the memory as arrays and there are two option for creating a Dataset object. The first one is simply using tf.data.Dataset.from_tensor_slices: image = tf.data.Dataset.from_tensor_slices((Train_images,Train_labels)) And input this resulting object to the model.fit(): model.fit(x=image,steps_per_epoch=1000) OR input this dataset's iterator by: iterator = image.make_one_shot_iterator() model.fit(x=iterator,steps_per_epoch=1000) Both of these two options just work fine since the dataset named image here is created using the data in the memory. However, according the the Importing Data here that we may like to avoid doing this because it copies data several times and takes up memory. So another option is creating such a dataset object based on tf.placeholder as well as the initialiable iterator: X = tf.placeholder(tf.float32,shape = [60000,28,28,1]) Y = tf.placeholder(tf.float32,shape = [60000,10]) image2 = tf.data.Dataset.from_tensor_slices((X,Y)) iterator2 = image.make_initializable_iterator() with tf.Session() as sess: sess.run(iterator2.initializer,feed_dict={X:Train_images,Y:Train_labels} sess.run(iterator2.get_next()) This kind of iterator works fine when using tf.Session() when fed with the data in the memory and avoids the multiple copies of the data. But I cannot find way to let it work with keras.mod…

http://stackoverflow.com/a/52729823
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52729806
answers question: http://stackoverflow.com/q/52729806
type: Answer
downvote count: 0
has body: Use this list comprehension: mytuple_with_3 = [i for i in mytuple if 3 in i] &gt;&gt;&gt; mytuple_with_3 [(1, 3), (3, 8)] To limit it to only the first 2 elements, use: mytuple_with_3 = [i for i in mytuple if 3 in i[:2]]

http://stackoverflow.com/a/52620963
score: 9
has comment: http://stackoverflow.com/comment/92178614
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92176093
upvote count: 9
has comment: http://stackoverflow.com/comment/92175877
has comment: http://stackoverflow.com/comment/92177173
type: Answer
has comment: http://stackoverflow.com/comment/92178298
has body: There are many methods! Method #1: You have to get the whole object to update it Try this: query = session.query(Table).first() query.column_one = value # setattr(query, column_one, value) session.commit() Method #2: Using SQLAlchemy Core API from sqlalchemy import update stmt = update(Table).where(Table.c.id==5).values(id=1) More information about this method on this link There are other methods, mentioned by Ilja Everilä in the comments , So the credit goes to him, upvote his comment! Method #3: load_only() method, It can get used like this: from sqlalchemy.orm import load_only query = session.query(Table).options(load_only("column_one", "column_two")) query.column_one = Value session.commit() More information about load_only() method on this link Method #4: Query.update() session.query(Table).filter(Table.column_one == 25).update({Table.column_one: 10}, synchronize_session=False) session.commit() More information about Query.update() here!
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52619891
answers question: http://stackoverflow.com/q/52619891
has comment: http://stackoverflow.com/comment/92181633
has comment: http://stackoverflow.com/comment/92176783
has comment: http://stackoverflow.com/comment/92176231

http://stackoverflow.com/a/52614273
downvote count: 1
answers question: http://stackoverflow.com/q/52614223
type: Answer
has body: I think changing 2*i-1 to 2*i+1. That's a simple question.
has comment: http://stackoverflow.com/comment/92163026
score: 0
upvote count: 1

http://stackoverflow.com/comment/92414608
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52744950
score: 1
has text: Either use `Base1.__init__(self)` and `Base2.__init__('hello world')`, **or** have your base classes use `super().__init__()`, where you make sure to call the next class in the chain cooperatively and take into account that `object.__init__()` does not take any arguments.

http://stackoverflow.com/q/52657648
has answer: http://stackoverflow.com/a/52657737
tagged with: list
accepted answer: http://stackoverflow.com/a/52657791
type: Question
answer count: 2
has title: I'm trying to generate a list of random numbers in a string that's based on user input in python
score: 0
has answer: http://stackoverflow.com/a/52657791
has body: I'm trying to make a simple dice rolling program for DnD, and I'm trying to make it so that you can roll any amount of dice and it shows you a list of the rolls. I'm still a little rusty at python, and I'm running into difficulty. Here's what I have (note: this is for a 4 sided dice): List = [] def Dice(): List = List + [random.randint(1, 4)] return List while multiplier &gt; 0: Dice() multiplier = multiplier - 1 #multiplier is how many times you rolled the dice print(Dice()) Whenever it runs, I get this error message: Traceback (most recent call last): File "C:/Users/Un-Local User/Desktop/Python/Dice Sim.py", line 68, in &lt;module&gt; Dice() File "C:/Users/Un-Local User/Desktop/Python/Dice Sim.py", line 5, in Dice List = List + [random.randint(1, 4)] UnboundLocalError: local variable 'List' referenced before assignment
tagged with: python
possible better answer: http://stackoverflow.com/a/52657737
has comment: http://stackoverflow.com/comment/92246029
has comment: http://stackoverflow.com/comment/92246051
type: AnsweredQuestion

http://stackoverflow.com/q/52690994
has comment: http://stackoverflow.com/comment/92309193
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52691477
accepted answer: http://stackoverflow.com/a/52691477
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52691723
upvote count: 3
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/92309200
type: Question
score: 3
tagged with: export-to-csv
has body: I am trying to write data from a website. The data is listed as a table in HTML with the tags '' listing when a new block of data is listed in the rankings and '' for each descriptive item about the element in the ranking. The list is a rank of top 500 computers, listed 1-100 with each 1, 2, 3, 4, etc. item listed by '' and the each characteristic of the computer listed as '' (it's storage, max power, etc). Here is my code: # read the data from a URL url = requests.get("https://www.top500.org/list/2018/06/") url.status_code url.content # parse the URL using Beauriful Soup soup = BeautifulSoup(url.content, 'html.parser') filename = "computerRank10.csv" f = open(filename,"w") headers = "Rank, Site, System, Cores, RMax, RPeak, Power\n" f.write(headers) for record in soup.findAll('tr'): # start building the record with an empty string tbltxt = "" tbltxt = tbltxt + data.text + ";" tbltxt = tbltxt.replace('\n', ' ') tbltxt = tbltxt.replace(',', '') # f.write(tbltxt[0:-1] + '\n') f.write(tbltxt + '\n') f.close() I'm getting nothing and my CSV file is always blank
answer count: 2
possible better answer: http://stackoverflow.com/a/52691723
downvote count: 0
has title: Web Scraping - Python; Writing to a CSV

http://stackoverflow.com/q/52601981
score: 4
has body: For example, if I want to list out all the stocks on NASAQ and their closing price, is there a way to do this without using the API for each individual stock? What I mean is, you pull data for a company using the company's ticker symbol in the API url. If there are 3000 companies on the NASDAQ, can I get all their closing prices without calling the URL 3000 times?
has title: Alpha Vantage - Can you pull for multiple stocks with the API?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/55599442
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/63869249
tagged with: alpha-vantage
type: Question
upvote count: 4
answer count: 2

http://stackoverflow.com/comment/92301692
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52687155
score: 0
has text: Can you please clarify what the code looked like when it worked, and which changes you made that broke it?

http://stackoverflow.com/a/52617701
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/52617670
downvote count: 0
score: 6
has body: The reason this isn't as straightforward as one might think is that tuples are immutable. An easy way would be to convert to list, use remove to remove the first instance, and convert back to tuple: t = (7, 5, 3, 3, 6, 3, 9) t2 = list(t) t2.remove(3) tuple(t2) # (7, 5, 3, 6, 3, 9) As a Function: def takeOut(k, r): k2 = list(k) k2.remove(r) return tuple(k2) takeOut((7, 5, 3, 3, 6, 3, 9), 3) # (7, 5, 3, 6, 3, 9)
has comment: http://stackoverflow.com/comment/92169580
has comment: http://stackoverflow.com/comment/92170071

http://stackoverflow.com/q/52690303
type: Question
has comment: http://stackoverflow.com/comment/92332715
has body: I was trying to use tf.dynamic_partition() to replace tf.gather() in order to aviod converting sparse representation into dense matrix implicitly. Here is my code, # edge_source_states = tf.gather(params=node_states_per_layer[-1], indices=edge_sources) partitions0 = tf.reduce_sum(tf.one_hot(edge_sources, tf.shape(node_states_per_layer[-1])[0], dtype='int32'), 0) edge_source_states = tf.dynamic_partition(node_states_per_layer[-1], partitions0, 2) edge_source_states = edge_source_states[1] The annotation is the orignal use of tf.gather(). There was no mistake when using tf.gather(), the only problem is that it converts sparse representation into dense matrix and thus consumes a lot of memory. However, when I use tf.dynamic_partition() method instead, I got an error: InvalidArgumentError (see above for traceback): partitions[21] = 2 is not in [0, 2) And according to the traceback, this error is caused by the sentence: edge_source_states = tf.dynamic_partition(node_states_per_layer[-1], partitions0, 2) As a novice, I really can't figure it out. My problems are: 1) I thought my new codes using tf.dynamic_partition() is functionally equivalent to the original code using tf.gather(). So why there is an error? 2) Is tf.dynamic_partition() a solution for avoiding the implicit conversion from sparse to dense as tf.gather() does? Are there any other solutions? I really need to control the memory consumption strictly.
tagged with: neural-network
has comment: http://stackoverflow.com/comment/92327446
upvote count: 2
favorite count: 0
type: UnansweredQuestion
has title: How to solve InvalidArgumentError for dynamic_partition in tensorflow?
tagged with: python
score: 2
downvote count: 0
answer count: 0
tagged with: machine-learning
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/92327676

http://stackoverflow.com/a/67422358
answers question: http://stackoverflow.com/q/52661025
score: 1
downvote count: 0
has body: Hopefully this will help someone. cv.findContours method does not find any contours if the image is a black image. Therefore check the image through imshow, bigSharpened.copy() in this case cv.imshow("Image", bigSharpened.copy())
upvote count: 1
type: Answer

http://stackoverflow.com/comment/92130203
has text: What have you tried, and what exactly is the problem with it?
type: QuestionComment
comment on: http://stackoverflow.com/q/52597760
score: 4
type: Comment

http://stackoverflow.com/a/52622064
answers question: http://stackoverflow.com/q/52619030
score: 0
type: Answer
has body: The simplest way is probably to use a Counter from the Python standard library. from collections import Counter tally = Counter() scores = [1, 2, 3, 4, 5] def add_scores(letters): for letter, score in zip(letters, scores): tally[letter] += score L1 = ['a', 'b', 'c', 'd', 'e'] add_scores(L1) L2 = ['c', 'a', 'd', 'e', 'b'] add_scores(L2) print(tally) &gt;&gt;&gt; python tally.py Counter({'e': 9, 'b': 7, 'd': 7, 'c': 4, 'a': 3}) zip is used to pair letters and scores, a for loop to iterate over them and a Counter to collect the results. A Counter is actually a dictionary, so you can write things like tally['a'] to get the score for letter a or for letter, score in tally.items(): print('Letter %s scored %s' % (letter, score)) to print the results, just as you would with a normal dictionary. Finally, small ells and letter O's can be troublesome as variable names because they are hard to distinguish from ones and zeros. The Python style guide (often referred to as PEP8) recommends avoiding them.

http://stackoverflow.com/comment/92317203
type: QuestionComment
has text: ahh sorry, I now understand. I'll make that edit. But even correcting it the thing is I'm not getting an error, whenever I call the program in PyCharm's terminal there is no output and it just prompts me again.
score: 0
comment on: http://stackoverflow.com/q/52694033
type: Comment

http://stackoverflow.com/q/52633989
type: Question
has comment: http://stackoverflow.com/comment/92201365
accepted answer: http://stackoverflow.com/a/52634066
has body: function in python 3.7 that print any word and slicing+making new line as explained in the next line: The function name('yesterday') printing: y ye yes yest yeste yester yesterd yesterda yesterday (every part in new line) this was what I tried to do: def yesterday(): str ="y\s ye\s" str.split("\s") ['y', 'ye', 'yes'] print()
answer count: 1
score: -6
favorite count: 0
has answer: http://stackoverflow.com/a/52634066
has comment: http://stackoverflow.com/comment/92201266
upvote count: 1
tagged with: python
downvote count: 7
has title: Python 3.7 new line and slicing
type: AnsweredQuestion

http://stackoverflow.com/q/52705108
tagged with: python-import
answer count: 1
downvote count: 1
has title: Simple use of "import as" to load multi-scenario data?
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I receive scenario data (identical sets of variables with different values by scenario) in the form of python modules. Example: scen00.py: scenario_name = ["foo"] scenario_num = [0] . . scen01.py: scenario_name = ["bar"] scenario_num = [1] . . I import each scenario to a separate incidence of a python function using import as, and then do all of the programming, referencing the base namespace. Example: import sys def main(): script = sys.argv[0] no_scens = int(sys.argv[1]) for i in range(0, no_scens): process_1(i) def process_1(scen_count): if scen_count == 0: import scen00 elif scen_count == 1: import scen01 as scen00 print(scen00.scenario_name[0], scen00.scenario_num[0]) Expected Outcome: foo 0 bar 1 While this code works when no_scens is 2, the segment in process_1() which assigns the different scenarios to scen00 is not scalable and inelegant. Assuming I now have 150 scenarios to import, how could I best modify process_1()?
tagged with: variable-assignment
tagged with: python
has comment: http://stackoverflow.com/comment/92338923
score: 1
has comment: http://stackoverflow.com/comment/92337623
linked to: http://stackoverflow.com/q/301134
type: Question
has answer: http://stackoverflow.com/a/52705246
duplicate of: http://stackoverflow.com/q/301134
has comment: http://stackoverflow.com/comment/92342175
upvote count: 2

http://stackoverflow.com/a/52741467
answers question: http://stackoverflow.com/q/52734267
score: 0
type: Answer
has body: I had the same issue that you, in my case i solved adding this header: self.set_header("Access-Control-Allow-Credentials", "true") self.set_header("Access-Control-Allow-Headers", "Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, Cache-Control") I hope have help you.

http://stackoverflow.com/comment/115632261
type: AnswerComment
has text: you can easily run into a race condition with different processes if you use two open statements like this
type: Comment
comment on: http://stackoverflow.com/a/52607429
score: 0

http://stackoverflow.com/q/52733864
score: 2
answer count: 0
has title: Unable to run coverage tool using embedded python using the -m option or when copied to different path locations in windows
type: Question
tagged with: embedded
downvote count: 0
has body: I am trying to run the python coverage tool using embedded python downloaded from https://www.python.org/ftp/python/3.6.1/python-3.6.1-embed-amd64.zip The following are the steps I followed to run a test code using coverage module. 1) After downloading python-3.6.1-embed-amd64.zip, I uncompress the files to D:\some_directory\python-3.6.1-embed-amd64 2) cd python-3.6.1-embed-amd64 3) python get-pip.py 4) python -mpip install coverage 5) python-3.6.1-embed-amd64\python36._pth is changed to python36.zip Lib\site-packages . # Uncomment to run site.main() automatically #import site 6) In case if there is an internet proxy to used then use the following command SET HTTP_PROXY=http://username:password@proxy_ip:proxy_port 7) python -mpip install coverage Create test files as follows The file module_prog.py is as follows # -*- coding: utf-8 -*- """ Dummy method for testing """ def method_to_tested() -&gt; None: """ Method To be tested """ print("Called method to be tested") The file test_module.py is as follows """ Unit test script for testing File : test_module.py """ import unittest from module_prog import method_to_tested class TestMethods(unittest.TestCase): """ Testing the methods """ def test_method_to_tested(self): method_to_tested() if __name__ == "__main__": unittest.main(warnings='ignore') 8) I run the following D:\some_directory\python-3.6.1-embed-amd64&gt;python test_module.py Called method to be tested . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK 9) But if I run the instruction as mentioned below using converage I get the following error. D:\some_directory\python-3.6.1-embed-amd64&gt;python -mcoverage run test_module.py Traceback (most recent call last): File "test_module.py", line 4, in &lt;module&gt; import unittest ModuleNotFoundError: No module named 'unittest' If I run the command Scripts\converage.exe run test_module.py Then coverage run successfully, But if I move the embedded python to another directory…
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: code-coverage
type: UnansweredQuestion
tagged with: python
tagged with: module

http://stackoverflow.com/q/52663358
type: Question
upvote count: 4
score: 4
has body: I am new in deep learning area. Now I am reproducing a paper’s codes. since they use several GPUs, there is a command torch.nn.DataParallel(model, device_ids= args.gpus).cuda() in codes. But I only have one GPU, what should I change this code to match up my GPU? Thank you!
has title: Problems about torch.nn.DataParallel
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pytorch
has answer: http://stackoverflow.com/a/52664209

http://stackoverflow.com/comment/92300640
score: 0
type: AnswerComment
has text: Be aware this is only working because it's being done in the shell, if you're not working in a shell you need to assign the copy that `replace` produces to another variable, or `a` will not change. (for example `a_new = a.replace("a=", "")`
type: Comment
comment on: http://stackoverflow.com/a/52685840

http://stackoverflow.com/comment/92468145
type: AnswerComment
score: 0
has text: Got it . One more thing, Why I have given a mutable default list because , I need the function to display the argument type as list where ever it is calling. In Java , we need to mention the data type as list for the function parameter, so where ever you call it , it will display the argument type to be passed as 'list'. How we can achieve the same here?
type: Comment
comment on: http://stackoverflow.com/a/52747535

http://stackoverflow.com/q/52689747
tagged with: memory
has body: I want to view the string representation of memory element of the following code: https://github.com/odoo/odoo/blob/11.0/addons/website_sale/controllers/main.py#L233 When i print "keep", it gives "odoo.addons.website.controllers.main.QueryURL object at 0xb1438fac". How actually i can convert it into string OR human readable format? The original code of QueryURL class is in below link: https://github.com/odoo/odoo/blob/11.0/addons/website_sale/controllers/main.py#L233
score: 0
answer count: 2
tagged with: string
has answer: http://stackoverflow.com/a/52689934
tagged with: python
type: UnansweredQuestion
has title: How to convert memory element to string in python?
type: Question
has answer: http://stackoverflow.com/a/52689824
tagged with: call
tagged with: odoo

http://stackoverflow.com/q/52636566
duplicate of: http://stackoverflow.com/q/182197
has answer: http://stackoverflow.com/a/52636653
has title: Read file from folder which is being written python
tagged with: read-write
answer count: 1
has comment: http://stackoverflow.com/comment/92206376
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/92206254
has comment: http://stackoverflow.com/comment/92206554
has body: I have a folder which is being written continuously with files (from a Raspberry Pi). I want to run a Python code which will read files (and process them) from the same folder. I start the Python code after say 5 files have been written into the folder. But then the code stops after it has processed 5 files. Any suggestions as to how to "stream" the files from this dynamically updated folder into my Python code? Thanks I am using the following code and was wondering if there is another solution: import os import time import numpy as np from PIL import Image import datetime # get the data &amp; time of an image output is str with format '%Y:%m:%d %H:%M:%S' def get_date_taken(path): return Image.open(path)._getexif()[36867] # get the difference in time between two images in seconds def getTimeDiffBetwImages(path1,path2): a1 = get_date_taken(path1) a2 = get_date_taken(path2) b1 = datetime.datetime.strptime(a1,'%Y:%m:%d %H:%M:%S') b2 = datetime.datetime.strptime(a2,'%Y:%m:%d %H:%M:%S') return (b1-b2).total_seconds() def getDiffImgs(img1,img2): a = img1.shape diff = np.zeros((a[0],a[1],a[2]),dtype = "uint8") for i in range(0,a[0]): for j in range(0,a[1]): for k in range(0,a[2]): diff[i,j,k] = abs(int(img2[i,j,k]) - int(img1[i,j,k])) return diff folder = "D:/work" file_num = 0 img_prev = [] last_file = None while True: for f in os.listdir(folder): path1 = os.path.join(folder,f) if not(last_file == None): path2 = os.path.join(folder,last_file) time_diff = getTimeDiffBetwImages(path1,path2) else: time_diff = 0 if time_diff &gt;= 0: print(f) im = cv2.imread(os.path.join(folder,f)) img_curr = np.copy(im) fname = "Diff_" + f if file_num &gt; 0: diff = getDiffImgs(img_prev,img_curr) cv2.imwrite(fname,diff) img_prev = np.copy(img_curr) file_num += 1 time.sleep(10) # additional processing but just delay out here last_file = f
type: Question
linked to: http://stackoverflow.com/q/182197
upvote count: 0
score: -2

http://stackoverflow.com/a/52593386
answers question: http://stackoverflow.com/q/52593109
has body: Using Javascript, you can do it simply using split() that divide your string when matching double points : var text = "1234567890:12312312:Lorem ipsum dolor sit amet"; var splitted = text.split(":"); console.log("id : " + splitted[1]); console.log("Title : " + splitted[2]); Using pure regex, you can do it with this one : ([0-9]{10,})[:]([0-9]{8})[:]([a-zA-Z ]+) Group 1 : 1234567890 Group 2 (ID) : 12312312 Group 3 (Title) : Lorem ipsum dolor sit amet The first group will detect 10 numbers from 0 to 9. The second group will detect 8 numbers from 0 to 9. The third group will detect a to Z and spaces. Working example : https://regex101.com/r/3TudrD/1
type: Answer
score: 0

http://stackoverflow.com/q/52636797
has answer: http://stackoverflow.com/a/58279652
upvote count: 3
has comment: http://stackoverflow.com/comment/92207188
answer count: 1
has title: Read hex or decimal from serial in Ignition
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/100213470
has body: I have a serial device that returns 23 hex values. I read the values using system.serial.readBytes('COM1', 23) in Ignition. This returns array('b', [-85, 112, 1, 18, -79, 0, 1, 116, -41, 2, -17, 10, 28, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0]). I know the values here are decimal from signed 2's complement, but how can I get the decimal value? For example -85 should be 171, or 0xAB in hex. I would prefer to directly read the hex values, but I don’t know how to do this. Any idea?
tagged with: ignition
tagged with: decimal
score: 3
downvote count: 0
favorite count: 0
tagged with: hex
type: Question
tagged with: serial-port
tagged with: python

http://stackoverflow.com/comment/92322281
comment on: http://stackoverflow.com/q/52697834
score: 0
type: Comment
type: QuestionComment
has text: I'm already using `continue` I need to skip 2 lines.

http://stackoverflow.com/comment/92371771
comment on: http://stackoverflow.com/q/52642700
score: 0
has text: How does it error out? With a catchable error? Or does it hang?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92394380
has text: Sorry I didn't get it. Could you please explain? And this is a sample program that I showed here. The actual shell script might contain several lines of code
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52734365

http://stackoverflow.com/a/52661472
type: Answer
answers question: http://stackoverflow.com/q/52661069
downvote count: 0
score: 1
has body: All other answers will insert a . in front of every character in the string, but you specified that you want letters only. So I am assuming that you only want a-z to be prepended with a . for which I suggest re.sub: import re s = "This is some test string. It contains some symbols also ()!!" result = re.sub('[aeoui]', '', s.lower()) # remove vowels and make lowercase result = re.sub("([a-z])", r".\1", result) # prepend '.' to every letter print(result) Outputs: .t.h.s .s .s.m .t.s.t .s.t.r.n.g. .t .c.n.t.n.s .s.m .s.y.m.b.l.s .l.s ()!!
upvote count: 1

http://stackoverflow.com/q/52665479
has body: I am not able to access template variables passed from views.py file in django. I coudldn't find any answer on stackoverflow yet. I have tried everything like converting the variable to json object and parsing it in the separate js file. How to access the template variable from views.py in a separate .js file ? Please help.
tagged with: django
has comment: http://stackoverflow.com/comment/92260738
tagged with: python
tagged with: django-templates
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/92260837
tagged with: javascript
has comment: http://stackoverflow.com/comment/92260706
has title: How to use access django template variable in a separate js file rather than inlcuding small script block in same html file?
has answer: http://stackoverflow.com/a/52665671
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92260735
type: UnansweredQuestion

http://stackoverflow.com/q/52618058
downvote count: 0
tagged with: google-colaboratory
favorite count: 0
tagged with: animation
tagged with: python
type: UnansweredQuestion
has title: Is there a way in Colab to generate animation dynamically?
has answer: http://stackoverflow.com/a/57820048
type: Question
has answer: http://stackoverflow.com/a/53348639
score: 4
has body: I wrote a Langton's ant code and I wanted to have the animation run in Colab until it is stopped by user or after a certain number of frames. As it is right now, it first generates all the frames, then compiles them into animation and then displays it. If there are a lot of frames, it takes forever and/or Colab runs out of memory. That's why I was hoping there was a way to just generate it one frame at a time and continuously update the image. It doesn't seem like FuncAnimation has that capability, but maybe I'm just not seeing it. If anyone knows of a way or documentation that would be helpful, please let me know. import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc, colors from IPython.display import HTML N = 40 ant = np.array([N//2, N//2]) move = {'N': [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]} d = ['N', 'E', 'S', 'W'] facing = 1 board = np.zeros((N, N)) color = 0 board[ant[0]][ant[1]] = 4 cmap = colors.ListedColormap(['darkgreen', 'limegreen', 'greenyellow', 'yellow', 'red']) def turn(direction): if direction == 'R': return (facing + 1) % 4 else: return (facing - 1) % 4 def update(data): global ant, board, facing, color if color in [0, 1]: facing = turn('R') else: facing = turn('L') board[ant[0]][ant[1]] = (color + 1) % 4 ant += move[str(d[facing])] color = board[ant[0]][ant[1]] board[ant[0]][ant[1]] = 4 mat.set_data(board) return [mat] fig, ax = plt.subplots(figsize=(5, 5)); ax.grid(False) plt.axis('off') mat = ax.matshow(board, cmap=cmap) ani = animation.FuncAnimation(fig, update, frames = 150, interval = 1, repeat=False, blit=True) rc('animation', html='jshtml') ani
upvote count: 4
has answer: http://stackoverflow.com/a/53349692
answer count: 3

http://stackoverflow.com/comment/92392697
comment on: http://stackoverflow.com/q/52733653
type: Comment
type: QuestionComment
has text: `def unique(word): result = [] for f in word: if f not in result: result.append(f) return result` it seems that just works without set()
score: 0

http://stackoverflow.com/comment/92370925
type: QuestionComment
has text: So you have a `Start_date` and/or `End_Date`? What is the input, and what should be the output?
comment on: http://stackoverflow.com/q/52722840
score: 0
type: Comment

http://stackoverflow.com/q/52697741
accepted answer: http://stackoverflow.com/a/52697907
has comment: http://stackoverflow.com/comment/92321949
has answer: http://stackoverflow.com/a/52697886
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1952464
score: 1
has title: Python: count overall elements in list of lists
type: Question
downvote count: 0
possible better answer: http://stackoverflow.com/a/52697886
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52698193
tagged with: python
has body: I want to write a function that takes a list of numbers and lists, which again can contain numbers and lists, and so on..., and returns the overall amount of numbers that are somewhere in the list. Example: [1,[[[0,2],7,3],5,[1,2]],3] contains 9 numbers in it. This is my code so far: test=[1,[[[0,2],7,3],5,[1,2]],3] def flatten(mylist): counter = 0 for i in range(len(mylist)): if type(mylist[i]) == int: counter += 1 if type(mylist[i]) == list: [item for sublist in mylist[i] for item in sublist] counter += 1 return counter I think I need to recursivley flatten the sublists. But I get the error: TypeError: 'int' object is not iterable
favorite count: 0
has answer: http://stackoverflow.com/a/52697907

http://stackoverflow.com/comment/92284477
has text: @Antonino thanks for the reply. I've found a solution but I will check your suggestion out as well. Thank you
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52677479
score: 0

http://stackoverflow.com/q/52673444
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52673699
has title: Matplotlib rcParams not recognizing "Times New Roman" (mac High Sierra)
score: 4
has comment: http://stackoverflow.com/comment/92276775
tagged with: fonts
tagged with: matplotlib
type: Question
upvote count: 4
has body: I am trying to set the font of a matplotlib plot to Times New Roman. I have tried: import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'Times New Roman' I believe this is the correct way to set the font, but I keep getting this error that the found is not found: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/font_manager.py:1238: UserWarning: findfont: Font family ['Times New Roman'] not found. Falling back to DejaVu Sans. After some searching, I verified that I have the font downloaded. I tried opening a python shell and checking the contents of rcParams myself. Among a bunch of other font parameters, I curiously got a list of fonts in font.serif that contains Times New Roman. 'font.serif': ['DejaVu Serif', 'Bitstream Vera Serif', 'Computer Modern Roman', 'New Century Schoolbook', 'Century Schoolbook L', 'Utopia', 'ITC Bookman', 'Bookman', 'Nimbus Roman No9 L', 'Times New Roman', 'Times', 'Palatino', 'Charter', 'serif'], However, font.family only contained one item: sans-serif, when the matplotlib documentation states that there should be five values inside font.family. Has anybody run into this error before? How did you fix it?
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/92340858
score: 1
comment on: http://stackoverflow.com/q/52706997
has text: Don't see any list of emails or list of filenames.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92136744
score: 0
has text: I don't know if you'll find anyone here who knows about tfrecord. I'd submit this question as an issue on their github page
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52600836

http://stackoverflow.com/q/52741872
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52757193
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
has body: as I have mentioned in the topic I would like to save my tf.graph into a frozen_graph.pb file. This should save space later I will try to run it an a jetson tx2. I have made a short MNIST example describing my problem. I run tf 1.7 on python 3.5. Question1: As far as I understood my freeze_graph method takes a checkpoint file transfers all variables to constants except the ones i define with the second parameter. When I try to get the correct tensorname I wrote loggits.name but I get an error no Tensor with that name found in graph. Question2: After that I would be able to extract a frozen graph, how can i load it back and run an classification on that. My Code is attached and should work in a single py file. Thank you very much in advance import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data import os import time import tensorflow as tf import os import argparse #METHODS I WANT TO TEST #TAKE THE CHECKPOINT FILE AND DELETE ALL NOTES THAT ARE NOT USEFUL def freeze_graph(checkpoint_directory,output_node_names): #checkpoint = tf.train.get_checkpoint_state(checkpoint_directory) print(checkpoint_directory) checkpoint = tf.train.get_checkpoint_state(checkpoint_directory) input_checkpoint = checkpoint.model_checkpoint_path absolute_model_dir = str(os.sep).join(input_checkpoint.split(os.sep)[:-1]) output_graph = absolute_model_dir + "/frozen_model.pb" clear_devices = True with tf.Session(graph = tf.Graph()) as sess: #import the metagraph in default graph saver = tf.train.import_meta_graph(input_checkpoint + '.meta',clear_devices=clear_devices) #restore the weights saver.restore(sess,input_checkpoint) #wrap variables to constants [print(n.name) for n in tf.get_default_graph().as_graph_def().node] output_graph_def = tf.graph_util.convert_variables_to_constants(sess, tf.get_default_graph().as_graph_def(),output_node_names.split(",")) with tf.gfile.GFile(output_graph, "wb") as f: f.write(output_grap…
tagged with: tensorflow
type: Question
has title: Tensorflow save/load frozen tf.graph and run classification on loaded graph
upvote count: 1

http://stackoverflow.com/comment/92224346
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52644984
has text: `pandas` is an external lib. You need to install it first, `pip3 install pandas`
score: 0

http://stackoverflow.com/comment/92552515
type: Comment
comment on: http://stackoverflow.com/a/52704875
has text: Could you help me one more time? the line `appenddf=df.eq(100).sum(level=[0])` is giving me much trouble, because it only looks for 100, but not if it is 25 or anything else between 0-100. I tried for hours to fix this, but nothing I put in `df.eq(here)` works. Not even int. Is there any way that this code can accept other values than 100?
type: AnswerComment
score: 0

http://stackoverflow.com/q/52730340
has comment: http://stackoverflow.com/comment/92386989
favorite count: 0
tagged with: python-3.x
has body: I am trying to automate the clicking of "next" on my university's online lecture when the current slide ends as it requires the user to manually press "next" whenever the slide has ended. Using selenium with python, managed to get to webpage, login and navigate to the lecture slides itself but am unable to progress further HTML Element on pastebin trying to element on line 3397 I am trying to get the elapsedTime / totalTime and while ( currentSlide != totalSlide ) if elapsedTime == totalTime find and click on 'next' I've tried: duration = driver.find_element(By.XPATH,"//div[@class='label time'][@style='display: none;]") duration = driver.find_element(By.XPATH,"//div[@class='.label.time'][@style='display: none;']") Any help would be appreciated! EDIT: Got it working suggested by Lukas content = urllib.request.urlopen(URL, timeout=10).read().decode("utf-8") duration = content.split("&lt;div class="label time" style="display: none;"&gt;")[1].split("&lt;/div&gt;")[0]
possible better answer: http://stackoverflow.com/a/52730782
accepted answer: http://stackoverflow.com/a/52731293
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92386829
has comment: http://stackoverflow.com/comment/92386304
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92386750
score: -1
has comment: http://stackoverflow.com/comment/92386972
has title: Finding element with Selenium on Python
has comment: http://stackoverflow.com/comment/92388482
answer count: 2
has comment: http://stackoverflow.com/comment/92388467
has answer: http://stackoverflow.com/a/52730782
upvote count: 0
has comment: http://stackoverflow.com/comment/92386814
has comment: http://stackoverflow.com/comment/92386475
has answer: http://stackoverflow.com/a/52731293

http://stackoverflow.com/q/52700395
type: Question
tagged with: pyspark
has comment: http://stackoverflow.com/comment/92380514
score: 0
has body: XGBoost using eli5 for showing prediction prints results in HTML format, which is not working in pyspark in Databricks. And displayHTML(file_name) is giving error: Py4JException: An exception was raised by the Python Proxy. Return Message: x I have installed ipython library too. Even for this simple query its giving error. from IPython.display import display, HTML from IPython.core.display import display, HTML display(HTML(' Hello, world! ')) print("Here's a link:") display(HTML("www.google.com")) print("some more printed text ...") display(HTML(' Paragraph text here ... ')) The Output/Error which I'm getting is: <IPython.core.display.HTML at 0x7f63e0c5d5f8> Here's a link: <IPython.core.display.HTML at 0x7f6408fbe358> some more printed text ... <IPython.core.display.HTML at 0x7f6408fbe358>
has title: Databricks pyspark IPython.core.display.HTML error in eli5 output
tagged with: xgboost
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92409622
tagged with: databricks

http://stackoverflow.com/a/52633773
type: AcceptedAnswer
has body: The code you have is for an older Keras version, the latest Keras I checked (2.2.2) has the ReLU and DepthWiseConv2D already integrated inside keras.layers, so you only need to impor this to use MobileNet: import keras from keras.applications import MobileNet There is also MobileNetV2 in the same package for a newer version of MobileNet.
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52632612
accepted answer of: http://stackoverflow.com/q/52632612
score: 1
downvote count: 1

http://stackoverflow.com/comment/92418069
type: QuestionComment
has text: Not an exact duplicate, but closely related: [Is `argv[0]` = name-of-executable an accepted standard or just a common convention?](https://stackoverflow.com/questions/2050961/is-argv0-name-of-executable-an-accepted-standard-or-just-a-common-conventi)
score: 0
comment on: http://stackoverflow.com/q/52746418
type: Comment

http://stackoverflow.com/comment/92178712
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [add\_loss function in keras](https://stackoverflow.com/questions/50063613/add-loss-function-in-keras)
comment on: http://stackoverflow.com/q/52621995

http://stackoverflow.com/q/52670014
score: -1
has comment: http://stackoverflow.com/comment/92269925
has title: Problem when using if __name__ == "__main__": in Python
has body: I have a file called game.py that contains the following code: import other items = [] for _ in range(1, 15): a = other.myfunction() items.append(a) min = min(items) max = max(items) print(min) print(max) When I run this function from the terminal using python game.py, it works perfectly fine and I get the two values printed. However, when I modify the script by adding def main(): at the beginning and if __name__ == "__main__": main() at the end of the script and run it from the terminal using ./game.py, I get the following error: File "./game.py", line 8, in &lt;module&gt; min = min(items) ValueError: min() arg is an empty sequence Why wouldn't the SAME code run if I just added a function definition? I've never had this problem before... I'm pasting here my code using def main(): at the beginning and if __name__ == "__main__": main() at the end of the script: import other items = [] def main(): for _ in range(1, 15): a = other.myfunction() items.append(a) min = min(items) max = max(items) print(min) print(max) if __name__ == "__main__": main()
possible better answer: http://stackoverflow.com/a/52670125
has comment: http://stackoverflow.com/comment/92270111
accepted answer: http://stackoverflow.com/a/52670266
favorite count: 0
downvote count: 2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92270062
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92270067
has comment: http://stackoverflow.com/comment/92269967
type: Question
has answer: http://stackoverflow.com/a/52670266
has comment: http://stackoverflow.com/comment/92269953
answer count: 2
has answer: http://stackoverflow.com/a/52670125
has comment: http://stackoverflow.com/comment/92270000
has comment: http://stackoverflow.com/comment/92270337
has comment: http://stackoverflow.com/comment/92270090

http://stackoverflow.com/comment/92234547
comment on: http://stackoverflow.com/a/52638343
score: 0
type: Comment
has text: When trying that for only `t[0]`, the error persists. When I convert `t` to `t.any()`, I am instead receiving the error that: `File "<ipython-input-34-79d20e32a96d>", line 2 for i, l in enumerate(a1) for j, t.any() in enumerate(l or [[]])))) SyntaxError: can't assign to function call`. Perhaps I am misinterpreting your suggestions; would you be able to update your answer with the particular modification?
type: AnswerComment

http://stackoverflow.com/comment/92372266
has text: thank you. Suppose I have x,y,z,a,b,c..etc then do you have an idea how to handle this case?
type: Comment
comment on: http://stackoverflow.com/a/52690957
score: 0
type: AnswerComment

http://stackoverflow.com/q/52679322
has comment: http://stackoverflow.com/comment/92287882
has comment: http://stackoverflow.com/comment/92315445
has answer: http://stackoverflow.com/a/52694450
has comment: http://stackoverflow.com/comment/92315482
answer count: 1
downvote count: 0
favorite count: 0
has body: import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure(1) ax1 = fig.add_subplot(1,1,1) def animate(i): graph_data = open('example.txt','r').read() lines = graph_data.split('\n') xs = [] ys = [] for line in lines: if len(line) &gt; 1: x, y = line.split(',') xs.append(x) ys.append(y) ax1.clear() ax1.plot(xs, ys) ani = animation.FuncAnimation(fig, animate, interval=1000) plt.show() Is there another way to write the code such that y-axis is in ascending order? If so. where should I find it? This is from sentdex matplotlib tutorial
has comment: http://stackoverflow.com/comment/92315505
type: UnansweredQuestion
tagged with: animation
tagged with: python
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92315559
tagged with: matplotlib
has title: How do i make y-axis to be in an ascending order in matplotlib.animation? Sentdex tutorial

http://stackoverflow.com/q/52715430
has answer: http://stackoverflow.com/a/52715962
accepted answer: http://stackoverflow.com/a/52716081
has comment: http://stackoverflow.com/comment/92359617
linked to: http://stackoverflow.com/q/51959128
possible better answer: http://stackoverflow.com/a/52715962
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92359088
type: Question
has comment: http://stackoverflow.com/comment/92569221
has answer: http://stackoverflow.com/a/69674137
has title: How do I get geopandas to work on Windows 10 with WinPython?
has comment: http://stackoverflow.com/comment/92357322
has answer: http://stackoverflow.com/a/52716081
has body: I'm using WinPython with Python 3.6 on Windows 10 and through a long and winding course I managed to get geopandas installed and working properly on my system. This required manually installing various dependencies like GDAL, Fiona, and PyProj, but it eventually worked fine. A few days later (during which the computer was asleep) I'm trying to run the same code that worked fine and now I'm getting Could not find lib geos_c.dll or load any of its variants on the code import geopandas as gp when it gets to from shapely.geos import lgeos. I have confirmed that I DO have shapely installed (via pip) and I have geos_c.dll, but it's looking here C:\\WinPython\\python-3.6.5.amd64\\Library\\lib\\geos_c.dll' while the file is actually here: C:\\WinPython\\python-3.6.5.amd64\\Lib\\site-packages\\osgeo In fact, I don't even have a Library directory in my python folder. So I reinstalled Shapely, but this time using a whl file, and the error changed to module 'shapely' has no attribute 'affinity',when called by import geopandas. Running from shapely import affinity causes no error. I don't know why these packages are so hard to install or get working but I'd sure like to know .... How do I get geopandas to work on Windows 10 with WinPython? Or really, since it worked a few days ago, and nothing should have changed while the computer was sleeping, how to get it to work again like it used to?
score: 0
answer count: 3
tagged with: shapely
tagged with: geopandas
tagged with: windows
has comment: http://stackoverflow.com/comment/92357027
tagged with: python
has comment: http://stackoverflow.com/comment/92357080
tagged with: python-3.x

integrity
type: Tag
tag name: integrity
tags question: http://stackoverflow.com/q/52686848

http://stackoverflow.com/q/52728461
upvote count: 0
has answer: http://stackoverflow.com/a/52733209
answer count: 1
score: -2
favorite count: 0
has title: How to turn the numbers in the sequence generated by the collatz function into a string by using concatenation
type: UnansweredQuestion
downvote count: 2
tagged with: python
has body: The numbers in the sequence generated by the Collatz function will be put in a string. Building this string is likely the hardest part of this. Get the computation working without worrying about creating the string. Now, I'm sure I'm getting logically correct output, I need the help to create the string containing all the numbers, separated by a comma and space characters. enter image description here
tagged with: collatz
type: Question

http://stackoverflow.com/comment/92333993
type: QuestionComment
has text: X_train = np.reshape(X_train, X_train.shape + (1,)) X_test = np.reshape(X_test, X_test.shape + (1,))
comment on: http://stackoverflow.com/q/52625358
score: 0
type: Comment

http://stackoverflow.com/a/52682815
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52682423
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52682423
has body: You can use the pd.DataFrame constructor while specifying index and columns. The important point is to use MultiIndex columns: idx = pd.Index([f'step {i}' for i in range(1, 5)], name='time') cols = pd.MultiIndex.from_tuples([(i, j) for i in range(-2, 3) for j in ('one', 'two')]) df = pd.DataFrame(index=idx, columns=cols) You can then populate a value via pd.DataFrame.at for fast scalar setting by label: df.at['step 1', (-2, 'two')] = 2 df.at['step 3', (0, 'one')] = 5 print(df) -2 -1 0 1 2 one two one two one two one two one two time step 1 NaN 2 NaN NaN NaN NaN NaN NaN NaN NaN step 2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN step 3 NaN NaN NaN NaN 5 NaN NaN NaN NaN NaN step 4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

cmake
tags question: http://stackoverflow.com/q/52734200
type: Tag
tags question: http://stackoverflow.com/q/52649715
tags question: http://stackoverflow.com/q/52736687
tag name: cmake

http://stackoverflow.com/a/52651562
score: 3
has body: AbstractUser is for when you want to add additional fields to Django's defaults. Use AbstractBaseUser if you don't want all those fields.
answers question: http://stackoverflow.com/q/52651519
has comment: http://stackoverflow.com/comment/92236139
downvote count: 0
has comment: http://stackoverflow.com/comment/92235020
type: Answer
has comment: http://stackoverflow.com/comment/92235921
upvote count: 3

http://stackoverflow.com/comment/92461742
type: AnswerComment
type: Comment
has text: you also mentioned - datashader converts my 10k columns into 10k lines which gets converted into pixels. so, dark blue means 2 lines crossing over, light blue one line etc, in this case how do we know how many lines are actually under dark blue and so on?
comment on: http://stackoverflow.com/a/52750981
score: 0

http://stackoverflow.com/comment/92245865
type: Comment
comment on: http://stackoverflow.com/q/52657676
score: 0
type: QuestionComment
has text: Literally `df.loc[3, 'D']`, or `df.loc[2, 'B']`

http://stackoverflow.com/a/52715328
has comment: http://stackoverflow.com/comment/92356218
has body: class PayViewSet(ModelViewSet): @action(methods=['PATCH'], detail=True) @transaction.atomic def approval(self, request, *args, **kwargs): sid = transaction.savepoint() success = something if success: transaction.savepoint_commit(sid) return success_response('yes') else: transaction.savepoint_rollback(sid) return error_response('no') savepoint is optionally depending on your situation
score: 12
type: Answer
has comment: http://stackoverflow.com/comment/92356102
accepted answer of: http://stackoverflow.com/q/52715005
upvote count: 12
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52715005
downvote count: 0
has comment: http://stackoverflow.com/comment/92356354

http://stackoverflow.com/comment/92191575
has text: If you output `{{ form.errors }}` in your template, then Django will *tell* you why it is not valid.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52628947

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/52671192
tags question: http://stackoverflow.com/q/52685198
tag name: google-oauth

http://stackoverflow.com/comment/92115776
type: AnswerComment
score: 1
type: Comment
has text: That's not what the OP means. `old_dicts` actually have those three keys too, but just with different values, hence the assertions of inequality in the OP's code.
comment on: http://stackoverflow.com/a/52590352

http://stackoverflow.com/q/52743995
tagged with: python
has answer: http://stackoverflow.com/a/53121278
has title: Moblenet V2: Importing graph with lower producer version into a graph with higher producer version
type: AnsweredQuestion
tagged with: pre-trained-model
has comment: http://stackoverflow.com/comment/92942490
accepted answer: http://stackoverflow.com/a/53121278
upvote count: 1
tagged with: tensorflow
type: Question
score: 1
has comment: http://stackoverflow.com/comment/92991953
answer count: 1
downvote count: 0
has body: I developing a transfer learning application where I am retraining MobileNetV2 for my data stream. I am retraining the model with retrain.py from tensorflow-hub and have made no modifications. When I run the script from a terminal, I get this warning directly after the model is downloaded to a temporary directory in my user profile. Importing a graph with a lower producer version 26 into an existing graph with producer version 27. Shape inference will have run different parts of the graph with different producer versions. During my debugging efforts, I created a test.py script to find out where the warning is coming from: import tensorflow as tf import tensorflow_hub as hub def create_module_graph(module_spec): """Creates a graph and loads Hub Module into it. Args: module_spec: the hub.ModuleSpec for the image module being used. Returns: graph: the tf.Graph that was created. bottleneck_tensor: the bottleneck values output by the module. resized_input_tensor: the input images, resized as expected by the module. wants_quantization: a boolean, whether the module has been instrumented with fake quantization ops. """ FAKE_QUANT_OPS = ('FakeQuantWithMinMaxVars', 'FakeQuantWithMinMaxVarsPerChannel') height, width = hub.get_expected_image_size(module_spec) with tf.Graph().as_default() as graph: resized_input_tensor = tf.placeholder(tf.float32, [None, height, width, 3]) m = hub.Module(module_spec) bottleneck_tensor = m(resized_input_tensor) wants_quantization = any(node.op in FAKE_QUANT_OPS for node in graph.as_graph_def().node) return graph, bottleneck_tensor, resized_input_tensor, wants_quantization def main(): module_spec = hub.load_module_spec('https://tfhub.dev/google/imagenet/mobilenet_v2_100_96/classification/2') graph, bottleneck_tensor, resized_input_tensor, wants_quantization = create_module_graph(module_spec) if __name__ =='__main__': main() And found it originated from the create_module_graph function in retrain.py. When I run the script from the terminal using p…
tagged with: transfer-learning
favorite count: 0

http://stackoverflow.com/comment/92138362
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52600892
has text: Possible duplicate of [SyntaxError: multiple statements found while compiling a single statement python](https://stackoverflow.com/questions/24588956/syntaxerror-multiple-statements-found-while-compiling-a-single-statement-python)
type: Comment

http://stackoverflow.com/a/52669234
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52667863
answers question: http://stackoverflow.com/q/52667863
type: Answer
has comment: http://stackoverflow.com/comment/92372329
has body: Unless data is already partitioned by emp_name (and in your case it isn't, and partitioning as such would require as shuffle) or data is loaded from a table bucketed by emp_name (same as before it isn't) reshaping data to the desired format, for example with pivot df.groupBy("emp_name").pivot("class", [True, False]).sum() will require a shuffle.
score: 0

http://stackoverflow.com/comment/92414178
type: QuestionComment
comment on: http://stackoverflow.com/q/52744777
has text: Did you try to place an [example request](https://finance.google.com/finance/converter?a=10&from=cad&to=gbp) manually ?
score: 0
type: Comment

http://stackoverflow.com/comment/92193523
has text: Your requested output throws a `TypeError`. It's not a valid dictionary structure but, rather, an impossible `set()`
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52630059

http://stackoverflow.com/comment/92202503
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52634552
has text: do you have *MacOS High Sierra 10.13.6* or *Linux machine*?
score: 0

http://stackoverflow.com/comment/137148595
type: Comment
comment on: http://stackoverflow.com/a/61958101
score: 0
type: AnswerComment
has text: It probably doesn't matter that much. Pandas is a homework tag, and there are probably *literally* tens of thousands of duplicates to this question. One duplicate less or one duplicate more doesn't matter (incl. the answers).

http://stackoverflow.com/q/52723335
type: Question
tagged with: http://stackoverflow.com/tag/c
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How can I get the gtk window of a C running program through a python script?
tagged with: gtk
has body: Is there a way to get the window in which we are with a python script in a running program that allows python scripts? The program I'm talking about is dia, that is written in C, which opens all the python scripts stored in the correct folder when ran. For example, if the simple following script is stored in .dia/python print "Something" that's what happens when I run dia $ dia &amp; $ Something So it's easy to import a script, but now what I want is to get the window, to be able to manipulate it (for example do changes on menu) or call other gtk functions, for example to add an hotkey into the application.
has answer: http://stackoverflow.com/a/52724674
tagged with: dia
downvote count: 0
score: 1

http://stackoverflow.com/q/52697541
score: 2
answer count: 1
downvote count: 0
tagged with: flask-sqlalchemy
favorite count: 0
has body: I faced with error, the sense of witch I can't understand: I write to models: class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) class UserFile(db.Model): __tablename__ = 'user_files' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) author_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) author = db.relationship(User, foreign_keys=[author_id]) I need to do a number of additional steps when I delete a UserFile instance. When a UserFile instance is deleted directly, I can do whatever I need to do. There is a problem when the User instance is deleted. In this case, I need to remove all UserFile instances associated with the User. But I can't use cascade deletion, because I need to perform additional actions for each UserFile. I tried using SQLAlchemy 'before_delete' event, but I got an error because it was already running after deletion, although it was called 'before'. I saw this by adding output of the message to the console and not seeing this message in the console until I got the error. Then I tried using FLASK-sqlalchemy signals. I did: from flask_sqlalchemy import before_models_committed @before_models_committed.connect_via(app) def delete_all_user_folders_after_delete(sender, changes): for obj, operation in changes: if isinstance(obj, User) and operation == 'delete': print('files: ', UserFile.query.filter_by(author_id=obj.id, parent_id=None).all()) for item in UserFile.query.filter_by(author_id=obj.id, parent_id=None).all(): print(item) delete_file(item, True) And got error on line: print ('files: ', UserFile.query.filter_by(author_id=obj.id, parent_id=None).all()) What is the cause of this error and how do I properly pre-delete all Userfiles before deleting a User? Error description: sqlalchemy.exc.IntegrityError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematur…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52700813
upvote count: 2
has title: Why I receive sqlalchemy.exc.IntegrityError
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/92321837
has comment: http://stackoverflow.com/comment/92321548

http://stackoverflow.com/comment/92320109
has text: Would be the same numbers as above, duplicated ? not the optimal way I guess..
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52696762

http://stackoverflow.com/q/52708033
has title: Python + Numpy : TypeError: 'int' object is not callable
type: AnsweredQuestion
upvote count: 5
type: Question
tagged with: numpy
answer count: 1
score: 4
has comment: http://stackoverflow.com/comment/92342629
accepted answer: http://stackoverflow.com/a/52708218
favorite count: 0
has body: I am trying to find the optimal smoothing parameter for additive smoothing with 10-fold cross validation. I wrote the following code: alphas = list(np.arange(0.0001, 1.5000, 0.0001)) #empty list that stores cv scores cv_scores = [] #perform k fold cross validation for alpha in alphas: naive_bayes = MultinomialNB(alpha=alpha) scores = cross_val_score(naive_bayes, x_train_counts, y_train, cv=10, scoring='accuracy') cv_scores.append(scores.mean()) #changing to misclassification error MSE = [1 - x for x in cv_scores] #determining best alpha optimal_alpha = alphas[MSE.index(min(MSE))] I am getting the following error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-21-9d171ddceb31&gt; in &lt;module&gt;() 18 19 #determining best alpha ---&gt; 20 optimal_alpha = alphas[MSE.index(min(MSE))] 21 print('\nThe optimal value of alpha is %f' % optimal_alpha) 22 TypeError: 'int' object is not callable I have run the same code for different values of parameters of arange() and K (cross validation). This is the first time I encountered this error. Why?
has answer: http://stackoverflow.com/a/52708218
tagged with: python
downvote count: 1

encoder-decoder
type: Tag
tags question: http://stackoverflow.com/q/52605067
tag name: encoder-decoder

http://stackoverflow.com/a/52682663
upvote count: 2
type: Answer
has body: import re alphabet = "abcdefghijklmnopqrstuvwxyz" def cleanIt(clean): global alphabet s = re.sub('[^a-z]+', '?', str(clean)) return s def symbol_add(symbol, key): position = alphabet.find(symbol) newPosition = (position + key) % 26 newLetter = alphabet[newPosition] return newLetter def cipher(data,key): text = "" for letter in data: if letter in alphabet: text += symbol_add(symbol=letter,key=key) return text def main(): try: msg = (input("Write the message you would like to encrypt\n")) key = int(input("which key would you like to use?\n")) # Note: you need to assign msg to be equal to cleanIt(clean=msg). # Just calling cleanIt(clean=msg) won't work, as strings # are immutable in Python msg = cleanIt(clean=msg) print(cipher(data=msg, key=key)) except ValueError: print("Write a number!") main() The main changes are: The for loop was moved from symbol_add to cipher, so that symbol_add gets called for each character In main(): cleanIt(clean=msg) -> msg = cleanIt(clean=msg); the reason for this is that strings are immutable in Python, meaning that you need to reassign the variable msg to essentially point to the new string. Output of this code: Write the message you would like to encrypt test which key would you like to use? 1 uftu Also, try to stick to a single naming convention; you have a function that follows camelCase (cleanIt) and another that follows snake_case (symbol_add). Try and name all functions in the same way. (The convention in Python is to use snake_case for functions)
score: 2
has comment: http://stackoverflow.com/comment/92293520
answers question: http://stackoverflow.com/q/52682436
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52682436

http://stackoverflow.com/comment/92199976
comment on: http://stackoverflow.com/q/52633254
score: 1
has text: That screenshot is not helpful. Show the contents of `_posts`, as (properly formatted) text.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52731903
answer count: 2
has body: I have the data set of customers with their policies, I am trying to find the number of months the customer is with us. (tenure) df cust_no poly_no start_date end_date 1 1 2016-06-01 2016-08-31 1 2 2017-05-01 2018-05-31 1 3 2016-11-01 2018-05-31 output should look like, cust_no no_of_months 1 22 So basically, it should get rid of the months where there is no policy and count the overlapping period once not twice. I have to do this for every customers, so group by cust_no, how can i do this? Thanks.
tagged with: pandas-groupby
tagged with: pandas
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52733223
favorite count: 0
possible better answer: http://stackoverflow.com/a/52732064
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52732064
type: Question
tagged with: python
has title: Finding number of months between overlapping periods - pandas
upvote count: 2
accepted answer: http://stackoverflow.com/a/52733223

http://stackoverflow.com/comment/92136396
type: QuestionComment
has text: @AasmundEldhuset I tried to remove the >>> but it won't allow me
comment on: http://stackoverflow.com/q/52600892
score: 0
type: Comment

http://stackoverflow.com/comment/92201070
comment on: http://stackoverflow.com/q/52633803
type: Comment
type: QuestionComment
has text: I know this code creates png image. However, the png image looks different from the dicom image when I see dicom image with dicom browser. Also, how can I creat jpg image from a numpy array?
score: 0

http://stackoverflow.com/comment/92254102
has text: I didn't exactly get that ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52661318

http://stackoverflow.com/comment/92211592
has text: yes, but i have waited more than 10 minutes and still its not executing. I've updated the question
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52639164
type: Comment

http://stackoverflow.com/comment/111565864
type: Comment
has text: The [`databases` package](https://www.encode.io/databases/) also provides this capability for SQLite and a number of other databases. `databases` is more popular than `aiosqlite` (as measured by GitHub stars), but they are both mature and actively maintained.
type: AnswerComment
comment on: http://stackoverflow.com/a/52682997
score: 0

http://stackoverflow.com/comment/92150435
type: Comment
score: 1
type: AnswerComment
has text: I alredy did it
comment on: http://stackoverflow.com/a/52608105

http://stackoverflow.com/q/52698670
has comment: http://stackoverflow.com/comment/92325475
has comment: http://stackoverflow.com/comment/92325357
has comment: http://stackoverflow.com/comment/92326314
has comment: http://stackoverflow.com/comment/92326497
tagged with: python
accepted answer: http://stackoverflow.com/a/52703339
has comment: http://stackoverflow.com/comment/92325407
has comment: http://stackoverflow.com/comment/92325048
downvote count: 2
has body: from keras.layers import Conv2D, Input # input tensor for a 3-channel 256x256 image x = Input(shape=(256, 256, 3)) # 3x3 conv with 2 output channels (same as input channels) y = Conv2D(2, (3, 3), padding='same')(x) z = keras.layers.add([x, y]) I need to create a neural network that not only classifies images, but also counts objects inside it.So, I have to create two channels, is the code above right? How can I train and predict in this case?
tagged with: tensorflow
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92324433
has comment: http://stackoverflow.com/comment/92325851
has comment: http://stackoverflow.com/comment/92325734
score: -2
has comment: http://stackoverflow.com/comment/92325542
has answer: http://stackoverflow.com/a/52703339
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92324712
tagged with: keras
has title: How add new channels in keras?
favorite count: 0

http://stackoverflow.com/comment/92296692
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52684122
score: 0
has text: <class 'bytes'>, so i have to use ".decode("utf-8") ", instead of str() ?

http://stackoverflow.com/a/52736108
answers question: http://stackoverflow.com/q/52736009
score: 0
has body: An easy but slightly fugly workaround is to have the formatting decorations in the string. try: pbm = ". Pubmed: " + art['pubmedId_s'] except (KeyError, NameError): pbm = "" ... print(f"{nom} ({dat}). {tit}. {jou}{pbm}")
type: Answer

http://stackoverflow.com/q/52615401
type: UnansweredQuestion
has body: I have created an XGBoost classifier and dumped the python file using joblib in a dat fileformat. I am able to load it using joblib but when I try to use the loaded model to predict on new data, I see the error xgboost.core.XGBoostError: need to call fit beforehand The original model that i trained was: XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=0.6, eval_metric='error', gamma=0, learning_rate=0.125, max_delta_step=0, max_depth=8, min_child_weight=1, missing=None, n_estimators=600, n_jobs=1, nthread=None, objective='binary:logistic', random_state=0, reg_alpha=0.2, reg_lambda=0.8, scale_pos_weight=1, seed=None, silent=True, subsample=0.8) The pickled model is: XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=3, min_child_weight=1, missing=None, n_estimators=100, n_jobs=1, nthread=None, objective='binary:logistic',random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=1) Any reason for the error and why both differ despite me saving and loading the same model?
score: 2
has answer: http://stackoverflow.com/a/54428810
downvote count: 0
tagged with: xgboost
favorite count: 0
type: Question
tagged with: python
upvote count: 2
has title: xgboost.core.XGBoostError: need to call fit beforehand - when trying to predict through a pickled model
answer count: 1
has comment: http://stackoverflow.com/comment/92165268

http://stackoverflow.com/comment/97771153
has text: also consider using `verify` + `checkHost` + `CAfile` options in stunnel, to check certificate chain of trust back to a CA...
comment on: http://stackoverflow.com/q/52617392
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92287255
has text: I just want an output in the form of 2,3,4,8 simple in a iline
comment on: http://stackoverflow.com/q/52679304
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92134073
comment on: http://stackoverflow.com/a/52599773
has text: Getting this error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/92156839
comment on: http://stackoverflow.com/a/52609404
score: 0
type: AnswerComment
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/181163/discussion-between-moshe-slavin-and-lunalight).

http://stackoverflow.com/comment/92242346
comment on: http://stackoverflow.com/a/52655390
type: Comment
has text: for example: Enter Player 1 choice (R, P, or S): R but the R after the semicolon is underlined when the program is run in pydev
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92371330
type: QuestionComment
comment on: http://stackoverflow.com/q/52722821
has text: "select" as in within the GUI, using the mouse cursor to select the text to copy? Or "select" as in get the text within the code and do something with it?
score: 0
type: Comment

http://stackoverflow.com/a/55418198
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/52606751
downvote count: 0
has body: As I posted on the thread Keras, How to get the output of each layer?, the way to solve this is to replace the line outputs = [ layer.output for layer in model.layers if layer.name == layer_name or layer_name is None ] with outputs = [ layer.output for layer in model.layers if layer.name == layer_name or layer_name is None ][1:] ...in order to skip the input layer.
type: Answer

relative-path
type: Tag
tags question: http://stackoverflow.com/q/52745241
tags question: http://stackoverflow.com/q/52595385
tag name: relative-path

http://stackoverflow.com/comment/113981838
has text: @A.B I don't have a linkedin profile (nor a social media account), but feel free to get in touch using the email in my profile page.
type: AnswerComment
comment on: http://stackoverflow.com/a/52629902
score: 0
type: Comment

http://stackoverflow.com/comment/92224589
comment on: http://stackoverflow.com/q/52638332
score: 0
has text: @JPG I mean I want to be able to send a GET/PUT/DELETE request to computers/<computer_id> and be able to get that computer ID, update that computer ID, or delete it, all from that endpoint
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92233178
comment on: http://stackoverflow.com/q/52650583
type: QuestionComment
score: 3
type: Comment
has text: I don't really see why someone would need something like that in the first place... Can you give us an use case? Maybe we can figure out a better way of doing what you want to do

http://stackoverflow.com/a/52623795
score: 1
answers question: http://stackoverflow.com/q/52623621
upvote count: 1
downvote count: 0
has body: The result of (30 - 6.75) * 0.02 is 0.465. So we would expect to get 0.47 when rounding. But here seems to be an explanation : round() documentation. The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92188801
type: Answer
has comment: http://stackoverflow.com/comment/92192136
accepted answer of: http://stackoverflow.com/q/52623621

http://stackoverflow.com/comment/92334156
comment on: http://stackoverflow.com/a/52703633
score: 0
type: AnswerComment
type: Comment
has text: Apologies, fixed and I added an example

http://stackoverflow.com/a/52755095
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52734736
type: Answer
has body: You can have both versions of pip together (pip2, pip3). Also pip can be linked to whether pip2/python2 or pip3/python3. For me, pip is linked to the Python 3.x, pip2 to the Python 2.7 and pip3 to the Python 3.x: $ pip -V pip 9.0.3 from /usr/local/lib/python3.6/dist-packages/pip-9.0.3-py3.6.egg (python 3.6) $ pip2 -V pip 10.0.1 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7) $ pip3 -V pip 9.0.3 from /usr/local/lib/python3.6/dist-packages/pip-9.0.3-py3.6.egg (python 3.6) Python versions: $ python -V Python 2.7.12 $ python3 -V Python 3.6.6 In this case, you should install bokeh for both versions of Python: pip3 install bokeh pip2 install bokeh Test: $ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import bokeh >>> $ python3 Python 3.6.6 (default, Jun 28 2018, 04:42:43) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import bokeh >>> [NOTE]: Refer to the following links to install both versions of pip: Link_1 Link_2

http://stackoverflow.com/a/52619211
upvote count: 2
has body: The problem is simple you have to enable the widgetResizable property to True since that property allows the QScrollArea to calculate the size of the content. scroll.setWidgetResizable(True) On the other hand I have taken the time to improve your code and I show it below: from PyQt4 import QtGui, QtCore class Bubble(QtGui.QLabel): def __init__(self, text): super(Bubble,self).__init__(text) self.setContentsMargins(5, 5, 5, 5) def paintEvent(self, e): p = QtGui.QPainter(self) p.setRenderHint(QtGui.QPainter.Antialiasing, True) p.drawRoundedRect(self.rect().adjusted(0, 0, -1, -1), 5, 5) super(Bubble, self).paintEvent(e) class MyWidget(QtGui.QWidget): def __init__(self, text, left=True): super(MyWidget,self).__init__() lay = QtGui.QVBoxLayout(self) lay.setContentsMargins(0, 0, 0, 0) self.setContentsMargins(0, 0, 0, 0) label = Bubble(text) lay.addWidget(label, alignment= QtCore.Qt.AlignLeft if left else QtCore.Qt.AlignRight) class Chatting(QtGui.QWidget): def __init__(self, parent=None): super(Chatting, self).__init__(parent) widget = QtGui.QWidget() self.vbox = QtGui.QVBoxLayout(widget) self.vbox.addStretch() self.scroll = QtGui.QScrollArea(widgetResizable=True) self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.scroll.setWidget(widget) #Scroll Area Layer add send = QtGui.QPushButton(icon= QtGui.QIcon('images/send.png')) send.setStyleSheet("background-color:#d00001; width: 44px") send.setIconSize(QtCore.QSize(84,20)) send.clicked.connect(self.on_clicked) vLayout = QtGui.QVBoxLayout(self) vLayout.addWidget(self.scroll) vLayout.addWidget(send) def send_message(self, text, direction=True): widget = MyWidget(text, direction) self.vbox.insertWidget(self.vbox.count()-1, widget) scroll_bar = self.scroll.verticalScrollBar() # move to end QtCore.QTimer.singleShot(10, lambda: scroll_bar.setValue(scroll_bar.maximum())) @QtCore.pyqtSlot() def on_clicked(self): self.send_message("testing") if…
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52618980
accepted answer of: http://stackoverflow.com/q/52618980
has comment: http://stackoverflow.com/comment/92172508
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92130209
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52597760
has text: more than 1 sandwiched? so if you have ['A', '', 'B'] you don't want to keep the single quote?

http://stackoverflow.com/q/52693903
has comment: http://stackoverflow.com/comment/92314591
has body: I need to sort a list of file paths into lexicographic order such as the output is sorted like this: C:\Test\Project1\Example\test1.txt C:\Test\Project1\Example\test2.txt C:\Test\Project1\Example\Sub\meee.txt C:\Test\Project1\Example\Sub\test1.txt C:\Test\Project1\Example\Sub\youu.txt C:\Test\Project1\Example\Zzz\zzz.py When I sort it naturally I receive C:\Test\Project1\Example\Sub\meee.txt before C:\Test\Project1\Example\test1.txt and do not want that.
type: UnansweredQuestion
score: 1
tagged with: file
upvote count: 1
has answer: http://stackoverflow.com/a/52693984
type: Question
tagged with: sorting
has comment: http://stackoverflow.com/comment/92314641
answer count: 1
downvote count: 0
tagged with: lexicographic
favorite count: 0
has title: How to order file paths in lexicographical order? Python
tagged with: path
tagged with: python

http://stackoverflow.com/a/52601418
has comment: http://stackoverflow.com/comment/92276558
type: AcceptedAnswer
has body: With the minimum information you have given, this can be used as a solution: Let's create a function to get data for both years, if available. def compare(x): f1 = df.loc[df['year'] == x, 'feature'].values[0] y2 = x - 7 if y2 in df['year'].unique(): f2 = df.loc[df['year'] == y2, 'feature'].values[0] return (x, f1, y2, f2) else: pass Apply the function to the year column and assign a new dataframe name. foo = df['year'].apply(compare) Create a dataframe of non-null values in foo: bar = pd.DataFrame(data = list(foo.loc[~foo.isnull()]), columns = ['f1', 'y1', 'f2', 'y2']) This will result in four columns for easy comparison. I understand you were looking for two columns solution but a four column solution with comparative data next to each other would make sense for later usage as well.
score: 0
has comment: http://stackoverflow.com/comment/92137445
type: Answer
accepted answer of: http://stackoverflow.com/q/52600243
answers question: http://stackoverflow.com/q/52600243

http://stackoverflow.com/comment/92299498
score: 0
type: Comment
has text: @juanpa.arrivillaga good article. Even has a code runtime visualizer.
type: QuestionComment
comment on: http://stackoverflow.com/q/52685928

http://stackoverflow.com/q/52681601
linked to: http://stackoverflow.com/q/36293208
tagged with: machine-learning
linked to: http://stackoverflow.com/q/52089601
linked to: http://stackoverflow.com/q/42154792
has comment: http://stackoverflow.com/comment/92293327
answer count: 1
has comment: http://stackoverflow.com/comment/92291609
tagged with: time-series
has body: First, I have read this and this questions with similar names to mine and still do not have an answer. I want to build a feedforward network for sequence prediction. (I realize that RNNs are more suitable for this task, but I have my reasons). The sequences are of length 128 and each element is a vector with 2 entries, so each batch should be of shape (batch_size, 128, 2) and the target is the next step in the sequence, so the target tensor should be of shape (batch_size, 1, 2). The network architecture is something like this: model = Sequential() model.add(Dense(50, batch_input_shape=(None, 128, 2), kernel_initializer="he_normal" ,activation="relu")) model.add(Dense(20, kernel_initializer="he_normal", activation="relu")) model.add(Dense(5, kernel_initializer="he_normal", activation="relu")) model.add(Dense(2)) But trying to train I get the following error: ValueError: Error when checking target: expected dense_4 to have shape (128, 2) but got array with shape (1, 2) I've tried variations like: model.add(Dense(50, input_shape=(128, 2), kernel_initializer="he_normal" ,activation="relu")) but get the same error.
has answer: http://stackoverflow.com/a/52681743
type: AnsweredQuestion
tagged with: forecasting
has comment: http://stackoverflow.com/comment/92291770
downvote count: 0
tagged with: keras
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/92291849
score: 3
has comment: http://stackoverflow.com/comment/92292348
tagged with: python
accepted answer: http://stackoverflow.com/a/52681743
has title: Keras 2D input to 2D output
upvote count: 3

http://stackoverflow.com/comment/92310886
score: 1
comment on: http://stackoverflow.com/q/52691945
type: Comment
type: QuestionComment
has text: Can you post samples of the initial DataFrames?

http://stackoverflow.com/a/52653329
downvote count: 0
has comment: http://stackoverflow.com/comment/94221887
answers question: http://stackoverflow.com/q/52652789
has body: In addition to bigreddot's answer if someone wants to know how to get bokeh chart from holoview renderer = hv.renderer('bokeh') myb = renderer.get_plot(holoviewplot).state myb.name = 'mynewchart' curdoc().add_root(myb) And then in the template {{ embed(roots.mynewchart) }}
type: Answer
has comment: http://stackoverflow.com/comment/112215066
score: 1
upvote count: 1

http://stackoverflow.com/q/52683873
tagged with: object
has title: Creating a nested object
downvote count: 1
has comment: http://stackoverflow.com/comment/92295850
type: Question
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/52684041
tagged with: javascript
score: -1
has answer: http://stackoverflow.com/a/52684020
tagged with: hashtable
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92295796
has comment: http://stackoverflow.com/comment/92295898
has body: this is what I am trying to do: "book" =&gt; {b:{o:{o:k:{'end':true} can someone explain me / link me an explanation for this? const ENDS_HERE = '__ENDS_HERE' class Trie { constructor() { this.node = {}; } insert(word){ let trie = this.node; console.log( 'start inset', trie ) for ( let index in word ) { let char = word[index]; if ( !trie[char] ) { trie[char]= {} } console.log( trie ) trie = trie[char] } trie[ENDS_HERE] = true } } let test= new Trie test.insert('book') test.insert('baak') this is what it logs: start inset {} { b: {} } { o: {} } { o: {} } { k: {} } start inset { b: { o: { o: [Object] } } } { b: { o: { o: [Object] } } } { o: { o: { k: [Object] } }, a: {} } { a: {} } { k: {} } on this line trie = trie[char] it reset the trie to {}. the last line for insert function then set { '__ENDS_HERE' = true} however when calling test.insert('baak') you can see that trie === { b: { o: { o: [Object] } } } . my question is how does it build {b:{o:{o:k:{'end':true} ? same results occurs in python. above code is written in javascript.
tagged with: python

http://stackoverflow.com/comment/92147512
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52595548
has text: Yes that fixes the bug in the constructor, but something is still wrong with the dimensions. Can you see anything?
score: 0

http://stackoverflow.com/comment/92197640
comment on: http://stackoverflow.com/q/52632158
type: Comment
type: QuestionComment
score: 1
has text: It's a basic programming task for school. Attempt yourself, play with loops and strings.

http://stackoverflow.com/q/52672369
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52672402
downvote count: 1
has comment: http://stackoverflow.com/comment/92274700
has comment: http://stackoverflow.com/comment/92274571
has body: I created this function that returns the GDP per capita and military spending per capita for some countries I am analyzing based on a particular year. def compare(year): simple = data.loc[year, :].sort_values(by = "gdp_pc", ascending = False) simple = simple.reset_index() simple = simple.drop(["gdp_share", "military_exp", "pop", "gdp"], axis = 1) simple = simple.round(2) simple.columns = ["Countries", "GDP per capita", "Military spending per capita"] simple.index = simple.index + 1 return simple I have already tested the function and it works fine. However, I would like to make it more user-friendly and have the user input the year (argument of the function). How do I do this?
type: Question
accepted answer: http://stackoverflow.com/a/52672402
tagged with: function
has comment: http://stackoverflow.com/comment/92274539
score: -1
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92274649
favorite count: 0
has title: Use input() as an argument in a function in Python
tagged with: input
tagged with: python

http://stackoverflow.com/comment/92243171
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52655887
has text: Your environment name should be prepended to your command prompt, e.g. `(testproj) yourname:~ yourname$` And using `conda info --envs` will list all of your conda environments, with `*` next to the active one. `which python` should show you the location of the executable.
score: 0

http://stackoverflow.com/q/52610740
has comment: http://stackoverflow.com/comment/92156103
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52649885
accepted answer: http://stackoverflow.com/a/52649885
answer count: 2
downvote count: 1
favorite count: 0
has title: Can't import tensorflow in Python 3.6.6
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92156215
has comment: http://stackoverflow.com/comment/92155886
possible better answer: http://stackoverflow.com/a/52610809
tagged with: pip
has body: I installed tensorflow with pip3 install tensorflow and then I opened the terminal typed python and import tensorflow. But when I hit Enter it gives me an Error: Invalid machine command (memory dump written) I already reinstalled tensorflow multiple times but it won't work. Could someone please help me?
has answer: http://stackoverflow.com/a/52610809
tagged with: tensorflow
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92155908

http://stackoverflow.com/comment/92384977
has text: Adding `--ipc=host` doesn't seem to solve the issue.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52715141
type: Comment

http://stackoverflow.com/a/58608431
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52639703
type: Answer
has body: I notice this haven't been active for a while but I'm trying to do the same and can't seem to make it work. What I noticed is that the encoded password string stored by Laravel is a base 64 encoded json object, which wasn't taken into consideration in the original question: pass_obj = base64.b64decode('[binary]') print(pass_obj) &gt;&gt;&gt; b'{"iv":"gqcE\\/1hvjHHUxjYRZbCtJQ==","value":"LWwFIiGvm50yni6m0R408S67\\/XK9JV+4\x1e16T{BHuSqo=","mac":"79ec4a61b9cdab780666455fd9b75fbe8e870d2433072eac17768fe51b226e94"}' From that you can get the IV and the encrypted value, both seem to be base64 encoded. But I still get a decoding error at the end like; UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfa in position 0: invalid start byte Here is my complete code; password = 'eyJpdiI6ImJGNDNNZjN3YWtpcDQ5VEJVXC9IazF3PT0iLCJ2YWx1ZSI6IkNVRW1VQUY1dXArYlFkU3NlY1pnZUE9PSIsIm1hYyI6ImM3ODk0NWQ0NjgxMzM4YjE0M2JhN2MzZWRmOWEwMWJiMjI2Y2FhYmUxYjFhYzAyYjY4YWZkZGE3N2EyMDYwNWYifQ==' key = 'some secret key that i can't share'.encode() p_obj = json.loads(base64.b64decode(password).decode()) decobj = AES.new(key, AES.MODE_CBC, base64.b64decode(p_obj['iv'])) data = decobj.decrypt(base64.b64decode(p_obj['value'])) print(data) &gt;&gt;&gt; b'l\xee:f\x9eZ\x90rP\x99\xca&amp;@\x1d1\x9f' data.decode() &gt;&gt;&gt; Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'utf-8' codec can't decode byte 0xee in position 1: invalid continuation byte @Pecans did you ever figure this out? Thank you. Full working code EDIT I fugured it out, I had a problem with my key initially. So here's the full snippet for future reference; import base64 import json from phpserialize import unserialize from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad key = b'my secret key' enc_pass = 'eyJpdiI6ImJGNDNNZjN3YWtpcDQ5VEJVXC9IazF3PT0iLCJ2YWx1ZSI6IkNVRW1VQUY1dXArYlFkU3NlY1pnZUE9PSIsIm1hYyI6ImM3ODk0NWQ0NjgxMzM4YjE0M2JhN2MzZWRmOWEwMWJiMjI2Y2FhYmUxYjFhYzAyYjY…
score: 1

http://stackoverflow.com/comment/92171712
score: 0
type: QuestionComment
type: Comment
has text: Your code as shown does nothing but create an empty list, define a function and a class. You never use the function or the class to create any objects. If you try to create a class with `ModelBasic` it will throw an `AttributeError`
comment on: http://stackoverflow.com/q/52618428

google-maps
tags question: http://stackoverflow.com/q/52616484
tag name: google-maps
tags question: http://stackoverflow.com/q/52675837
type: Tag
tags question: http://stackoverflow.com/q/52709241

http://stackoverflow.com/q/52676059
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92281514
tagged with: urlopen
has answer: http://stackoverflow.com/a/52676120
tagged with: connection-timeout
type: Question
has body: I want to create a connection timeout exception using urlopen. try: urllib2.urlopen("http://example.com", timeout = 5) except urllib2.URLError, e: raise MyException("There was an error: %r" % e) This is the code I want to create a timeout that this code would bring an exception. Thank You in advance.
answer count: 1
has title: Create a Conection TimeOut using urllib2.urlOpen()
score: 0
tagged with: python

http://stackoverflow.com/comment/92231351
has text: `.reset()` returns `None` if there is no explicit return clause. You seem to want `.reset()` to return the reset instance. Updated my answer
type: AnswerComment
comment on: http://stackoverflow.com/a/52649195
score: 0
type: Comment

http://stackoverflow.com/q/52725477
possible better answer: http://stackoverflow.com/a/52725595
has comment: http://stackoverflow.com/comment/92376234
downvote count: 2
has answer: http://stackoverflow.com/a/52725595
tagged with: python
type: AnsweredQuestion
score: 2
has title: Why does 'or' only use the first value in python?
has comment: http://stackoverflow.com/comment/92376491
has answer: http://stackoverflow.com/a/52725518
has comment: http://stackoverflow.com/comment/92376319
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/92376374
linked to: http://stackoverflow.com/q/18195322
has body: b = 'a' print(b==('b' or 'a')) You will get False if you enter this code. But if you change the order like this: b = 'a' print(b==('a' or 'b')) You get True. So, why does or in this code only consider the first value of the two? I think the upper code should also return True.
has comment: http://stackoverflow.com/comment/92376267
has comment: http://stackoverflow.com/comment/92376475
accepted answer: http://stackoverflow.com/a/52725518
favorite count: 0

http://stackoverflow.com/q/52591066
tagged with: python
has comment: http://stackoverflow.com/comment/92160196
tagged with: tweepy
score: 2
has title: How to retrieve full text tweets using tweepy?
tagged with: twitter
has answer: http://stackoverflow.com/a/55448092
type: Question
has body: I am trying to scrape tweets from a user-defined Twitter profile. Having read previous posts I understand that the Twitter JSON has a section for extended tweets. I've added tweet_mode='extended' into my api.user_timeline section and changed .text to .full_text. However, I am still getting truncated tweets. I understand that retweets have a full_text attribute but I am scraping the timeline and not separating tweets from retweets. Is there a way to universally query tweets and retrieve the full_text version. I have included my code below. screen_name_list = ['@x'] for name in screen_name_list: user = api.get_user(name) #initialize a list to hold all the tweepy Tweets alltweets = [] #make initial request for most recent tweets (200 is the maximum allowed count) new_tweets = api.user_timeline(screen_name = name, count = 200,tweet_mode='extended', include_rts=True) #save most recent tweets alltweets.extend(new_tweets) #save the id of the oldest tweet less one oldest = alltweets[-1].id - 1 #keep grabbing tweets until there are no tweets left to grab while len(new_tweets) &gt; 0: print 'getting tweets before %s' % (oldest) #all subsiquent requests use the max_id param to prevent duplicates new_tweets = api.user_timeline(screen_name = name, count=200, max_id=oldest, tweet_mode='extended') #save most recent tweets alltweets.extend(new_tweets) #update the id of the oldest tweet less one oldest = alltweets[-1].id - 1 print "...%s tweets downloaded so far" % (len(alltweets)) #transform the tweepy tweets into a 2D array that will populate the csv outtweets = [[tweet.id_str, tweet.created_at, tweet.full_text.encode('utf-8')] for tweet in alltweets] tweet_time = [index[1] for index in outtweets] tweet_list = [index[2] for index in outtweets]
downvote count: 0
has comment: http://stackoverflow.com/comment/92142561
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92133481
upvote count: 2
tagged with: tweets
type: UnansweredQuestion

http://stackoverflow.com/comment/92376092
type: Comment
has text: both are up to date. numpy 1.15.2 and pandas 0.23.4
type: AnswerComment
comment on: http://stackoverflow.com/a/52724284
score: 0

http://stackoverflow.com/comment/92383601
type: Comment
score: 0
type: AnswerComment
has text: But here the challenge is "*Python - How do you pad the output of a mysql table*", so that means you want that every "column" has the same "width". I agree the question perhaps could be improved, but the idea is that all rows start the same column at the same amount of spacing from the left of the screen.
comment on: http://stackoverflow.com/a/52729218

http://stackoverflow.com/q/52736009
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52736108
upvote count: 2
tagged with: f-string
tagged with: http://stackoverflow.com/tag/json
has title: Python: Hiding json empty key values with f-string
type: Question
has body: I have improved my first Python program using f-strings instead of print: .... js = json.loads(data) # here is an excerpt of my code: def publi(type): if type == 'ART': return f"{nom} ({dat}). {tit}. {jou}. Pubmed: {pbm}" print("Journal articles:") for art in js['response']['docs']: stuff = art['docType_s'] if not stuff == 'ART': continue tit = art['title_s'][0] nom = art['authFullName_s'][0] jou = art['journalTitle_s'] dat = art['producedDateY_i'] try: pbm = art['pubmedId_s'] except (KeyError, NameError): pbm = "" print(publi('ART')) This program fetches data through json files to build scientific citations: # sample output: J A. Anderson (2018). Looking at the DNA structure, Nature. PubMed: 3256988 It works well, except that (again) I don't know how to hide key values from the return statement when keys have no value (ie. there is no such key in the json file for one specific citation). For example, some of the scientific citations have no "Pubmed" key/value (pmd). Instead of printing "Pubmed: " with a blank value, I would like to get rid of both of them: # Desired output (when pbm key is missing from the JSON file): # J A. Anderson (2018) Looking at the DNA structure, Nature # NOT: J A. Anderson (2018) Looking at the DNA structure, Nature. Pubmed: Using the print statement in the publi function, I could write the following: # Pubmed: ' if len(pbm)!=0 else "", pbm if len(pbm)!=0 else "" Does anyone know how to get the same result using f-string? Thanks for your help. PS: As a python beginner, I would not have been able to solve this specific problem just reading the post Using f-string with format depending on a condition
accepted answer: http://stackoverflow.com/a/52736342
has comment: http://stackoverflow.com/comment/92402505
has comment: http://stackoverflow.com/comment/92397571
answer count: 2
linked to: http://stackoverflow.com/q/51885913
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/51300358
favorite count: 0
has comment: http://stackoverflow.com/comment/92397535
has answer: http://stackoverflow.com/a/52736342
tagged with: python
possible better answer: http://stackoverflow.com/a/52736108

http://stackoverflow.com/comment/92368110
type: AnswerComment
has text: All arrays in the question need to be 1D arrays and they need to have the same shape, else you'd get an error from the shown code. As the questions says *"In the x direction there are 275 pixel and in the y direction there are 72"*, meaning 275*72=19800 entries in each of them. It may of course be that the information in the question is inaccurate. In that case the use of pcolormesh as shown here would additionally have the problem that it only shows 19454 of the 19800 elements.
comment on: http://stackoverflow.com/a/52718246
type: Comment
score: 0

http://stackoverflow.com/a/52650468
downvote count: 0
score: 1
upvote count: 1
has body: As I don't know your complete code of have a sample of data, here would be my suggestion: Instead of using ".argmin()" just sort your list by distance and then return the first ten elements of the sorted list. Then find their indices like you're already doing it.
answers question: http://stackoverflow.com/q/52649191
type: Answer

http://stackoverflow.com/a/54495580
score: 26
has comment: http://stackoverflow.com/comment/109137248
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/125874162
has comment: http://stackoverflow.com/comment/107981698
accepted answer of: http://stackoverflow.com/q/52615414
type: Answer
answers question: http://stackoverflow.com/q/52615414
has comment: http://stackoverflow.com/comment/109130649
downvote count: 1
has body: A slightly neater way to achieve @TwoUnderscorez's answer is to just launch the module with -m IPython: "python.terminal.launchArgs": [ "-m", "IPython" ] Edit: For anyone struggling with IndentationError: unexpected indent errors, try the following: "python.terminal.launchArgs": [ "-m", "IPython", "--no-autoindent", ] (wouldn't have just added a comment to the existing answer, but not enough rep)
upvote count: 27

http://stackoverflow.com/q/52722653
has title: reference multiple python classes in one build.load_string
has body: I have python file that is supposed to reference multiple classes firstscreenScreen and secondscreenScreen in the Builder.load_string. However what it does it shows the error unknow class secondscreenScreen. I guess this is because it searches only for the first class and ignores others. I have deleted the irrevelant code here. How can I include two or multiple files in one buildloader is there an option to include 2 buil.load_string and still be able to switch screens? from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.core.window import Window from kivy.lang import Builder from kivy.uix.button import Button Builder.load_string(""" #:kivy 1.9.0 &lt;firstscreenScreen&gt;: Word: &lt;secondscreenScreen&gt;: WordList: Label: id: label1 text: self.parent.txt1 """) class Word(Widget): pass class firstscreenScreen(Screen): pass class secondscreenScreen(Screen): pass class ScreenManager(ScreenManager): pass sm = ScreenManager() sm.add_widget(firstscreenScreen(name='firstscreen')) sm.add_widget(secondscreenScreen(name='secondscreen')) class WordApp(App): def build(self): Window.clearcolor = (0,0,0.3,1) return sm if __name__ == '__main__': WordApp().run() class WordList(Widget): txt1 = "abc" class firstscreenScreen(Screen): pass class secondscreenScreen(Screen): pass class WordListApp(App): def build(self): Window.clearcolor = (0,0,0.3,1) return sm if __name__ == '__main__': WordListApp().run()
upvote count: 0
type: UnansweredQuestion
favorite count: 0
type: Question
tagged with: android
tagged with: kivy
score: -1
has answer: http://stackoverflow.com/a/52724245
tagged with: python
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92379154
has comment: http://stackoverflow.com/comment/92379052
has comment: http://stackoverflow.com/comment/92376273

http://stackoverflow.com/q/52667328
tagged with: python
linked to: http://stackoverflow.com/q/36676576
has body: I am trying to generate an array out of a file with numpy.genfromtxt. File is like: 16.37.235.200|59009|514|16.37.235.153| 17.37.235.200|59009|514|18.37.235.153| And I get an array like: ['16.37.235.200' '17.37.235.200'] But I want the array to be like that: [16.37.235.200,17.37.235.200]
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/92267241
type: Question
tagged with: numpy
tagged with: arrays
has answer: http://stackoverflow.com/a/52667949
upvote count: 3
tagged with: genfromtxt
answer count: 1
has title: How to display a NumPy array of strings without quotes and with comma as a delimiter?
favorite count: 0
linked to: http://stackoverflow.com/q/2891790
type: UnansweredQuestion

http://stackoverflow.com/q/52648735
has answer: http://stackoverflow.com/a/52648941
tagged with: odoo
has body: hello i want to give an record a domain but ican't access to the field related this my code python : class emmployee_e(models.Model): _inherit = 'employee.departement' employee_parent_id = fields.Many2one('res.partner', string="parent id",related="employee_id.parent_id",store=True) this my xml code name record employee.departement form tree,form [('employee_id','child_of', 'employee_parent_id')] {'search_default_This_Week': 1} Click here to add new message how to access to this field , i try with id of employee domain works but when i call the field related nothing happened
score: 1
tagged with: odoo-8
has title: access to field many2one related
type: Question
has answer: http://stackoverflow.com/a/52671085
answer count: 2
downvote count: 0
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/52655542
has body: You could simply use list comprehension data = ['1A', '1B', '2', '3A', '3B'] pt = [x for x in data if x in digits]
type: Answer
answers question: http://stackoverflow.com/q/52655415
has comment: http://stackoverflow.com/comment/92242724
has comment: http://stackoverflow.com/comment/92242416
score: 0

http://stackoverflow.com/comment/92339290
has text: `Box.totalMass` is a class attribute, so it's shared by all instances of `Box`. Are you sure you want that? BTW, staticmethods aren't very common in Python, but when they are used, they're normally created using the `@staticmethod` decorator.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52706200
type: Comment

http://stackoverflow.com/a/52732020
has comment: http://stackoverflow.com/comment/92420924
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92419087
has body: The missing piece to the puzzle is that @property is a descriptor (an object which implements __get__ / __set__ / __del__ to participate in attribute lookup). Implementation of descriptors is done via the __getattribute__ magic method. The important bit of the implementation here from the docs (emphasis mine): Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError. To illustrate with your example a little further: class Item(object): def __getattribute__(self, name): print(f'__getattribute__ {name}') try: return super().__getattribute__(name) except Exception as e: print(f'{e} during __getattribute__ {name}') raise def __getattr__(self, name): print("In __getattr__ looking for '{}'".format(name)) # useful logic here which might return a value... message = "'{}' object has no attribute '{}'".format(type(self).__name__, name) raise AttributeError(message) @property def thing_a(self): return self.thing_b @property def thing_b(self): return self.nonexistent_thing Item().thing_a The call sequence goes: - __getattribute__(thing_a) - property.__get__(...) - thing_a - __getattriute__(thing_b) - property.__get__(...) - thing_B - __getattribute__(nonexistent_thing) - (raised AE) -&gt; __getattr__(nonexistent_thing) - (raised AE) -&gt; __getattr_(thing_b) - (raised AE) -&gt; getattr(thing_a) The calls to __getattr__ are in response to AttributeErrors during descriptor resolution in __getattribute__. Here's the output of the above python snippet: __getattribute__ thing_a __getattribute__ thing_b __getattribute__ nonexistent_thing 'Item' object has no attribute 'nonexistent_thing' during __getattribute__ nonexistent_thing In __getattr__ looking for 'nonexistent_thing' 'Item' object has no attribute 'nonexistent_thing' during __getattribute__ thing_b In __getattr__ looking for 'thing_b' 'Item' object ha…
has comment: http://stackoverflow.com/comment/92420469
has comment: http://stackoverflow.com/comment/92407530
downvote count: 0
has comment: http://stackoverflow.com/comment/92420744
has comment: http://stackoverflow.com/comment/92419479
answers question: http://stackoverflow.com/q/52731801

http://stackoverflow.com/q/52598422
score: 0
answer count: 1
has title: auto completions ipython end square/round bracket
has answer: http://stackoverflow.com/a/52600577
linked to: http://stackoverflow.com/q/2603798
has comment: http://stackoverflow.com/comment/92131751
accepted answer: http://stackoverflow.com/a/52600577
linked to: http://stackoverflow.com/q/11486757
tagged with: python
has comment: http://stackoverflow.com/comment/92132109
type: AnsweredQuestion
type: Question
tagged with: anaconda
tagged with: autocomplete
has body: In Jupyter Notebook if you type in [ it automatically completes it to []. Same for the ( --> () and { --> {} How can one make Ipython do this? I have anaconda installation of python that also includes Ipython
has comment: http://stackoverflow.com/comment/92134721
tagged with: conda

http://stackoverflow.com/comment/92173542
comment on: http://stackoverflow.com/a/52619812
score: 0
type: AnswerComment
type: Comment
has text: remove the .text

http://stackoverflow.com/comment/92282000
type: QuestionComment
comment on: http://stackoverflow.com/q/52676396
has text: Thanks for your comment, but still not working...
score: 0
type: Comment

http://stackoverflow.com/comment/92160966
has text: $ sign is to enforce the end of the string but if we use $ sign here, it will ignore any string which has non-numeric data at the end
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52602325

http://stackoverflow.com/comment/92311305
score: 0
type: Comment
has text: Thanks, I'll consider that! And to the third point, why is it even worse to read the file system? That's where a lot of settings are stored.
comment on: http://stackoverflow.com/a/52690039
type: AnswerComment

http://stackoverflow.com/a/52741626
type: Answer
has comment: http://stackoverflow.com/comment/92409209
has body: You will need to use LocalExecutor. Check your configs (airflow.cfg), you might be using SequentialExectuor which executes tasks serially. Airflow uses a Backend database to store metadata. Check your airflow.cfg file and look for executor keyword. By default, Airflow uses SequentialExecutor which would execute task sequentially no matter what. So to allow Airflow to run tasks in Parallel you will need to create a database in Postges or MySQL and configure it in airflow.cfg (sql_alchemy_conn param) and then change your executor to LocalExecutor in airflow.cfg and then run airflow initdb. Note that for using LocalExecutor you would need to use Postgres or MySQL instead of SQLite as a backend database. More info: https://airflow.incubator.apache.org/howto/initialize-database.html If you want to take a real test drive of Airflow, you should consider setting up a real database backend and switching to the LocalExecutor. As Airflow was built to interact with its metadata using the great SqlAlchemy library, you should be able to use any database backend supported as a SqlAlchemy backend. We recommend using MySQL or Postgres.
score: 40
upvote count: 40
has comment: http://stackoverflow.com/comment/92409638
has comment: http://stackoverflow.com/comment/92408537
accepted answer of: http://stackoverflow.com/q/52741536
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92408395
answers question: http://stackoverflow.com/q/52741536
has comment: http://stackoverflow.com/comment/92409786

http://stackoverflow.com/comment/92177948
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52621748
has text: @retryme What specific command(s) are you trying to run? Also, are you sure it didn't work - *note that `subprocess.Popen` won't display any output by default* so it may have worked but you just aren't seeing any output

matplotlib
tags question: http://stackoverflow.com/q/52686649
tags question: http://stackoverflow.com/q/52603247
tags question: http://stackoverflow.com/q/52678108
tags question: http://stackoverflow.com/q/52607232
tags question: http://stackoverflow.com/q/52658364
tags question: http://stackoverflow.com/q/52640752
tags question: http://stackoverflow.com/q/52713217
tags question: http://stackoverflow.com/q/52743101
tags question: http://stackoverflow.com/q/52603227
tags question: http://stackoverflow.com/q/52710519
tags question: http://stackoverflow.com/q/52670273
tags question: http://stackoverflow.com/q/52697206
tags question: http://stackoverflow.com/q/52639892
tags question: http://stackoverflow.com/q/52731410
tags question: http://stackoverflow.com/q/52704324
tags question: http://stackoverflow.com/q/52632242
tags question: http://stackoverflow.com/q/52647493
tags question: http://stackoverflow.com/q/52743119
tags question: http://stackoverflow.com/q/52712847
tags question: http://stackoverflow.com/q/52615206
tags question: http://stackoverflow.com/q/52589054
tags question: http://stackoverflow.com/q/52711973
tags question: http://stackoverflow.com/q/52672988
tags question: http://stackoverflow.com/q/52695654
tag name: matplotlib
tags question: http://stackoverflow.com/q/52722431
tags question: http://stackoverflow.com/q/52654622
tags question: http://stackoverflow.com/q/52742100
tags question: http://stackoverflow.com/q/52673444
tags question: http://stackoverflow.com/q/52661906
tags question: http://stackoverflow.com/q/52729986
tags question: http://stackoverflow.com/q/52680145
tags question: http://stackoverflow.com/q/52731304
tags question: http://stackoverflow.com/q/52737246
tags question: http://stackoverflow.com/q/52646649
tags question: http://stackoverflow.com/q/52696447
tags question: http://stackoverflow.com/q/52642283
tags question: http://stackoverflow.com/q/52723180
tags question: http://stackoverflow.com/q/52631031
tags question: http://stackoverflow.com/q/52704327
tags question: http://stackoverflow.com/q/52629796
tags question: http://stackoverflow.com/q/52729169
tags question: http://stackoverflow.com/q/52598031
tags question: http://stackoverflow.com/q/52675819
tags question: http://stackoverflow.com/q/52633626
tags question: http://stackoverflow.com/q/52659777
tags question: http://stackoverflow.com/q/52713462
tags question: http://stackoverflow.com/q/52673550
tags question: http://stackoverflow.com/q/52663052
tags question: http://stackoverflow.com/q/52630340
tags question: http://stackoverflow.com/q/52733912
tags question: http://stackoverflow.com/q/52724030
tags question: http://stackoverflow.com/q/52617091
tags question: http://stackoverflow.com/q/52703805
tags question: http://stackoverflow.com/q/52690139
tags question: http://stackoverflow.com/q/52689091
tags question: http://stackoverflow.com/q/52722554
tags question: http://stackoverflow.com/q/52725981
tags question: http://stackoverflow.com/q/52597171
tags question: http://stackoverflow.com/q/52687144
tags question: http://stackoverflow.com/q/52598821
tags question: http://stackoverflow.com/q/52590247
tags question: http://stackoverflow.com/q/52697594
tags question: http://stackoverflow.com/q/52625998
tags question: http://stackoverflow.com/q/52629661
tags question: http://stackoverflow.com/q/52687936
tags question: http://stackoverflow.com/q/52732472
tags question: http://stackoverflow.com/q/52691048
tags question: http://stackoverflow.com/q/52634390
tags question: http://stackoverflow.com/q/52620222
tags question: http://stackoverflow.com/q/52677823
tags question: http://stackoverflow.com/q/52620922
tags question: http://stackoverflow.com/q/52737526
tags question: http://stackoverflow.com/q/52683117
tags question: http://stackoverflow.com/q/52601258
tags question: http://stackoverflow.com/q/52600652
tags question: http://stackoverflow.com/q/52720616
tags question: http://stackoverflow.com/q/52619925
tags question: http://stackoverflow.com/q/52714658
tags question: http://stackoverflow.com/q/52740374

http://stackoverflow.com/a/52673578
answers question: http://stackoverflow.com/q/52649815
type: Answer
upvote count: 1
score: 1
has body: Here are a fixed version of your code and a different method that is a bit faster. They give the same results so I'm reasonably confident they are correct: import numpy as np from scipy.spatial.distance import squareform, pdist, cdist from numpy.linalg import norm def pb_OP(A, p=1.0): distl = [] for *offs, ct in [(0, 0, 0), (0, p, 1), (p, 0, 1), (p, p, 1), (-p, p, 1)]: B = A - offs distl.append(cdist(B, A, metric='euclidean')) if ct: distl.append(distl[-1].T) return np.amin(np.dstack(distl), 2) def pb_pp(A, p=1.0): out = np.empty((2, A.shape[0]*(A.shape[0]-1)//2)) for o, i in zip(out, A.T): pdist(i[:, None], 'cityblock', out=o) out[out &gt; p/2] -= p return squareform(norm(out, axis=0)) test = np.random.random((1000, 2)) assert np.allclose(pb_OP(test), pb_pp(test)) from timeit import timeit t_OP = timeit(lambda: pb_OP(test), number=10)*100 t_pp = timeit(lambda: pb_pp(test), number=10)*100 print('OP', t_OP) print('pp', t_pp) Sample run. 1000 points: OP 210.11001259903423 pp 22.288734700123314 We see that my method is ~9x faster which by a neat coincidence is the number of offset cponfigurations OP's version has to check. It uses pdist on the individual coordinates to get absolute differences. Where these are larger than half the grid spacing we subtract one period. It remains to take Euclidean norm and to unpack storage.
downvote count: 0

http://stackoverflow.com/comment/92270263
has text: What's wrong with what you did? I don't know if their is other way than reinitializing it
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52670222
type: QuestionComment

http://stackoverflow.com/a/69449896
has body: I would suggest using G.subgraph(). Extract all the data from the graph with the nodes returned from the dfs tree, like so G.subgraph(nx.dfs_tree(G, 1).nodes()) This avoids the comprehension list of going through every node individually, and it automatically stores both node data and edge data, while add_nodes_from() only adds the node data of graph G
type: Answer
answers question: http://stackoverflow.com/q/52597599
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/a/52691416
answers question: http://stackoverflow.com/q/52691128
type: AcceptedAnswer
downvote count: 0
has body: You can use pd.pivot_table: res = df.pivot_table(index='ID', columns='Week/Year', aggfunc='count', fill_value=0) print(res) Timestamp Week/Year 41/2014 42/2014 ID 123 0 7 147 1 0 148 2 2 150 2 0 200 1 0 236 1 0 999 2 0
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/52691128

http://stackoverflow.com/q/52726337
has answer: http://stackoverflow.com/a/52726631
downvote count: 0
has answer: http://stackoverflow.com/a/52727490
accepted answer: http://stackoverflow.com/a/52727490
type: Question
has body: [MongoDB shell or pyMongo] I would like to know how to efficiently convert one record in a collection with an array in one field, to multiple records in say anew collection. So far, the only solution, I've been able to achieve is iterating the records one by one and then iterating the array in the field I want and do individual inserts. I'm hoping there's a more efficient way to do this. Example: I want to take a collection in MongoDB with structure similar to : [{ "_id": 1, "points": ["a", "b", "c"] }, { "_id": 2, "points": ["d"] }] and convert it to something like this: [{ "_id": 1, "points": "a" }, { "_id": 2, "points": "b" }, { "_id": 3, "points": "c" }, { "_id": 4, "points": "d" }]
upvote count: 2
tagged with: mongodb
answer count: 2
linked to: http://stackoverflow.com/q/39426022
has title: MongoDB - Convert One record with an array to multiple records in a new collection
favorite count: 0
possible better answer: http://stackoverflow.com/a/52726631
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52589404
has comment: http://stackoverflow.com/comment/92113920
tagged with: python
has answer: http://stackoverflow.com/a/52589593
score: 0
answer count: 2
tagged with: object
accepted answer: http://stackoverflow.com/a/52589593
type: AnsweredQuestion
tagged with: python-3.x
has title: Python 3.x - Object not available in class
tagged with: constructor
possible better answer: http://stackoverflow.com/a/52589553
type: Question
has body: I'm having an issue with classes and passing an object to a second class, in the code below , the line Class one logs correctly to a log file and in class two the line Class two print outputs on screen but when it gets to the logger line in class two's default constructor I get the error below and the second line isn't written to the log file. Note: logger is defined and works ok in class one. Error: NameError: name 'logger' is not defined Code: class one: logger = logger() logger.write("Class one") twoObj = two(logger) class two: print("Class two print") def __init__(self, logger): self.logger = logger logger.write("Class two")
has comment: http://stackoverflow.com/comment/92113693
has answer: http://stackoverflow.com/a/52589553
has comment: http://stackoverflow.com/comment/92113640

http://stackoverflow.com/q/52658767
has comment: http://stackoverflow.com/comment/92248109
has answer: http://stackoverflow.com/a/52658853
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52670460
tagged with: nested-lists
answer count: 5
type: UnansweredQuestion
has body: I want to convert my list of lists and within these lists there are list into only list of lists. For example: My code: a = [[], [], 'around_the_world', 'around_the_globe', [], [], [], []] aaa = len(a) aa = [[] for i in range(aaa)] for i, x in enumerate(a): if len(x) != 0: for xx in x: for xxx in xx: aa[i].append(xxx) print(aa) Currently: a = [[], [], 'around_the_world', 'around_the_globe', [], [], [], []] to expected: [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []] My current code works in finding the expected output. However, i have to use too many for loop and its too deep. Is there a shorter way to do so like just in one or 2 lines?
tagged with: python
linked to: http://stackoverflow.com/q/952914
score: 3
tagged with: list
has title: Converting list of lists / nested lists to list of lists without nesting
upvote count: 3
has answer: http://stackoverflow.com/a/52658842
has answer: http://stackoverflow.com/a/52658903
type: Question
has answer: http://stackoverflow.com/a/52658858

http://stackoverflow.com/a/52606364
upvote count: 2
has body: The desired element is a &lt;button&gt; tag within a Modal Dialog so to click on the desired element you need to induce WebDriverWait for the element to be clickable and you can use the following solutions: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC options = Options() options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe') driver.get("https://shopping.rochebros.com/shop/categories/37") WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='close' and @id='shopping-selector-parent-process-modal-close-click']"))).click()
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52598793
score: 2
answers question: http://stackoverflow.com/q/52598793

http://stackoverflow.com/comment/92277434
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52673400
has text: what is *method\_len*? Also you have `const char *method`. That means that the *method* contents is *const* and can't be modified. Something seems wrong. Check [\[SO\]: How to create a Minimal, Complete, and Verifiable example (mcve)](https://stackoverflow.com/help/mcve).

http://stackoverflow.com/q/52706538
has body: Communication between objects The idea is create a Toplevel window from Gui and after Toplevel closed send the data (name) from Toplevel Entry back to Gui How object app can know whether the toplev object was destroyed? or with other words How can object of Gui know that the object of My_Toplevel is closed? from tkinter import * font1 = font=("Open Sans Standard",16,"bold") class My_Toplevel(): def __init__(self, master=None): self.master = master self.toplev = Toplevel(master) self.name = None self.create_widgets() def create_widgets(self): self.entry_name = Entry(self.toplev, font=font1) self.button_ok = Button(self.toplev, text="Ok", font=font1, command=self.get_name) self.entry_name.pack() self.button_ok.pack() def get_name(self): self.name = self.entry_name.get() self.toplev.destroy() class Gui(Frame): def __init__(self, master): Frame.__init__(self, master) self.pack() self.master = master self.label_text = Label(self, text="Foo Bar Window", font=font1) self.label_text.pack() self.button_toplevel = Button(self, text="Create Toplevel", command=self.get_toplevel, font=font1) self.button_toplevel.pack() def get_toplevel(self): self.my_top = My_Toplevel(self) if __name__ == "__main__": root = Tk() root.title("Parent") app = Gui(root) root.mainloop()
favorite count: 0
tagged with: tkinter
tagged with: python
has title: Communication between python objects?
type: AnsweredQuestion
tagged with: oop
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/52706873
type: Question
has answer: http://stackoverflow.com/a/52706873
upvote count: 1
answer count: 1

http://stackoverflow.com/q/52716531
has body: Given the following code: from collections import deque import websockets import threading import asyncio # asyncio bugfix where CTRL+C won't exit when run_forever() import signal signal.signal(signal.SIGINT, signal.SIG_DFL) clients = set() queue = deque() async def handle_client(client, path): try: clients.add(client) async for buffer in client: queue.append(buffer) await client.send(buffer) finally: clients.remove(client) def start_loop(port): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(websockets.serve(handle_client, host='localhost', port=port)) loop.run_forever() def start(port=1234): threading.Thread(target=start, args=(port,)).start() By calling start() and interacting with the server, I expected that I'll be able to pull data from the queue and clients global variables, but they don't seem to be modified from within handle_client(). Why is that?
tagged with: python-asyncio
tagged with: python
favorite count: 0
answer count: 0
tagged with: python-multithreading
type: UnansweredQuestion
has title: global variables won't update from within asyncio loop inside thread
has comment: http://stackoverflow.com/comment/92365559
downvote count: 0
score: 1
type: Question
upvote count: 1

http://stackoverflow.com/a/52605988
accepted answer of: http://stackoverflow.com/q/52605852
answers question: http://stackoverflow.com/q/52605852
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92146309
score: 0
has comment: http://stackoverflow.com/comment/92146193
type: Answer
has body: This line is ambiguous: Transactions_Meat = Transactions[Transactions['Category'] == 'Meat'] If you want a copy, be explicit and use pd.DataFrame.copy: Transactions_Meat = Transactions[Transactions['Category'] == 'Meat'].copy() This should remove the subsequent warnings, as well as guarantee that you original Transactions dataframe will not be modified when you manipulate Transactions_Meat.

http://stackoverflow.com/a/52637312
upvote count: 1
answers question: http://stackoverflow.com/q/52637168
type: Answer
accepted answer of: http://stackoverflow.com/q/52637168
downvote count: 0
has body: You are using circular imports. There are tons of explanations on what it is, but you are importing the same module across multiple modules. One solution is to import the modules in the scope of the functions, instead of globally in the file, ie: def KeyHandle(): import main # Import here instead import pygame for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_UP: main.dire.append(3) if event.key == pygame.K_DOWN: main.dire.append(2) if event.type == pygame.KEYUP: if event.key == pygame.KEYUP: main.dire.remove(3) if event.key == pygame.K_DOWN: main.dire.remove(2)
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/52600209
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52599903
answers question: http://stackoverflow.com/q/52599903
has body: instead of explicitly iterating over the elements (or sub-arrays) of an array like for x in range(1, 12): print(np.max(npTrainingData[:x])) there are numpy functions, which can be controlled regarding on which axis they are applied. E.g. np.max: np.max(npTrainingData, 0) or equivalently npTrainingData.max(0) where the 0 here is the axis parameter, which can be 0 or 1 for 2D-arrays. When left blank, the maximum of the flattened array, i.e. a single value for the whole dataset is returned.
type: AcceptedAnswer
score: 4

http://stackoverflow.com/q/52673190
has comment: http://stackoverflow.com/comment/92276259
has title: Typing a date (element.send_keys) with Selenium/python/chromedriver, element.submit() crashes EMS web app
type: Question
has answer: http://stackoverflow.com/a/52674698
has comment: http://stackoverflow.com/comment/92276276
has body: There is a calendar on a website and with Selenium/Python/Chromedriver I'm trying to select a certain date in order to modify the schedule for a given day. time.sleep(5) inputElement = browser.find_element_by_xpath("//input[@type='text']") time.sleep(5) #I clear the date that is set before inputElement.send_keys("\b\b\b\b\b\b\b\b\b\b\b\b\b\b16/10/2018") time.sleep(5) inputElement.submit() The code is fine, but on the webpage I get this: EMS Web App is an application for a calendar, here the website: https://www.emssoftware.com/resources/ems-web-app-datasheet#! THIS IS NOT THE WEBSITE I'M TRYING TO USE BUT THE WEBSITE OF EMS WEB APP. I CANNOT GIVE THE RELEVANT WEBSITE BECASUE CREDENTIALS ARE NEEDED. Is there any chance that I can handle it with Selenium? Why this piece of the website behaves differently? I'm a newbie of Selenium and all this stuff.
has comment: http://stackoverflow.com/comment/92288086
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92278889
answer count: 1
has comment: http://stackoverflow.com/comment/92276280
tagged with: python
has comment: http://stackoverflow.com/comment/92276141
tagged with: selenium-chromedriver
score: 0
type: UnansweredQuestion
tagged with: selenium

http://stackoverflow.com/q/52668645
has body: I have a nested list that looks something like this: first_list = [[a, 1], [b, 3], [a, 6], [a, 2], [b, 4], [b, 5], ...] I want to group these by their first element, and create a new nested list that looks like: new_list = [ [1, 6, 2, ...], [3, 4, 5, ...], ...] where all of the elements that started with a go in the first sublist and so on. The number of different values a, b, etc. are not known before runtime, or I could do something like: a_list = [] b_list = [] for tag, x in first_list: if tag == a: a_list.append(x) elif tag == b: b_list.append(x) new_list = [a_list, b_list] I am struggling to adapt this for an arbitrary number of tags, however. I probably omitted an important part of the question, but I should say that I already have a list of "tags", i.e: tags = [a, b, c, d, ...] They are not actually characters, hence the lack of inverted commas, but they should be hashable in any case.
has answer: http://stackoverflow.com/a/52668689
has answer: http://stackoverflow.com/a/52668738
upvote count: 3
tagged with: grouping
tagged with: sublist
favorite count: 0
has answer: http://stackoverflow.com/a/52668871
has answer: http://stackoverflow.com/a/52668804
answer count: 5
downvote count: 2
tagged with: python
tagged with: dictionary
has title: Regroup sublists by first element in python
has comment: http://stackoverflow.com/comment/92267102
type: AnsweredQuestion
tagged with: list
score: 1
type: Question
possible better answer: http://stackoverflow.com/a/52668689
has answer: http://stackoverflow.com/a/52668722
accepted answer: http://stackoverflow.com/a/52668722
has comment: http://stackoverflow.com/comment/92267111

http://stackoverflow.com/a/52636316
has comment: http://stackoverflow.com/comment/92223835
accepted answer of: http://stackoverflow.com/q/52631869
type: Answer
answers question: http://stackoverflow.com/q/52631869
score: 2
upvote count: 2
has body: You can efficiently convert labels into a color image through Numpy's broadcasting like this clusters[labels]. Demo from skimage import io from sklearn.cluster import MiniBatchKMeans import numpy as np import matplotlib.pyplot as plt image = io.imread('https://i.sstatic.net/LkU1i.jpg') rows = image.shape[0] cols = image.shape[1] pixels = image.reshape(image.shape[0] * image.shape[1], image.shape[2]) kmeans = MiniBatchKMeans(n_clusters=128, n_init=10, max_iter=200) kmeans.fit(pixels) clusters = np.asarray(kmeans.cluster_centers_, dtype=np.uint8) labels = np.asarray(kmeans.labels_, dtype=np.uint8).reshape(rows, cols) colored = clusters[labels] d = {'Image': image, 'Labels': labels, 'Colored': colored} fig, ax = plt.subplots(1, 3) for i, name in enumerate(d): cmap = 'gray' if d[name].ndim == 2 else 'jet' ax[i].imshow(d[name], cmap=cmap) ax[i].axis('off') ax[i].set_title(name) plt.show(fig)
has comment: http://stackoverflow.com/comment/92226070
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52709542
has comment: http://stackoverflow.com/comment/92346037
has comment: http://stackoverflow.com/comment/92345934
has answer: http://stackoverflow.com/a/52711517
has answer: http://stackoverflow.com/a/52709802
score: 1
has body: I used to have a SQL query to count number of records for a given day, in a given location. Input Data structure was like this : id, location, start_date, end_date import pandas as pd data = [('20170009003','0681','2017-07-25','2017-08-02'), ('20170009221','0682','2017-07-28','2017-08-02'), ('20170009271','0682','2017-07-31','2017-08-02'), ('20170009286','0681','2017-07-18','2017-09-19'), ('20170009654','0682','2017-07-28','2017-08-03'), ('20170010053','0681','2017-07-31','2017-08-04'), ('20170010059','0681','2017-07-20','2017-08-07')] labels = ['idnum','loc','start_date','end_date'] df = pd.DataFrame.from_records(data, columns=labels) This would give me the count of (present) persons on a given day. i.e. the '2018-08-01', would get: 2018-08-01, 0681, 4 2018-08-01, 0682, 3 I'd like to produce a similar result with python/pandas. If it's of any help, the sql (postgreql function) used to achieve the above goal was : CREATE OR REPLACE FUNCTION nb_present(oneday date) RETURNS TABLE(ddj date, loc character, eff numeric) LANGUAGE sql AS $function$ SELECT $1, loc,sum(case when ($1= start_date and start_date_end_date) then 1 when $1=start_date then 0.5 when $1=end_date then 0.5 when ($1 &gt; start_date and $1 &lt; end_date) then 1 else 0 end) from passage group by 1,2 order by 1,2; $function$ Thanks for your help. PS: This is my first post here.
has comment: http://stackoverflow.com/comment/92345261
upvote count: 1
tagged with: date
type: Question
has comment: http://stackoverflow.com/comment/92345502
has answer: http://stackoverflow.com/a/52710005
has answer: http://stackoverflow.com/a/52709964
downvote count: 0
has comment: http://stackoverflow.com/comment/92345732
has comment: http://stackoverflow.com/comment/92345629
answer count: 6
has comment: http://stackoverflow.com/comment/92346009
has title: Count number of records for a given day
tagged with: pandas
tagged with: sql
has comment: http://stackoverflow.com/comment/92345326
has comment: http://stackoverflow.com/comment/92348473
has answer: http://stackoverflow.com/a/52727123
favorite count: 0
has answer: http://stackoverflow.com/a/52709613
type: UnansweredQuestion
tagged with: count
tagged with: python

big-o
tags question: http://stackoverflow.com/q/52718194
type: Tag
tags question: http://stackoverflow.com/q/52682861
tags question: http://stackoverflow.com/q/52684993
tag name: big-o
tags question: http://stackoverflow.com/q/52622629

heap-memory
tag name: heap-memory
type: Tag
tags question: http://stackoverflow.com/q/52617078
tags question: http://stackoverflow.com/q/52652887

http://stackoverflow.com/comment/92316609
score: 0
type: Comment
has text: I come from a C systems programming environment. With compute-intensive code, doing three checks is trivial if what comes next is multiplying two 100 x 100 matrices, or big convolutions with thousands of points. Better to weed out the user (and programmer) errors, since 99.999% of execution time is not in the redundant checks.
comment on: http://stackoverflow.com/a/52690944
type: AnswerComment

http://stackoverflow.com/q/52703694
tagged with: python
has answer: http://stackoverflow.com/a/52703962
has body: I have this small piece of code to scrape table data from a web site and then display in a csv format. The issue is that for loop is printing the records multiple time . I am not sure if it is due to tag. btw I am new to Python. Thanks for your help! #import needed libraries import urllib from bs4 import BeautifulSoup import requests import pandas as pd import csv import sys import re # read the data from a URL url = requests.get("https://www.top500.org/list/2018/06/") # parse the URL using Beauriful Soup soup = BeautifulSoup(url.content, 'html.parser') newtxt= "" for record in soup.find_all('tr'): tbltxt = "" for data in record.find_all('td'): tbltxt = tbltxt + "," + data.text newtxt= newtxt+ "\n" + tbltxt[1:] print(newtxt)
score: 1
upvote count: 1
has title: Beautiful Soup Scraping table
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52703961
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/a/52712479
answers question: http://stackoverflow.com/q/52712139
accepted answer of: http://stackoverflow.com/q/52712139
has body: copy makes a copy of the parent object only. It makes a new object that points to all the same attributes as the original object. deepcopy - 1) copies the original object, 2) then runs copy on each attribute pointed to, then makes copies of any attributes that those other copies point to etc.... In your case, since the attributes of your list are immutable, copy and deepcopy are interchangeable. if you have a list of lists, or list of lists of lists or ... then you use deepcopy. Here is a quick example of the difference: &gt;&gt;&gt; example = [[1, 2, 3], [4, 5, 6]] &gt;&gt;&gt; same_obj = example &gt;&gt;&gt; shallow_copy = copy(example) &gt;&gt;&gt; deep_copy = deepcopy(example) &gt;&gt;&gt; example.append([7, 8, 9]) &gt;&gt;&gt; print(example) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; print(same_obj) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; print(shallow_copy) [[1, 2, 3], [4, 5, 6]] &gt;&gt;&gt; example[0].sort(reverse=True) &gt;&gt;&gt; print(example) [[3, 2, 1], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; print(shallow_copy) [[3, 2, 1], [4, 5, 6]] &gt;&gt;&gt; print(deep_copy) [[1, 2, 3], [4, 5, 6]] shallow_copy and example are two different objects. They have indexes which point to other objects (in this case, lists). These indexes are all pointing to the same objects, so if you mutate the object that either list points to, the mutation shows up in both lists. deepcopy, not only copied the parent list, but also copied each list that the parent list pointed to. so any changes to a sub-list did not affect deep_copy in any way.
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/52723551
type: Answer
has comment: http://stackoverflow.com/comment/92375708
has comment: http://stackoverflow.com/comment/92375599
score: 4
upvote count: 4
has body: Yes, you normally use the connection.start_transaction() method to start a transaction when the autocommit feature is enabled. Since MySQL Connector/Python is Python DB API-compliant, autocommit is disabled by default and the first SQL statement will implicitly begin a transaction. You must call connection.commit to commit the transaction.
downvote count: 0
answers question: http://stackoverflow.com/q/52723251

http://stackoverflow.com/a/52592108
answers question: http://stackoverflow.com/q/52591696
has comment: http://stackoverflow.com/comment/92124620
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92118958
has comment: http://stackoverflow.com/comment/92118830
score: 2
upvote count: 2
has body: Method 2 also works. Since Python 3.6 it remembers the order it is created too.
has comment: http://stackoverflow.com/comment/92126071

http://stackoverflow.com/a/52607984
score: 3
has body: You can do it with recursion, but the time complexity wont change... Something like this: def method(n, size): if n == 0: return; for i in range(size,0,-1): print(str(i)*n,sep='',end='') print() method(n-1, size) method(3, 3)
downvote count: 0
answers question: http://stackoverflow.com/q/52607849
type: Answer
upvote count: 3

http://stackoverflow.com/q/52669755
has comment: http://stackoverflow.com/comment/92269742
has title: Newton method for transcendental equation
tagged with: python
has comment: http://stackoverflow.com/comment/92270606
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92269860
tagged with: math
has comment: http://stackoverflow.com/comment/92271510
has comment: http://stackoverflow.com/comment/92271095
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92270795
has body: Transcendental equation: tan(x)/x + b = 0, where b is any real number. I need to introduce n and give me n solutions of this equation. My code (Python): from math import tan, cos, pi, sqrt, sin,exp import numpy as np from matplotlib.figure import Figure import matplotlib.pyplot as plt def f(x,b): return tan(x)/x + b def f1(x,b): return (x/(cos(x)*cos(x)) - tan(x))/(x**2) e = 0.00000000001 def newtons_method(x0, f, f1, e): x0 = float(x0) while True: x1 = x0 - (f(x0,b) / f1(x0,b)) if abs(x1 - x0) &lt; e: return x1 x0 = x1 result = [] n = int(input("Input n: ")) b = float(input("Input b: ")) for i in range(2,4*n,1): result.append(newtons_method(i, f , f1, e)) lambda_result = sorted(list(set(result))) print(len(lambda_result)) I change the initial approximation with step 1.The roots are repeated with a period of ~pi, so the second argument 4*n. I exclude repeated solutions through set. If n is 50 then he finds only 18 solution. What needs to be fixed to make it work? Help me, please.
has comment: http://stackoverflow.com/comment/92270610
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/52671224
tagged with: numerical-methods
answer count: 1
has comment: http://stackoverflow.com/comment/92269891
accepted answer: http://stackoverflow.com/a/52671224
favorite count: 0
has comment: http://stackoverflow.com/comment/92271222

http://stackoverflow.com/q/52666957
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52771621
tagged with: metaclass
linked to: http://stackoverflow.com/q/5189699
score: 0
has comment: http://stackoverflow.com/comment/92271579
type: Question
tagged with: python-2.7
has title: How can we mutate attributes on basis of attributes passed at init in metaclass
answer count: 1
has body: say i have a class which takes a attribute called bucket_name, on basis of this bucket i want to set an attribute bucket_path for class which is of kind bucket_path = "{bucket_name}_created".format(bucket_path='master-bucket') I am trying to use metaclass for it which is like this: class MyMeta(type): def __new__(meta, klassname, bases, attrs): # trying to get bucket_name here from attrs but attrs is {} return type.__new__(meta, klassname, bases, attrs) class M(object): __metaclass__= MyMeta def __init__(self, bucket_name): self.bucket_name = bucket_name but i am failing because attrs is empty when i do m = M('my_bucket_name'), how to go about it?

http://stackoverflow.com/comment/92264944
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52664080
has text: Update the question with your _code trials_ and _relevant error_ you are seeing

http://stackoverflow.com/a/52622828
downvote count: 0
has body: Importing a package does not automatically import all its submodules, so import package1 is not necessarily enough to access package1.module1. Try: import package1.module1 You can also do: from package1 import module1 def main(): module1.main() or from package1.module1 import main def my_main(): # names of mains must be different main()
has comment: http://stackoverflow.com/comment/92182946
upvote count: 3
answers question: http://stackoverflow.com/q/52622764
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52622764
type: Answer
has comment: http://stackoverflow.com/comment/92182167
score: 3

http://stackoverflow.com/comment/92338612
type: QuestionComment
score: 1
has text: Did you try : img.rotate(angle, resample=Image.BICUBIC, expand=True). https://stackoverflow.com/questions/17821945/how-to-preserve-image-quality-when-rotating-with-pil
comment on: http://stackoverflow.com/q/52705237
type: Comment

http://stackoverflow.com/comment/92404443
type: Comment
type: QuestionComment
has text: Please show us a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve).
score: 0
comment on: http://stackoverflow.com/q/52739619

http://stackoverflow.com/comment/92201467
type: QuestionComment
has text: I'm not getting an error, the conditional is getting "false" even if the content of the fields are the same
comment on: http://stackoverflow.com/q/52619472
score: 0
type: Comment

http://stackoverflow.com/a/52731401
downvote count: 0
has body: If you cannot accept the lingering comma even if it is standard, you will only make it more complicated. tuple accepts a iterable object and convert it into a tuple. So you can accomplish what you need by tuple([possible_none_object]). But isn't is more awkward? Rudendant brackets and an additionally created list. Or you can make it even more complicated by using a decorator which hides that lingering comma for you: def ensure_tuple(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if not isinstance(result, tuple): return (result,) return result return wrapper
answers question: http://stackoverflow.com/q/52731195
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/52713587
favorite count: 0
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/52713642
type: AnsweredQuestion
tagged with: odoo-11
has comment: http://stackoverflow.com/comment/92352797
has title: How to convert string into datetime in Python
possible better answer: http://stackoverflow.com/a/52713642
downvote count: 1
has comment: http://stackoverflow.com/comment/92352781
type: Question
has comment: http://stackoverflow.com/comment/92352872
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/52713610
answer count: 2
accepted answer: http://stackoverflow.com/a/52713610
has body: i have concatenated date(date field) time(float) date_time_to(Char) i am getting output in this format "2018-10-09 20.00". I need output in this format '%m/%d/%Y %H:%M:%S' I used "obj.date_time_to = datetime.strptime(self.date_time_to, "%m/%d/%Y %H:%M:%S.%f")" i am getting ValueError: time data '2018-10-09 20.00' does not match format '%m/%d/%Y %H:%M:%S.%f'

http://stackoverflow.com/q/52597611
type: Question
has answer: http://stackoverflow.com/a/52598420
has title: How to tell Python's ldap3 module to TLS version 1.2 explicitly?
has body: I am attempting to use the ldap3 Python module to authenticate to ldap, but I'm wanting to verify if my connection is using TLS version 1.2. Relevant code snippet: tls = Tls(validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1_2) server = Server(server_uri, use_ssl=True, tls=tls, get_info=ALL) conn = Connection(server, user="domain\\myusername", password="password", authentication=NTLM, auto_referrals=False) conn.bind() Output of my Connection object: Connection(server=Server( host='domain.host.com', port=636, use_ssl=True, allowed_referral_hosts=[('*', True)], tls=Tls(validate=&lt;VerifyMode.CERT_REQUIRED: 2&gt;, version=&lt;_SSLMethod.PROTOCOL_TLSv1_2: 5&gt;), get_info='ALL', mode='IP_V6_PREFERRED'), version=3, authentication='NTLM', client_strategy='SYNC', ...truncated...) I'm not sure what the "5" means in the version property, but ultimately I'm trying to validate if I'm authenticating using TLS version 1.2 or not.
score: 0
tagged with: ldap3
answer count: 1
accepted answer: http://stackoverflow.com/a/52598420
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52666071
has body: You could just locate your 17 length rows as following condition = (df["vin"].str.len() == 17) print(df[condition])
answers question: http://stackoverflow.com/q/52665955
score: 0
has comment: http://stackoverflow.com/comment/92262050
has comment: http://stackoverflow.com/comment/92261985
type: Answer

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/52739311
tags question: http://stackoverflow.com/q/52616591
tags question: http://stackoverflow.com/q/52597841
tags question: http://stackoverflow.com/q/52728997
tags question: http://stackoverflow.com/q/52736009
tags question: http://stackoverflow.com/q/52636846
tags question: http://stackoverflow.com/q/52699945
tags question: http://stackoverflow.com/q/52733830
tags question: http://stackoverflow.com/q/52641515
tags question: http://stackoverflow.com/q/52712421
tags question: http://stackoverflow.com/q/52729786
tags question: http://stackoverflow.com/q/52741226
tags question: http://stackoverflow.com/q/52613196
tags question: http://stackoverflow.com/q/52694786
tags question: http://stackoverflow.com/q/52662585
tags question: http://stackoverflow.com/q/52677078
tags question: http://stackoverflow.com/q/52609285
tags question: http://stackoverflow.com/q/52612021
tags question: http://stackoverflow.com/q/52703848
tags question: http://stackoverflow.com/q/52675556
tags question: http://stackoverflow.com/q/52664136
tags question: http://stackoverflow.com/q/52636795
tags question: http://stackoverflow.com/q/52685754
tags question: http://stackoverflow.com/q/52745237
tags question: http://stackoverflow.com/q/52733545
tags question: http://stackoverflow.com/q/52609495
tags question: http://stackoverflow.com/q/52684858
tags question: http://stackoverflow.com/q/52666528
type: Tag
tags question: http://stackoverflow.com/q/52629888
tags question: http://stackoverflow.com/q/52626780
tags question: http://stackoverflow.com/q/52698573
tags question: http://stackoverflow.com/q/52738256
tags question: http://stackoverflow.com/q/52646004
tags question: http://stackoverflow.com/q/52588722
tags question: http://stackoverflow.com/q/52654327
tags question: http://stackoverflow.com/q/52730953
tags question: http://stackoverflow.com/q/52712825
tags question: http://stackoverflow.com/q/52706597
tags question: http://stackoverflow.com/q/52672598
tags question: http://stackoverflow.com/q/52690078
tags question: http://stackoverflow.com/q/52606733
tags question: http://stackoverflow.com/q/52604788
tags question: http://stackoverflow.com/q/52721643
tags question: http://stackoverflow.com/q/52654282
tags question: http://stackoverflow.com/q/52645142
tags question: http://stackoverflow.com/q/52635681
tags question: http://stackoverflow.com/q/52745335
tag name: json
tags question: http://stackoverflow.com/q/52716267
tags question: http://stackoverflow.com/q/52684828
tags question: http://stackoverflow.com/q/52633468
tags question: http://stackoverflow.com/q/52616351
tags question: http://stackoverflow.com/q/52726927
tags question: http://stackoverflow.com/q/52662009
tags question: http://stackoverflow.com/q/52689411
tags question: http://stackoverflow.com/q/52680236
tags question: http://stackoverflow.com/q/52644377
tags question: http://stackoverflow.com/q/52652522
tags question: http://stackoverflow.com/q/52696432
tags question: http://stackoverflow.com/q/52712674
tags question: http://stackoverflow.com/q/52601472
tags question: http://stackoverflow.com/q/52678387
tags question: http://stackoverflow.com/q/52647131
tags question: http://stackoverflow.com/q/52595408
tags question: http://stackoverflow.com/q/52665479
tags question: http://stackoverflow.com/q/52663218
tags question: http://stackoverflow.com/q/52735322
tags question: http://stackoverflow.com/q/52726991
tags question: http://stackoverflow.com/q/52599466
tags question: http://stackoverflow.com/q/52648306
tags question: http://stackoverflow.com/q/52602917
tags question: http://stackoverflow.com/q/52693854
tags question: http://stackoverflow.com/q/52638991
tags question: http://stackoverflow.com/q/52594179
tags question: http://stackoverflow.com/q/52720552
tags question: http://stackoverflow.com/q/52650006
tags question: http://stackoverflow.com/q/52708568

http://stackoverflow.com/comment/92271149
type: QuestionComment
has text: What is `for value in type` doing here?
comment on: http://stackoverflow.com/q/52670717
score: 0
type: Comment

http://stackoverflow.com/a/52656080
type: Answer
answers question: http://stackoverflow.com/q/52656025
has body: A dictionary of lists might be appropriate, mapping letters to a list of indices: s = "abcabcdefdefjhi" indices = {} for i, l in enumerate(s): if l not in indices: indices[l] = [] indices[l].append(i) for k, v in indices.items(): print("{}: {}".format(k, str(v)[1:-1])) Output: a: 0, 3 b: 1, 4 c: 2, 5 d: 6, 9 e: 7, 10 f: 8, 11 j: 12 h: 13 i: 14 Or, testing with "لوحة المفاتيح ال": ل: 0, 6, 15 و: 1 ح: 2, 12 ة: 3 : 4, 13 ا: 5, 9, 14 م: 7 ف: 8 ت: 10 ي: 11 Try it.
score: 0

http://stackoverflow.com/a/52652601
score: 3
upvote count: 3
has body: A common strategy is to create an invisible widget (eg: a 1x1 frame in the corner of the window), and do a grab (ie: call grab_set) on that widget. That causes all events to be funneled to that widget. As long as there are no bindings on that window, the net effect is that the events get ignored. You just need to flush the event queue (call the update method) before removing the grab.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52649477

http://stackoverflow.com/q/52631700
upvote count: 1
downvote count: 1
has title: Trying to create a python dictionary for 4x4 board coordinates
favorite count: 0
has answer: http://stackoverflow.com/a/52632733
has comment: http://stackoverflow.com/comment/92197162
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/52631785
has comment: http://stackoverflow.com/comment/92196658
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52632733
has comment: http://stackoverflow.com/comment/92196810
has answer: http://stackoverflow.com/a/52631785
type: Question
has body: I want the desired output as- coord = {0: (0, 0), 1: (0, 1), 2: (0, 2), 3: (0, 3), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (1, 3),8: (2, 0), 9: (2, 1), 10: (2, 2), 11: (2, 3),12: (3, 0), 13: (3, 1), 14: (3, 2), 15: (3, 3)} using coord = {} for i in range(0,16): if i &lt; 4: for j in range (0,4): coord[i] = (0,j) elif i &gt; 3 and i &lt;8: for j in range (0,4): coord[i] = (1,j) elif i &gt; 7 and i &lt; 12: for j in range (0,4): coord[i] = (1,j) elif i &gt; 11 and i &lt; 16: for j in range (0,4): coord[i] = (1,j) print (coord) getting the output as {0: (0, 3), 1: (0, 3), 2: (0, 3), 3: (0, 3), 4: (1, 3), 5: (1, 3), 6: (1, 3), 7: (1, 3), 8: (1, 3), 9: (1, 3), 10: (1, 3), 11: (1, 3), 12: (1, 3), 13: (1, 3), 14: (1, 3), 15: (1, 3)} not able to build the logic to get desired output.
has comment: http://stackoverflow.com/comment/92196733
has comment: http://stackoverflow.com/comment/92197649
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92196937

mpi
tags question: http://stackoverflow.com/q/52589839
tag name: mpi
type: Tag
tags question: http://stackoverflow.com/q/52657173

http://stackoverflow.com/q/52613383
upvote count: 5
tagged with: gpu
type: UnansweredQuestion
tagged with: python
downvote count: 0
tagged with: pytorch
tagged with: cpu
type: Question
has answer: http://stackoverflow.com/a/52664444
score: 5
has body: The Migration guide recommends the following to make code CPU/GPU agnostic: &gt; # at beginning of the script device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") ... # then whenever you get a new Tensor or Module # this won't copy if they are already on the desired device input = data.to(device) model = MyModule(...).to(device) I did this and ran my code on a CPU-only device, but my model crashed when fed an input array, as saying it was expecting a CPU tensor not a GPU one. Somehow my model was automatically converting the a CPU-input array to a GPU array. Finally I traced it down to this command in my code: model = torch.nn.DataParallel(model).to(device) Even though I convert the model to 'cpu', the nn.DataParallel overrides this. The best solution I came up with was a conditional: if device.type=='cpu': model = model.to(device) else: model = torch.nn.DataParallel(model).to(device) This does not seem elegant. Is there a better way?
answer count: 1
favorite count: 0
has title: A better way to make pytorch code agnostic to running on a CPU or GPU?

http://stackoverflow.com/a/52657290
score: 0
has comment: http://stackoverflow.com/comment/92246482
has comment: http://stackoverflow.com/comment/92247167
answers question: http://stackoverflow.com/q/52656417
has body: Scripts are generally used for these kinds of tasks. You have a monitor script that keeps track of update.py that keeps running in the background. It becomes easier if monitor script launches the python script in the beginning. #!/bin/bash # Monitor script. EXEC=&lt;path&gt;/update.py while true; do "$EXEC" &amp; wait # Here the assumption is that you want to run this forever. done
type: Answer
has comment: http://stackoverflow.com/comment/92246310

http://stackoverflow.com/comment/92419056
has text: @eyllanesc, I updated the question with what versions I'm using. Can you share yours?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52745343
type: Comment

http://stackoverflow.com/comment/92208277
type: Comment
comment on: http://stackoverflow.com/a/52637624
type: AnswerComment
has text: I'm using python3.4 is string format supported in that version?
score: 0

http://stackoverflow.com/q/52704750
favorite count: 0
has comment: http://stackoverflow.com/comment/92336361
has answer: http://stackoverflow.com/a/52706638
has comment: http://stackoverflow.com/comment/92336065
has body: import pprint def print_values(key): pprint.pprint(key, width=1) I tried this, but it ends up printing both the keys and values. I only want the set to print the values, not the keys.
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92337013
downvote count: 1
has comment: http://stackoverflow.com/comment/92336187
has title: How do I add newline to only dictionary values?
type: Question
score: 0
answer count: 1

http://stackoverflow.com/a/52636912
answers question: http://stackoverflow.com/q/52636686
type: Answer
has body: Thanks to Employee and Canh! Working proof of concept: Terminal: &gt;python -m PyInstaller --noconsole --name WorkLogger ../WorkLogger/main.py Python script: subprocess.call(r"python -m PyInstaller --noconsole --name WorkLogger F:\KivyApps\WorkLogger\main.py") If needed, you can start the subprocess from a specific working directory: subprocess.call(r"python -m PyInstaller --noconsole --name WorkLogger F:\KivyApps\WorkLogger\main.py", cwd=r"F:\KivyApps\WorkLogger_Dist")
downvote count: 0
score: 5
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52636686
upvote count: 5

http://stackoverflow.com/a/52728611
has body: Just add a count into your if/else branches success = 0 failure = 0 for i in range (len(list_password)) : if final_password (list_password[i]) == list_result[i] : success += 1 print(list_password[i]+"-----SUCCESS") else : failure += 1 print(list_password[i]+"-----FAILURE") print('Successes: {} Failures: {}'.format(success, failure))
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/92382589
answers question: http://stackoverflow.com/q/52728522
score: 2
downvote count: 0

http://stackoverflow.com/a/52700149
answers question: http://stackoverflow.com/q/52699932
downvote count: 0
has body: You can use the POSTGRES_DB environment variable. From Postgres docker image docs: POSTGRES_DB This optional environment variable can be used to define a different name for the default database that is created when the image is first started. If it is not specified, then the value of POSTGRES_USER will be used. The docker-compose.yml file would be: version: '3' services: db: image: postgres env: POSTGRES_DB: &lt;DATABASE NAME&gt; web: build: . command: bash -c "python manage.py makemigrations &amp;&amp; python manage.py migrate &amp;&amp; python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '&lt;DATABASE NAME&gt;', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } }
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/92356140
score: 2
has comment: http://stackoverflow.com/comment/92352315

http://stackoverflow.com/comment/92127270
type: AnswerComment
type: Comment
has text: The mode is very noise-sensitive. I like the segmentation approach, but you could also think about some edge-preserving smoothing (e.g. a bilateral filter) to make sure that neighboring pixels with similar value become pixels with identical value, and hence contribute to the same dictionary entry and have a chance to build up a higher peak. Some form of discretization of pixel values is also possible.
comment on: http://stackoverflow.com/a/52592707
score: 1

http://stackoverflow.com/comment/93665847
type: Comment
has text: I wonder who thought that removing code from the question was funny.
comment on: http://stackoverflow.com/q/52736840
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92379020
score: 0
has text: How do i do this?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52726818

http://stackoverflow.com/comment/92360586
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52707546
has text: In response to your comment about the apparent contradiction between wanting a task to happen asynchronously as well as immediately, in my case there may be an urgent API request, for example to cancel a trade. It is desirable to send the http request asap. The confirmation response form the exchange is of lower priority than other existing tasks in the event loop, so yielding after the http request is sent is absolutely fine. The ability to force a new task to the front of the event loop would be beneficial in this situation.
type: AnswerComment

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/52641802
tags question: http://stackoverflow.com/q/52716843
type: Tag

http://stackoverflow.com/comment/92375903
score: 1
comment on: http://stackoverflow.com/q/52721099
type: Comment
type: QuestionComment
has text: Please [edit] and put it in the question. And yes, this has nothing to do with conda. Why do you suspect conda is the problem?

http://stackoverflow.com/q/52686891
upvote count: 3
has comment: http://stackoverflow.com/comment/92301004
linked to: http://stackoverflow.com/q/6285327
tagged with: python
favorite count: 0
tagged with: python-3.x
tagged with: django-templates
linked to: http://stackoverflow.com/q/8659560
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92301052
tagged with: django
has comment: http://stackoverflow.com/comment/92301054
has title: Counter increment in template outside of for loop
score: 3
has body: I need to do a counter increment within a loop. I had a look at django for.counter, but unfortunately, my increments dont exactly occur within each iteration of the loop. So is there any way at all that I can implement increment of a variable within django template, without going to great pains to implement a new object in my code to do this without such an increment? In the following code, I am writing the lines {{ count = 0 }}, {{ count += 1 }} just for illustration purpose. I know it wont work. The following is a very simplified form of my template: Headertext {% if weeklyslotsav %} {% for day,daynum in weekzip %} {{ count = 0 }} {% if daynum in weeklyslotsav.day %} {% for weekslotav in weeklyslotsav %} {% if weekslotav.day == daynum %} {{ count += 1 }} {% endif} {% endfor %} {% else %} {% endif %} {% endfor %} {% else %} {% for weekday, weeknum in weekzip %} {% endfor %} {% endif %} The following is a segment from my views: def edit_doctorslots(request, cliniclabel, doctor_id): doctor_id=int(doctor_id) doc = get_object_or_404(doctor, docid=doctor_id) cl = Clinic.objects.get(label=cliniclabel) print("Clinic name", cl.name) regularslotsav = '' try: regularslotsav = Timeslots.objects.filter(clinic =cl, doctor =doc, available =True) except: pass regularslotsbr = '' try: regularslotsbr = Timeslots.objects.filter(clinic =cl, doctor =doc, available =False) except: pass weekavzip = '' try: weeklyslotsav = Weekdays.objects.filter(clinic =cl, doctor =doc, available =True) weekav = range(0, len(weeklyslotsav)) weekavzip = list(zip(weeklyslotsav, weekav)) except: pass weeklyslotsbr = '' try: weeklyslotsbr = Weekdays.objects.filter(clinic =cl, doctor =doc, available =False) except: pass formslot = SlotForm() formspecialdays = SpecialdaysForm() formweekdays = WeekdaysForm() weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] weekdaynum = [0,1,2,3,4,5,6] weekzip = list(zip(weekdays, weekdaynum)) newweekzip = weekzip return render(request, …
has comment: http://stackoverflow.com/comment/92301040
linked to: http://stackoverflow.com/q/1070398
has comment: http://stackoverflow.com/comment/92301145
type: Question
has comment: http://stackoverflow.com/comment/92301044
answer count: 1
has answer: http://stackoverflow.com/a/52691612

http://stackoverflow.com/a/52730415
downvote count: 0
has comment: http://stackoverflow.com/comment/92386130
type: Answer
accepted answer of: http://stackoverflow.com/q/52730272
score: 1
has body: There's a shorter way to do this with the all funtion. listt = ['big', 'letters'] links_set = set(['hello', 'hi', 'big', 'cccc', 'letters', 'anotherword']) all_are_present = all([word in links_set for word in listt]) # True Edit I think what you were trying to do was check if each word in listt was in the text string of all html elements, in which case this would be: listt = ['big', 'letters'] links_text_list = ['hello letters', 'big hi letters', 'big superman letters'] all_are_present = all([word in text for word in listt for text in links_text_list]) # False because "hello letters" doesn't have big But since you only want those links that have all words in listt present, you can use the filter function. links_with_all_words = list(filter(lambda text: all([word in text for word in listt]), links_text_list)) print(links_with_all_words) # ['big hi letters', 'big superman letters']
has comment: http://stackoverflow.com/comment/92386587
upvote count: 1
answers question: http://stackoverflow.com/q/52730272
type: AcceptedAnswer

http://stackoverflow.com/q/52736851
has answer: http://stackoverflow.com/a/52739081
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/52737184
accepted answer: http://stackoverflow.com/a/52739081
has title: scapy "TypeError: 'IP' object is not callable"
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: in my Scapy Script I get an Error, I cannot find a reason for. #!/usr/bin/python from scapy.all import * from settings import * #Create Layer-2 Frame. l2 = Ether( dst=dst, src=src, type=2048) #dst and src from settings pkt = IP(dst=dst)/ICMP(type=8)/Raw(load=("X"*10000)) #Create some big pings: for i in range(10000,10020): frags = fragment(pkt) #create Fragments for fragment in frags: sendp(l2/fragment, iface=iface) print("i: " + str(i)) Scapy sends one whole packet and after that, I become the error message: TypeError: 'IP' object is not callable Can someone please tell me how to fix this?
score: 1
tagged with: scapy
has answer: http://stackoverflow.com/a/52737184
tagged with: ip
type: Question

http://stackoverflow.com/comment/92310112
type: QuestionComment
comment on: http://stackoverflow.com/q/52690529
score: 0
has text: Looking to find the top 2 principal components for PCA
type: Comment

http://stackoverflow.com/q/52603661
has comment: http://stackoverflow.com/comment/92142188
has answer: http://stackoverflow.com/a/52603727
has answer: http://stackoverflow.com/a/52603740
upvote count: 2
answer count: 2
has body: I have a file that looks like so: The file is comma-separated...however, the comma is also used for commas in digits. the good thing is that i only need to remove a comma that sits between 2 numbers: a,b,100,000.00,2018-01-01,c c,d,20,000.0,2017-12-01,e e,f,1,000,000.00,2015-11-10,g and convert this to: a,b,100000.00,2018-01-01,c c,d,20000.0,2017-12-01,e e,f,1000000.00,2015-11-10,g i was thinking of using (?&lt;=\d),(?=\d+\.\d+) but this only takes care of the comma at the (1000) place but not the (1000000) place. Is there a way to do this recursively? Alternatively I can call this subsitution twice.
downvote count: 0
has comment: http://stackoverflow.com/comment/92141517
favorite count: 0
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/52603727
possible better answer: http://stackoverflow.com/a/52603740
has comment: http://stackoverflow.com/comment/92141494
has title: Replacing comma for numerics in csv file
has comment: http://stackoverflow.com/comment/92141700
has comment: http://stackoverflow.com/comment/92141660
type: Question

http://stackoverflow.com/a/52714735
answers question: http://stackoverflow.com/q/52713809
has body: You have the following errors: scrollArea is a widget that is not part of the w widget, so it will not show, so there are 2 possible solutions: make it son of w and resize its size manually, or use a layout, in this case use the second. When you read a file with f.read() you delete it from the buffer f, that is, if you call f.read() it will not return anything since the cursor is at the end of the file, so it is printed on the console but it will not show up in the QTextEdit. You have some typographical errors. Considering the above, the solution is as follows: import sys from PyQt4 import QtGui if __name__ == '__main__': a = QtGui.QApplication(sys.argv) w = QtGui.QWidget() lay = QtGui.QVBoxLayout(w) scrollArea = QtGui.QScrollArea(widgetResizable=True) lay.addWidget(scrollArea) textEdit = QtGui.QTextEdit() scrollArea.setWidget(textEdit) filename = QtGui.QFileDialog.getOpenFileName(w, 'Open File', '/') if filename: with open(filename, 'r') as f: textEdit.setText(f.read()) w.resize(320, 240) w.show() sys.exit(a.exec_())
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92375835
upvote count: 1
has comment: http://stackoverflow.com/comment/92376047
type: Answer
has comment: http://stackoverflow.com/comment/92375661
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52713809

http://stackoverflow.com/comment/92247404
type: AnswerComment
type: Comment
has text: user.status.id does the trick. FINALLY found it, thanks to you! ty!
comment on: http://stackoverflow.com/a/52657911
score: 0

http://stackoverflow.com/comment/92360237
score: 0
comment on: http://stackoverflow.com/q/52717235
has text: @roganjosh, ahh!! Got it, I see what's going on here, thanks :)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/112678389
type: AnswerComment
type: Comment
has text: Hey @BjornW, so yes things have changed since this answer was posted. Why don't you edit it and provide the correct syntax. Thanks for pointing it out.
comment on: http://stackoverflow.com/a/52734173
score: 0

http://stackoverflow.com/comment/92206919
type: AnswerComment
comment on: http://stackoverflow.com/a/52636628
type: Comment
has text: this helps you? https://stackoverflow.com/questions/40880259/how-to-pass-arguments-in-pytest-by-command-line
score: 0

http://stackoverflow.com/comment/135870914
comment on: http://stackoverflow.com/q/52696198
type: QuestionComment
score: 0
type: Comment
has text: Do not include solution to question please (post a separate answer instead).

screen-scraping
tags question: http://stackoverflow.com/q/52726818
tags question: http://stackoverflow.com/q/52678883
tags question: http://stackoverflow.com/q/52703128
tags question: http://stackoverflow.com/q/52627863
type: Tag
tags question: http://stackoverflow.com/q/52667641
tag name: screen-scraping
tags question: http://stackoverflow.com/q/52690615

http://stackoverflow.com/q/52715005
type: Question
upvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/52715328
possible better answer: http://stackoverflow.com/a/63447925
has comment: http://stackoverflow.com/comment/92355948
downvote count: 0
tagged with: django-rest-framework
score: 4
favorite count: 0
tagged with: python
has title: Atomic transactions in DRF action?
has answer: http://stackoverflow.com/a/52715328
tagged with: django
has body: I am trying to get into Django atomic transactions at first time. I wonder if there is a possibility to use it something like this: class TaskViewSet(MultiSerializerViewSet): @transaction.atomic @action(methods=['PATCH'], detail=True) def move_task(self, request, pk): # making queries, trying to update them, roll back if last one fails. return Response("message: SUCCESS", status=_status.HTTP_200_OK) I have searched a bit - there is some information about how to use transactions but I did not find any info if it is possible to use them with DRF.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63447925

http://stackoverflow.com/q/52691931
tagged with: python
answer count: 3
downvote count: 1
accepted answer: http://stackoverflow.com/a/52692420
upvote count: 4
has title: Simple way to test websocket availability in python
type: AnsweredQuestion
score: 3
tagged with: websocket
possible better answer: http://stackoverflow.com/a/52692134
favorite count: 0
has body: I am using the following code to test that a local websocket server is running: import asyncio import websockets async def hello(): async with websockets.connect('ws://127.0.0.1:8000/ws/registration/123') as websocket: await websocket.send(json_data) asyncio.get_event_loop().run_until_complete(hello()) Is there a simpler way to do this without using asyncio? Something such as: import asyncio import websockets conn = websockets.connect('ws://127.0.0.1:8000/ws/registration/123') conn.send('hello') Basically, I'm just trying to find the simplest way to test to see if my websocket server is listening and receiving messages at a particular url.
has answer: http://stackoverflow.com/a/75619170
has answer: http://stackoverflow.com/a/52692134
type: Question
has answer: http://stackoverflow.com/a/52692420

http://stackoverflow.com/comment/92434920
score: 0
type: Comment
type: QuestionComment
has text: You should probably create separare questions for installing it on windows, and installing it on NAO ...
comment on: http://stackoverflow.com/q/52717364

http://stackoverflow.com/q/52616553
favorite count: 0
tagged with: python-3.x
tagged with: pyqt5
possible better answer: http://stackoverflow.com/a/52616955
tagged with: qlabel
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52617980
has answer: http://stackoverflow.com/a/52616955
type: Question
upvote count: 4
has title: PyQt5 Image and QGridlayout
answer count: 2
tagged with: pyqt
downvote count: 0
score: 4
has body: I've a Widget, which wants to display Images with QLabel and QCheckBox. 4 classes are created each contains some information to be put on the final screen. Class Grid align and grid images, text and checkboxes. After script running get current screen. No images appear in present widget. Where are images? Desired screen The code import sys, os from PyQt5 import QtCore, QtGui, QtWidgets iconroot = os.path.dirname(__file__) class ImageWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(ImageWidget, self).__init__(parent) self.hlay = QtWidgets.QHBoxLayout(self) buckling_ilabel = QtWidgets.QLabel(self) pixmap = QtGui.QPixmap(os.path.join(iconroot, "images/fixed-fixed.png")) buckling_ilabel.resize(150, 150) buckling_ilabel.setPixmap(pixmap.scaled(buckling_ilabel.size(), QtCore.Qt.KeepAspectRatio)) self.hlay.addWidget(buckling_ilabel) buckling_blabel = QtWidgets.QLabel(self) pixmap = QtGui.QPixmap(os.path.join(iconroot, "images/pinned-pinned.png")) buckling_blabel.resize(150, 150) buckling_blabel.setPixmap(pixmap.scaled(buckling_blabel.size(), QtCore.Qt.KeepAspectRatio)) self.hlay.addWidget(buckling_blabel) buckling_clabel = QtWidgets.QLabel(self) pixmap = QtGui.QPixmap(os.path.join(iconroot, "images/fixed-free.png")) buckling_clabel.resize(150, 150) buckling_clabel.setPixmap(pixmap.scaled(buckling_clabel.size(), QtCore.Qt.KeepAspectRatio)) self.hlay.addWidget(buckling_clabel) buckling_dlabel = QtWidgets.QLabel(self) pixmap = QtGui.QPixmap(os.path.join(iconroot, "images/fixed-pinned.png")) buckling_dlabel.resize(150, 150) buckling_dlabel.setPixmap(pixmap.scaled(buckling_dlabel.size(), QtCore.Qt.KeepAspectRatio)) self.hlay.addWidget(buckling_dlabel) self.setLayout(self.hlay) class EffLengthInfo(QtWidgets.QWidget): def __init__(self, parent=None): super(EffLengthInfo, self).__init__(parent) ilabel = QtWidgets.QLabel('Ley = 1.0 L\nLec = 1.0 L') blabel = QtWidgets.QLabel('Ley = 0.699 L\nLec = 0.699 L') clabel = QtWidgets.QLabel('Ley = 2.0 L\nLec = 2.0 L') dlabel …
has answer: http://stackoverflow.com/a/52617980
tagged with: python

http://stackoverflow.com/a/52590518
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52590254
score: 1
answers question: http://stackoverflow.com/q/52590254
has comment: http://stackoverflow.com/comment/92115863
has comment: http://stackoverflow.com/comment/92116145
has body: If you need to get list of teams of specific player use exact lookup instead of contains: class TeamFilter(django_filters.FilterSet): teams = django_filters.NumberFilter( field_name='players_id', lookup_type='exact', ) class Meta: model = Team fields = ('players', 'teams',) Also use field_name as argument instead of players. If you want to show only current user's team, you'd better overrride view's get_queryset method: class MyTeamListAPIView(ListAPIView): serializer_class = MyTeamListSerializer permission_classes = [IsOwnerOrReadOnly] pagination_class = ProfileLimitPagination filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('players') filter_class = TeamFilter def get_queryset(self): return Team.objects.filter(players=self.request.user)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92115994
type: Answer

http://stackoverflow.com/comment/92162595
has text: I modified it to range(len(string)-1,0,-1): but the first character is still missing
comment on: http://stackoverflow.com/q/52614096
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52742943
has comment: http://stackoverflow.com/comment/92412675
has comment: http://stackoverflow.com/comment/92427338
has body: I have a scenario as depicted below in python code . In this I am trying to explicitly define new york and ny as synonyms. But unfortunately it is not working. Can you please guide me as I am new to elastic search. Also I am using custom analyzer. I also have the file synonyms.txt having text: ny,newyork,nyork from datetime import datetime from elasticsearch import Elasticsearch es = Elasticsearch() keywords = ['thousand eyes', 'facebook', 'superdoc', 'quora', 'your story', 'Surgery', 'lending club', 'ad roll', 'the honest company', 'Draft kings', 'newyork'] count = 1 doc_setting = { "settings": { "analysis": { "analyzer": { "my_analyzer_keyword": { "type": "custom", "tokenizer": "keyword", "filter": [ "asciifolding", "lowercase", "synonym" ] }, "my_analyzer_shingle": { "type": "custom", "tokenizer": "standard", "filter": [ "asciifolding", "lowercase", "synonym" ] } }, "filter": { "synonym": { "type": "synonym", "synonyms_path": "synonyms.txt", "ignore_case": "true" } } } }, "mappings": { "your_type": { "properties": { "keyword": { "type": "string", "index_analyzer": "my_analyzer_keyword", "search_analyzer": "my_analyzer_shingle" } } } } } validate=es.index(index='test', doc_type='your_type', body=doc_setting) print(validate) for keyword in keywords: doc = { 'id': count, 'keyword': keyword } res = es.index(index="test", doc_type='your_type', id=count, body=doc) print(res['result']) count = count + 1 #res11 = es.get(index="test", doc_type='your_type', id=1) #print(res11['_source']) es.indices.refresh(index="test") question = "I saw news on ny news channel of lending club on facebook, your story and quora" print("Question asked: %s" % question) res = es.search(index="test",`enter code here` doc_type='your_type', body={ "query": {"match": {"keyword": question}}}) print("Got %d Hits:" % res['hits']['total']) for hit in res['hits']['hits']: print(hit["_source"])
has comment: http://stackoverflow.com/comment/92411806
tagged with: elasticsearch
tagged with: python
has comment: http://stackoverflow.com/comment/92412443
score: 1
has comment: http://stackoverflow.com/comment/92410766
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92427162
has title: Synonym analyzer not working in elastic search with python
upvote count: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52751804
accepted answer: http://stackoverflow.com/a/52751804
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52700615
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
tagged with: marshmallow
has body: I'm using Marshmallow 2.15.3 for a Flask project and want to enforce strict Date and DateTime formats. With strict I mean that I only want to accept strings that are identical to the formats below. What I'm experiencing are some difference in the handling of Date and DateTime. The formats: DATE_FORMAT = '%Y-%m-%d' DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S' For example, with DateTime I can do the following: dt = fields.DateTime(format=DATETIME_FORMAT) dt.deserialize('2018-01-01') # fails, as desired dt.deserialize('2018-01-01T05:06:08.012312+02:00') # fails, as desired dt.deserialize('2018-01-01T05:06:08') # works, as desired and according to format With Date I can do the following: d = fields.Date() # does not accept format argument d.deserialize('2018-01') # fails, as desired d.deserialize('2018-01-01T05:06:08.012312+02:00') # works, NOT as desired d.deserialize('2018-01-01') # works, as desired and according to format While DateTime does not allow extra information, Date does allow it. From my understanding there is no format argument for the Date field. Is there any way I can work around this for similar functionality, and enforcing my strict format both for too short and too long input values?
answer count: 1
has answer: http://stackoverflow.com/a/52754095
accepted answer: http://stackoverflow.com/a/52754095
favorite count: 0
has title: Enforce strict fields.Date format with Marshmallow deserialization

http://stackoverflow.com/comment/92155977
score: 0
type: QuestionComment
type: Comment
has text: No, have you tried something that we can help you with? Stack Overflow is not a code writing service.
comment on: http://stackoverflow.com/q/52610134

http://stackoverflow.com/comment/95971227
comment on: http://stackoverflow.com/a/52596897
score: 1
type: Comment
has text: delete could break other thing, because the interpret might get to: line 936 mod = imp.new_module(name). Fix the module or ignore the error ...
type: AnswerComment

http://stackoverflow.com/comment/92309123
comment on: http://stackoverflow.com/q/52685021
has text: The brain-dead and left-arm checks usually *will* happen with the line you wrote, because `or` has to keep going if the left side is false.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92228464
type: Comment
comment on: http://stackoverflow.com/q/52647908
score: 0
has text: It could be something that could meet your needs..[click](https://stackoverflow.com/questions/27624850/launch-a-completely-independent-process)
type: QuestionComment

http://stackoverflow.com/comment/92310462
has text: But work fine with pysnmp 4.4.5 installed by pip3. Is it bug in 4.4.6?
type: Comment
comment on: http://stackoverflow.com/a/52681737
score: 0
type: AnswerComment

http://stackoverflow.com/a/52686189
type: Answer
score: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52686127
accepted answer of: http://stackoverflow.com/q/52686127
upvote count: 2
has body: you could use enumerate to get the index of the current item in your list: thislist = ["apple", "banana", "cherry", "banana", "banana"] for i, fruit in enumerate(thislist): if fruit == 'banana': thislist[i] = 3 to explain what is happening in your code: thislist == "banana" is always False (comparing a str to a list) thislist[False] == thislist[0] (as False == 0) thislist[0] = 3: you only set the first element. if you want to use numpy you could to the same without a (explicit) for loop (not in plain python though...) import numpy as np a = np.array(["apple", "banana", "cherry", "banana", "banana"]) a[a == 'banana'] = 3 note that multiple replacements can be done with one for loop only: repl = {'banana': 3, 'cherry': 5} for i, fruit in enumerate(thislist): if fruit in repl: thislist[i] = repl[fruit] print(thislist)

http://stackoverflow.com/q/52694838
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92348575
type: UnansweredQuestion
has title: python folium map setting (prevent zooming and panning)
tagged with: python
tagged with: folium
has body: I'm having some issues figuring out if folium can be restricted to a single instance of the world rather than allowing for panning and zooming into other instances? What I mean is when I try some basic examples online, I get maps that looks like this when zoomed out: While the output I want would only have one instance of each continent in the map rather than repeating them when panning / zooming out. I used the following code to generate the linked image: import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import folium #df_traffic = pd.read_csv('../input/ukTrafficAADF.csv') df_acc = pd.read_csv('../input/accidents_2005_to_2007.csv', dtype=object) map_hooray = folium.Map(location=[51.5074, 0.1278], zoom_start = 11) # Uses lat then lon. The bigger the zoom number, the closer in you get map_hooray # Calls the map to display What modifications do I need to make the map only display one instance of the continents even when zoomed out? Thanks!
has comment: http://stackoverflow.com/comment/92349918
has answer: http://stackoverflow.com/a/61468874
type: Question
score: 4
upvote count: 4
answer count: 1

http://stackoverflow.com/q/52594503
type: Question
has comment: http://stackoverflow.com/comment/92123958
accepted answer: http://stackoverflow.com/a/52594602
has answer: http://stackoverflow.com/a/52594651
has comment: http://stackoverflow.com/comment/92123932
has answer: http://stackoverflow.com/a/52594712
score: 0
tagged with: arrays
has comment: http://stackoverflow.com/comment/92123876
has body: def featureScaling(arr): arr= [x1,x2,x3] y=(x2-x1)/(x3-x1) return y data = [115, 140, 175] print (featureScaling(data)) I want to define a function on an array that divides the difference of the of the first two terms by the difference of the third and first term but I keep getting an error saying that x1 is not defined. I am new to coding and could really use the help.
has answer: http://stackoverflow.com/a/52594588
answer count: 5
has comment: http://stackoverflow.com/comment/92123966
tagged with: python
has title: Defining a function on an array
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92123940
possible better answer: http://stackoverflow.com/a/52594539
has answer: http://stackoverflow.com/a/52594539
has answer: http://stackoverflow.com/a/52594602

http://stackoverflow.com/comment/92369552
score: 0
comment on: http://stackoverflow.com/q/52721616
type: QuestionComment
type: Comment
has text: My y is a np.array which is 1d by default. But the Keras model runs. It also runs for a 2d array if I add new axis. I'm just not sure which one to use for full training.

http://stackoverflow.com/comment/92272458
comment on: http://stackoverflow.com/a/52671023
score: 0
type: AnswerComment
has text: I suggest checking the im1 and im2 aren't `None`, and reporting those as "file not found". If both fail to read, `cv2.subtract(None, None)` will give you `None`, and `np.any(None)` likewise returns `None`. `not None` is `True`, causing that code to always report "Images are the same" if both images fail to read.
type: Comment

http://stackoverflow.com/comment/93326049
type: AnswerComment
has text: Please some comments or description to explain how your code works.
comment on: http://stackoverflow.com/a/52658653
type: Comment
score: 0

http://stackoverflow.com/q/52648418
has comment: http://stackoverflow.com/comment/97982225
accepted answer: http://stackoverflow.com/a/58243606
has comment: http://stackoverflow.com/comment/126831969
answer count: 1
downvote count: 0
score: 7
has title: How to reference finalized object in weakref.finalize?
favorite count: 0
tagged with: weak-references
linked to: http://stackoverflow.com/q/30294458
has body: I have a class (that I do not control) that doesn't implement its own cleanup. I thought that this is one of the cases that weakref.finalize is for, but I can't get it working. def cleanup(obj): print('Cleanup obj') if not obj.is_closed: obj.close() ... def make_obj(): obj = SomeClass() # this creates an extra ref, so cleanup is never run weakref.finalize(obj, cleanup, obj) # this always results in ReferenceError; obj is already gone when cleanup is called weakref.finalize(obj, cleanup, weakref.proxy(obj)) Am I doing something wrong? What have I misunderstood?
tagged with: python
has answer: http://stackoverflow.com/a/58243606
type: AnsweredQuestion
upvote count: 7
type: Question

http://stackoverflow.com/q/52735313
has comment: http://stackoverflow.com/comment/92396358
has comment: http://stackoverflow.com/comment/92396534
tagged with: python
tagged with: jupyter-notebook
linked to: http://stackoverflow.com/q/5091993
type: AnsweredQuestion
has title: Import package works in jupyter notebook but not in iPython and Anaconda cmd
upvote count: 2
has comment: http://stackoverflow.com/comment/92396893
has answer: http://stackoverflow.com/a/52736579
type: Question
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/52736579
has comment: http://stackoverflow.com/comment/92397849
has body: When searching about this issue, I came across some questions asking the opposite, i.e., package opens in iPython but not in Jupyter Notebook. But in my case, its the opposite. That's why I posted this question. I added path\to\anaconda3 and path\to\anaconda3\Lib\site-packages in the environment variable, but it doesn't solve the issue. I can see the packages in the site-packages folder: But I just can't import some of the packages in iPython: or with python in the anaconda cmd: But it works fine in Jupyter Notebook: What do/can I do to fix this? Here's some more info if it helps: (base) C:\Users\h473&gt;where python C:\Users\h473\AppData\Local\Continuum\anaconda3\python.exe (base) C:\Users\h473&gt;where conda C:\Users\h473\AppData\Local\Continuum\anaconda3\Library\bin\conda.bat C:\Users\h473\AppData\Local\Continuum\anaconda3\Scripts\conda.exe (base) C:\Users\h473&gt;where pip C:\Users\h473\AppData\Local\Continuum\anaconda3\Scripts\pip.exe P.S.: It doesn't happen for all packages, only some packages, as shown for pandas, numpy and matplotlib in the screenshot below.
tagged with: ipython
tagged with: conda
score: 2
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92397357
has comment: http://stackoverflow.com/comment/92396703
has comment: http://stackoverflow.com/comment/92396598

http://stackoverflow.com/a/52694116
has comment: http://stackoverflow.com/comment/92315588
type: Answer
upvote count: 3
score: 3
has body: Filter the data frame down to LogOn only first and then do groupBy.pivot: import pyspark.sql.functions as F df.filter( df.auth_orient == 'LogOn' ).groupBy('time').pivot('success').agg(F.count('*')).show() +----+----+-------+ |time|Fail|Success| +----+----+-------+ | 1| 1| 3| | 2| 2| 8| +----+----+-------+
answers question: http://stackoverflow.com/q/52693510
downvote count: 0

http://stackoverflow.com/q/52687629
tagged with: networkx
tagged with: dijkstra
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52688219
has body: I'm wondering what the most efficient method would be to verify that all target nodes from a set T are reachable from at least one source node S in Python's NetworkX library. To me, it should be a simple many-to-many Dijkstra function call, where S is the source node list input and T is the target node list input. I could then verify that the returned value indicates that at least one of the routings was a success. This is how I would approach the problem using PostgreSQL's pgRouting extension, for those that may be familiar with that: pgr_dijkstra(edges_sql, start_vids, end_vids) However, it seems from the documentation that a function where both the sources and targets are lists does not exist. The closest I could find is multi_source_dijkstra or all_pairs_dijkstra. I feel that multi_source_dijkstra is insufficient because I cannot specify a list of multiple target nodes as input, and that all_pairs_dijkstra is too much because I don't want to waste time testing connectivity between source nodes or between target nodes. Furthermore, I am fully expecting my graph to have gaps within itself, and I just want to test the original condition - that all target nodes are just reachable from at least one source node. I'm sure that something can be cobbled together the multi_source_dijkstra function, but I want to this be as efficient as possible so I am hoping that I am just missing an obvious implementation that would do what I want most efficiently. EDIT: Image for @abc. The red/yellow, red/pink lines and green lines represent a subgraph which I am using in the DFS or BFS algorithm. This configuration is returning True, claiming that all the red dots (targets) are reachable from the green dot (source).
tagged with: routes
type: Question
accepted answer: http://stackoverflow.com/a/52688219
answer count: 1
downvote count: 0
has title: Verify if all target nodes are reachable from at least one source node in Python NetworkX
tagged with: python
favorite count: 0
upvote count: 1

http://stackoverflow.com/a/52632737
has comment: http://stackoverflow.com/comment/92199020
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Don't make a string out of the other two lists. That turns them into an iterator over the characters in the string rather than the elements in the list. Try this instead: row_list = zip(list1, list2, list3) Oh, and if you're only writing one row, use writerow instead of writerows
accepted answer of: http://stackoverflow.com/q/52632689
answers question: http://stackoverflow.com/q/52632689
score: 4

http://stackoverflow.com/a/52627949
has body: Connection refused is generated by the kernel because receiving side refuses to establish TCP connection. Possible reasons are: No on listen on this host/port iptables (or other firewall) specifically -j REJECT those connections. From your code it's hard to say if you listen on a proper host/port or not. How to debug? Run you service. Without connecting to it run 'netstat -lnpt', it should provide you with list of services listening on this host. Try nc host port (note - not a ':', but a space here), if connection is refused, nc will terminate instantly. If not, you've established connection (try to type 'GET / HTTP/1.1' and Enter twice in this case). Just print output of socket.gethostname() and port variable in your code. I suspect that in your case socket.gethostname() has been resolved into something different than localhost.
accepted answer of: http://stackoverflow.com/q/52627563
answers question: http://stackoverflow.com/q/52627563
has comment: http://stackoverflow.com/comment/100694493
type: AcceptedAnswer
downvote count: 0
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/100696884
score: 8
has comment: http://stackoverflow.com/comment/92209551
has comment: http://stackoverflow.com/comment/92194860

http://stackoverflow.com/comment/98068999
type: Comment
comment on: http://stackoverflow.com/a/52663589
has text: Indeed, using `universal_newlines=True` instead of `text=True` worked.
score: 12
type: AnswerComment

http://stackoverflow.com/q/52641630
has answer: http://stackoverflow.com/a/52641689
favorite count: 0
duplicate of: http://stackoverflow.com/q/19128523
tagged with: python
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/52641689
score: 1
has comment: http://stackoverflow.com/comment/92215744
upvote count: 1
possible better answer: http://stackoverflow.com/a/52641693
linked to: http://stackoverflow.com/q/19128523
has body: If I use numpy, than I can slice an array as follows: import numpy as np A = np.asarray([1, 2, 3, 4, 5]) print(A[np.asarray([1, 3])]) Then the output is [2 4]. I wonder if I can do the same operation without using numpy, when A is just a list.
type: Question
has answer: http://stackoverflow.com/a/52641693
tagged with: numpy
has title: Can I slice a list like numpy?
answer count: 2
has comment: http://stackoverflow.com/comment/92215604
downvote count: 0

http://stackoverflow.com/comment/92399727
type: QuestionComment
type: Comment
has text: If you are satisfied by answer please mark it accepted...let me know if you need any other information.
comment on: http://stackoverflow.com/q/52737165
score: 0

http://stackoverflow.com/a/52641104
upvote count: 2
answers question: http://stackoverflow.com/q/52640981
has body: You can wrap the whole optional part within an optional non-capturing group and make the capturing group for CONFIG_FILE obligatory: re.compile(r"""CLASS_NAME:(?:\w+\W+){3}(?P&lt;class&gt;\w+)(?:.*? (CONFIG_FILE:(?:\w+\W+){3}(?P&lt;cnf&gt;\w+\.txt)))? """, re.X) In case there are newlines, use re.X | re.S modifier options. Note that \w+\W\w+\W\w+\W is better written as (?:\w+\W+){3}. See the regex demo The main difference is (?:.*?(CONFIG_FILE:(?:\w+\W+){3}(?P&lt;cnf&gt;\w+\.txt)))? part: (?: - start of an optional (as there is a greedy ? quantifier after it) non-capturing group matching .*? - any 0+ chars, as few as possible (CONFIG_FILE:(?:\w+\W+){3}(?P&lt;cnf&gt;\w+\.txt)) - matches CONFIG_FILE: - a literal substring (?:\w+\W+){3} - three sequences of 1+ word chars followed with 1+ non-word chars (?P&lt;cnf&gt;\w+\.txt) - Group cnf: 1+ word chars, a dot (note it should be escaped) and then txt )? - end of the optional non-capturing group (that will be tried once)
accepted answer of: http://stackoverflow.com/q/52640981
has comment: http://stackoverflow.com/comment/92227364
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/52693004
accepted answer: http://stackoverflow.com/a/52694835
has body: I have a sample of ~60,000 documents. We've hand coded 700 of them as having a certain type of content. Now we'd like to find the "most similar" documents to the 700 we already hand-coded. We're using gensim doc2vec and I can't quite figure out the best way to do this. Here's what my code looks like: cores = multiprocessing.cpu_count() model = Doc2Vec(dm=0, vector_size=100, negative=5, hs=0, min_count=2, sample=0, epochs=10, workers=cores, dbow_words=1, train_lbls=False) all_docs = load_all_files() # this function returns a named tuple random.shuffle(all_docs) print("Docs loaded!") model.build_vocab(all_docs) model.train(all_docs, total_examples=model.corpus_count, epochs=5) I can't figure out the right way to go forward. Is this something that doc2vec can do? In the end, I'd like to have a ranked list of the 60,000 documents, where the first one is the "most similar" document. Thanks for any help you might have! I've spent a lot of time reading the gensim help documents and the various tutorials floating around and haven't been able to figure it out. EDIT: I can use this code to get the documents most similar to a short sentence: token = "words associated with my research questions".split() new_vector = model.infer_vector(token) sims = model.docvecs.most_similar([new_vector]) for x in sims: print(' '.join(all_docs[x[0]][0])) If there's a way to modify this to instead get the documents most similar to the 700 coded documents, I'd love to learn how to do it!
has title: Doc2Vec: Similarity Between Coded Documents and Unseen Documents
score: 0
has comment: http://stackoverflow.com/comment/92312877
answer count: 3
tagged with: doc2vec
has answer: http://stackoverflow.com/a/52693205
has answer: http://stackoverflow.com/a/52936170
possible better answer: http://stackoverflow.com/a/52693205
tagged with: python
tagged with: gensim
has answer: http://stackoverflow.com/a/52694835
tagged with: nlp
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92312900
tagged with: word2vec
type: Question

http://stackoverflow.com/q/52691703
has title: SCAPY send packet error OSError: [Errno 97] Address family not supported by protocol
type: UnansweredQuestion
tagged with: sockets
has body: I hit the below error when trying to send packet using: Ubuntu: release 18.04 Python: 3.6.6 scapy version: 2.4.0 &gt;&gt;&gt; send(IP(dst="192.168.1.1")/ICMP()) --------------------------------------------------------------------------- OSError Traceback (most recent call last) &lt;ipython-input-2-8333be02b5c1&gt; in &lt;module&gt; ----&gt; 1 send(IP(dst="192.168.1.1")/ICMP()) ~/scapy/lib/python3.6/site-packages/scapy/sendrecv.py in send(x, inter, loop, count, verbose, realtime, return_packets, socket, *args, **kargs) 298 [socket=None]) -&gt; None""" 299 if socket is None --&gt; 300 socket = conf.L3socket(*args, **kargs) 301 return __gen_send(socket, x, inter=inter, loop=loop, count=count, verbose=verbose, 302 realtime=realtime, return_packets=return_packets) ~/scapy/lib/python3.6/site-packages/scapy/arch/linux.py in __init__(self, iface, type, promisc, filter, nofilter, monitor) 405 def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0): 406 self.type = type --&gt; 407 self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) 408 self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) 409 if iface: /usr/lib/python3.6/socket.py in __init__(self, family, type, proto, fileno) 142 # constructor of _socket.socket converts the given argument to an 143 # integer automatically. --&gt; 144 _socket.socket.__init__(self, family, type, proto, fileno) 145 self._io_refs = 0 146 self._closed = False OSError: [Errno 97] Address family not supported by protocol Is there anything that might cause this on a fresh install of Scapy?
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/55664911
downvote count: 0
tagged with: scapy
type: Question
has comment: http://stackoverflow.com/comment/92338682
score: 4
has comment: http://stackoverflow.com/comment/92311893
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92340230

http://stackoverflow.com/a/52680733
answers question: http://stackoverflow.com/q/52680467
upvote count: 4
downvote count: 0
type: Answer
has body: You can create a dataframe of the expected result by group and then merge it back to the original dataframe. expected = ( df.groupby('Group') .apply(lambda x: (x['Value1'].eq(7).any() &amp; x['Value2'].eq(9)).any()) .to_frame('Expected_Output')) &gt;&gt;&gt; expected Expected_Output Group 1 True 2 False &gt;&gt;&gt; df.merge(expected, left_on='Group', right_index=True) Group Value1 Value2 Expected_Output 0 1 3 9 True 1 1 7 6 True 2 1 9 7 True 3 2 3 8 False 4 2 8 5 False 5 2 7 6 False
score: 4

http://stackoverflow.com/comment/92392741
has text: what is group profile?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52733905
type: Comment

http://stackoverflow.com/q/52595251
downvote count: 2
tagged with: django
tagged with: python
has body: models.py from django.db import models from collections import Counter from django.db.models import Count from itertools import groupby Gender = ( ('Male', 'MALE'), ('Female', 'FEMALE'), ) Diseases = ( ('Cholera', 'CHOLERA'), ('HIV', 'HIV'), ('Malaria', 'MALARIA'), ('Typhoid', 'TYPHOID'), ('Measles', 'MEASLES'), ) class MyModel(models.Model): Gender = models.CharField(max_length=16, choices=Gender, default='MALE') Diseases = models.CharField(max_length=16, choices=Diseases, default='MALARIA') vote = models.IntegerField(default=0) def __str__(self): r=0 return u'%s %s' % (self.Gender, self.Diseases) Now this returns this in the admin django panel Male Measles Male Measles Male Cholera Female Cholera Female Typhoid Female Typhoid But I want to group it so it looks something like this: Male malaria 2 Male Measles 2 Female Typhoid 3 in this admin panel instead of listing all of it like it does now
type: Question
has title: Looping through instances for django
score: -2
has answer: http://stackoverflow.com/a/52595679
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52694273
type: Answer
has comment: http://stackoverflow.com/comment/92318336
score: 0
answers question: http://stackoverflow.com/q/52694006
has comment: http://stackoverflow.com/comment/92326373
has body: There's install_requires keywrod to pass to setup function, and you should put there numpy and add to this line some version specificators. For example, install_requires=['numpy&gt;=1.0'] More about specificators and other options you can read here

http://stackoverflow.com/q/52648862
linked to: http://stackoverflow.com/q/17388213
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92231578
has comment: http://stackoverflow.com/comment/92231807
type: Question
has body: I have 2 data frames. One pulls values using an API of current values of certain fields on system. The other has the actual current values of those fields. Example: Names on the system and names on paper. I've merged the two on the common column but now am trying to compare the names on Python to see if they are an approximate match and/or if they need an update. Is there a way I can do this? I believe this can be done on excel using isnumber(search(...)). Case Insensitive and possibly consider abbreviations (I can make a dictionary?) for comparing text strings Example of how my dataframe looks and the result I want: Name on System Current Name Match 1 APPLE INFORMATION TECHNOLOGY Apple International Information Technology No 2 IBM Intl group IBM International Group YES PS. Apologies in advance if I have broken any rules or etiquette of the Stack community, I'm new to this and open to learning and constructive criticism.
has title: Match and compare strings in Python Dataframe
score: 0
has comment: http://stackoverflow.com/comment/92229663
answer count: 2
has answer: http://stackoverflow.com/a/52649212
tagged with: pandas
has answer: http://stackoverflow.com/a/52650387
accepted answer: http://stackoverflow.com/a/52649212
has comment: http://stackoverflow.com/comment/92230388
has comment: http://stackoverflow.com/comment/92231657
possible better answer: http://stackoverflow.com/a/52650387

http://stackoverflow.com/a/52694989
upvote count: 1
has body: You can using mean with level=0 pd.to_numeric(df.a,errors='coerce').mean(level=0) Out[438]: c 2.0 d 5.0 e 5.0 Name: a, dtype: float64 Also nan is not NaN , using replace df=df.replace('nan',np.nan)
has comment: http://stackoverflow.com/comment/92316531
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52694947
has comment: http://stackoverflow.com/comment/92316546
has comment: http://stackoverflow.com/comment/92316507
type: Answer
has comment: http://stackoverflow.com/comment/92316605

http://stackoverflow.com/comment/92356645
has text: Passing single class name to `find_element_by_class_name` is absolutely correct usage
comment on: http://stackoverflow.com/a/52715015
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92112993
score: 0
type: Comment
type: QuestionComment
has text: because this website using javascrip to load data,so you can not scrape it all
comment on: http://stackoverflow.com/q/52588733

http://stackoverflow.com/comment/92134636
comment on: http://stackoverflow.com/q/52600048
has text: I can't, though. Even though there is lots of overall code, this is the only *relevant* code.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92165451
type: AnswerComment
has text: does this work in qtconsole by default or does one need to follow the instructions in #2? I just launched qtconsole and typed " and it did not automatically supply the close "
comment on: http://stackoverflow.com/a/52600577
score: 0
type: Comment

http://stackoverflow.com/comment/92443894
comment on: http://stackoverflow.com/a/52746756
type: Comment
score: 0
type: AnswerComment
has text: *connection attempts*. Not *connections*. Put another way, don't try to *start* 60k connections at once. Try to *start* a few dozen or a hundred at once (exactly how many depends on your network resources). Once the connections are *established* you can maintain them while you *start* more.

http://stackoverflow.com/a/52738491
answers question: http://stackoverflow.com/q/52723672
has body: The short of it is: You can't track that the function is being called with assert_called_once if the return value of open isn't a mock object. So, instead of making the return value a StringIO we can make it a MagicMock that will act like a file handle. import io from unittest.mock import patch, MagicMock class MyObject(): def __init__(self,path): fp = open(path) self.file_list = [] for line in fp: self.file_list.append(line.strip()) fp.close() def testsimpleFile(): fake_file = MagicMock() fake_file.__iter__.return_value = ["data.csv", "data2.csv"] with patch("builtins.open", return_value=fake_file, create=True) as mock_file: f = MyObject("/path/to/open/test.f") mock_file.assert_called_once_with("/path/to/open/test.f") golden_list = ["data.csv", "data2.csv"] assert f.file_list == golden_list fake_file.close.assert_called_once()
has comment: http://stackoverflow.com/comment/92402739
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92402436
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52723672
score: 1

http://stackoverflow.com/q/52598341
has comment: http://stackoverflow.com/comment/92132516
has body: I have the following code which I use to determine how much of each repayment goes into each late payments bucket (i.e. 0-7 days past due, 7-15 days past due... etc) For example, the repayment amount is 100. 20 gets repid early, and then the customer misses the repayment date. Therefore, 80 goes into the 0-7dpd bucket and so on. Similarly, if the customer does not repay for 7 days, the 80 goes into the 7-15dpd bracket. The code works, but takes a long time. I was wondering if there is a method to make the code run faster. repayments['principal_0_7_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 2.0), repayments.amount_principal - (repayments.child_principal_repaid_early), 0) repayments['principal_7_15_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 7.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days), 0) repayments['principal_15_30_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 15.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days), 0) repayments['principal_30_45_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 30.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days), 0) repayments['principal_45_60_dpd'] = np.where((repayments.paid_y_n == 'no') &amp; (repayments.days_since_due &gt;= 45.0), repayments.amount_principal - (repayments.child_principal_repaid_early + repayments.child_principal_repaid_1_7_days + repayments.child_principal_repaid_7_15_days + repayments.child_principal_repaid_15_30_days + repayments.child_principal_repaid_30_45_days), 0) repayments['principal_60_90_dpd']…
score: 0
tagged with: pandas
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Calculating how much $ goes into each defaulting bucket
has comment: http://stackoverflow.com/comment/92131477
type: Question

http://stackoverflow.com/comment/92813468
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52915298
has text: OK, thanks. I'll go ahead and add mine altho it's not substantially different than yours or @jpp's (just slightly simpler)
type: Comment

http://stackoverflow.com/comment/92133973
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52599682
has text: @Victor Do `df.index.time == datetime.time(12, 5)`

http://stackoverflow.com/comment/92393151
type: Comment
type: QuestionComment
has text: Can you set rankdir to LR - see if the graph gets generated from left to right instead of top to bottom. I know how to do this directly but not from python.
comment on: http://stackoverflow.com/q/52734050
score: 0

http://stackoverflow.com/comment/92299161
has text: What _are_ `DueDate` and `ByDate` exactly… the numbers are too big for an epoch and the second number there is negative? Are you sure that your JSON is correct?
type: QuestionComment
comment on: http://stackoverflow.com/q/52685754
type: Comment
score: 0

http://stackoverflow.com/a/52692882
accepted answer of: http://stackoverflow.com/q/52692315
has body: Contingency tables are used in statistics to summarize the relationship between several categorical variables. In your example, The Contingency table between the two variables Genderand Married is a Frequency table of these variables presented simultaneously. A chi-squared test conducted on a contingency table can test whether or not a relationship exists between variables. These effects are defined as relationships between rows and columns. scipy.stats.chi2_contingency computes -by default- Pearson’s chi-squared statistic. Moreover,we are interested in the Sig(2-Tailed) which is the p-value in your example. The p-value is the evidence against a null hypothesis. The smaller the p-value, the strong the evidence that you should reject the null hypothesis. And the null hypothesis in your case is the dependence of the observed frequencies in the contingency table. Choosing Significant Level -alpha as 5%; your p-value is 4.502328957824834e-19 is much less than .05 indicating that the rows and columns of the contingency table are independent. Generally this means that it is worthwhile to interpret the cells in the contingency table. In this particular case it means that being Male or Female (i.e. Gender) is not distributed similarly across the different levels of Marital Status (i.e. Married, Not-Married). So, being married may be the status of one gender more than the other! Update According to your comment, I see you have some doubts about this test. This test basically tells you if the relationship between variables is Significant (i.e. may represent the population) or came by chance! So if you have high level of Significance (high p-value), that means there's a significant dependency between the variables! Now, if Gender and Married are both features in your model, that may lead to over-fitting and features redundancy. Then, you may want to choose one of them. But if Gender or Married is the dependent variable (like y), then it's good they have significant relationshi…
type: Answer
has comment: http://stackoverflow.com/comment/92312932
has comment: http://stackoverflow.com/comment/92312750
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/92313188
answers question: http://stackoverflow.com/q/52692315
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52659448
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52659023
type: Answer
upvote count: 1
has body: The issue you are getting is KeyError which is raised when a mapping (dictionary) key is not found in the set of existing keys. In your case the competencies key is not in dict d. So, you'll need to change your class call from: es = employer_search(d,ans) To: es = employer_search(ans,d) Side note: You can make __init__ call mandatory using named parameter by writing it as: def __init__(self,*,ans,d) and then call it as es = employer_search(ans=ans, d=d) Also, if you are using Python 3 you can simply declare it as class EmployerSearch:. (CamelCase)

http://stackoverflow.com/comment/92452180
type: AnswerComment
type: Comment
has text: That would be problem with your environment but, not with the code.
score: 0
comment on: http://stackoverflow.com/a/52726012

http://stackoverflow.com/a/52721369
type: Answer
has body: There are some other issues with your code, but answering your question, your function special_caracters(password) does not return any value when the condition is True. Try refactoring it a bit: def special_caracters (password): for i in password: if i in NON_ALPHABETIC_CARACTERS: return True return False
answers question: http://stackoverflow.com/q/52721226
has comment: http://stackoverflow.com/comment/92367904
score: 0
has comment: http://stackoverflow.com/comment/92369479

http://stackoverflow.com/a/53549954
answers question: http://stackoverflow.com/q/52657809
has comment: http://stackoverflow.com/comment/93966611
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/93976229
has body: there is a error. Can you provide the error message? And of course the code will not run directly from Python 2 to 3 until you do the modification from importing the PySerial Library. Python runs and finds the library, but it cannot be used for Python 3, that's why they made 2 libraries for PySerial.

http://stackoverflow.com/a/52670959
has comment: http://stackoverflow.com/comment/92271863
has comment: http://stackoverflow.com/comment/92272002
has comment: http://stackoverflow.com/comment/92275946
has comment: http://stackoverflow.com/comment/92275569
score: 0
has body: If I understand your question correctly, you could try this: &gt;&gt;&gt; from django.contrib.auth.models import Permission &gt;&gt;&gt; field_name_list = [] &gt;&gt;&gt; qs = Permission.objects.all() &gt;&gt;&gt; qs = qs.filter(content_type__id=1) # I added this line to make this sample output shorter &gt;&gt;&gt; qs = qs.values(*field_name_list) &gt;&gt;&gt; final_data = [] &gt;&gt;&gt; for elem in qs: ... print(type(elem)) ... print(elem) ... for v in elem.values(): ... final_data.append(v) &lt;class 'dict'&gt; {'id': 1, 'name': 'Can add log entry', 'content_type_id': 1, 'codename': 'add_logentry'} &lt;class 'dict'&gt; {'id': 2, 'name': 'Can change log entry', 'content_type_id': 1, 'codename': 'change_logentry'} &lt;class 'dict'&gt; {'id': 3, 'name': 'Can delete log entry', 'content_type_id': 1, 'codename': 'delete_logentry'} &gt;&gt;&gt; final_data [1, 'Can add log entry', 1, 'add_logentry', 2, 'Can change log entry', 1, 'change_logentry', 3, 'Can delete log entry', 1, 'delete_logentry'] This uses the method queryset.values() to have each Permission instance be represented by a dict instead of an actual model instance. If you leave field_name_list as an empty list, then you will get all fields for that model, but you can also add the names of the fields you want. Then, you can use dict.values() to just get the values (the column values for that row) without the keys (which would be the column names).
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52670717
has comment: http://stackoverflow.com/comment/92275627
answers question: http://stackoverflow.com/q/52670717
has comment: http://stackoverflow.com/comment/92276070
type: Answer

directory
tags question: http://stackoverflow.com/q/52631992
tag name: directory
type: Tag
tags question: http://stackoverflow.com/q/52642070
tags question: http://stackoverflow.com/q/52706574
tags question: http://stackoverflow.com/q/52703465
tags question: http://stackoverflow.com/q/52620350
tags question: http://stackoverflow.com/q/52648248

http://stackoverflow.com/a/52654743
has body: You code works in delivering help output but not in paging it. The pager executes in the user code run process and does not know how to interact with an IDLE shell in a separate gui process. I don't believe you can change this. To address this issue, IDLE has a new feature, starting with 3.6.7 and 3.7.1 (the release candidates are available now, the final releases will be out in a week or so). IDLE squeezes 'long' output to a button. (By default, 'long' is 50 lines, but user can modify this. Shorted output can be squeezed by right-clicking on it.) &gt;&gt;&gt; help(int) [ Squeezed text (241 lines) ] # &lt;== tkinter button &gt;&gt;&gt; You can expand the text in place, with a double click, or into the clipboard or a separate non-modal view window, with a right click. A separate window lets one scroll or page up and down in the help entry while writing a statement in the Shell.
type: Answer
answers question: http://stackoverflow.com/q/52649433
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52649433
has comment: http://stackoverflow.com/comment/92242456
has comment: http://stackoverflow.com/comment/92242466
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52659755
score: 2
answer count: 1
downvote count: 0
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/52660124
tagged with: python
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: Importing a python module from the python script from drive in colab
has body: I am currently working on a project on Machine Learning on Google Colab which uses Tensorflow API. I created a folder and uploaded it on google drive to run on google Colab. I successfully mounted the google drive and can run the script, But when I try importing another module from the script present in the same folder, it throws an error from . import inference ImportError: cannot import name 'inference' I tried finding out a solution for this but found results stating how to import a module directly to the colab notebook. Please tell me what I am missing here. Edit: The folder structure is -nmt -nmt.py -train.py -inference.py -utils -evaluation.py and so on. And I am running the python file from the nmt folder. I am getting relative import errors.
tagged with: import
type: Question

http://stackoverflow.com/q/52623820
favorite count: 0
has comment: http://stackoverflow.com/comment/92181203
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92181760
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52624289
tagged with: dataframe
score: -1
tagged with: pandas
has comment: http://stackoverflow.com/comment/92182313
upvote count: 0
has body: a b ... c d DateTime ... 2016-07-01 00:00:00 994.758209 31.556425 ... NaN NaN 2016-07-01 12:00:00 994.727417 29.273750 ... NaN NaN 2016-07-02 00:00:00 996.516484 26.598056 ... NaN NaN 2016-07-04 00:00:00 997.588235 10.686389 ... NaN NaN 2016-07-04 12:00:00 994.347107 25.472639 ... NaN NaN my index is datetime but i want to set default index from 0,1...to n but want to retain my datetime index as column in dataframe. reset_index() drops the index and I'm not able to get the datetime as a column. How can I do that?
answer count: 1
has comment: http://stackoverflow.com/comment/92181585
has title: I want to reset index but want to have all the columns in dataframe

http://stackoverflow.com/comment/92314793
type: Comment
comment on: http://stackoverflow.com/a/52693649
has text: df['is negative'] = (df['b'] < 0).cummax().astype(int) - this line creates the column i was referring to
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92409391
type: QuestionComment
has text: The model is an auto encoder, which contains de/convolution layers in the encoder and decoder. when I save the images in csv file and read them directly this was not a problem, that is why I thought this is caused by the dataset.
score: 0
comment on: http://stackoverflow.com/q/52717630
type: Comment

http://stackoverflow.com/comment/92209275
type: QuestionComment
comment on: http://stackoverflow.com/q/52638157
score: 0
has text: @matts they are strings.
type: Comment

http://stackoverflow.com/a/52624303
accepted answer of: http://stackoverflow.com/q/52622220
answers question: http://stackoverflow.com/q/52622220
has comment: http://stackoverflow.com/comment/92187412
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92188066
type: Answer
has body: I'm not familiar with the Raspberry Pi, but I can show you how I'd do this in a "normal" pygame program. Put the names of your music files into a list and switch the songs with the help of the set_endevent function and a custom event type and an index variable. To pause the playback, I'd define a paused boolean variable and toggle it when the user presses Space paused = not paused. Then just pause and unpause the music in this way: if paused: pg.mixer.music.pause() else: pg.mixer.music.unpause() Here's a complete example: import random import pygame as pg pg.mixer.pre_init(44100, -16, 2, 2048) pg.init() screen = pg.display.set_mode((640, 480)) SONGS = ['song1.wav', 'song2.wav', 'song3.wav'] # Here we create a custom event type (it's just an int). SONG_END = pg.USEREVENT # When a song is finished, pygame will add the # SONG_END event to the event queue. pg.mixer.music.set_endevent(SONG_END) # Load and play the first song. pg.mixer.music.load(SONGS[0]) pg.mixer.music.play(0) def main(): clock = pg.time.Clock() song_idx = 0 paused = False done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True if event.type == pg.KEYDOWN: # Press right arrow key to increment the # song index. Modulo is needed to keep # the index in the correct range. if event.key == pg.K_RIGHT: print('Next song.') song_idx += 1 song_idx %= len(SONGS) pg.mixer.music.load(SONGS[song_idx]) pg.mixer.music.play(0) elif event.key == pg.K_SPACE: # Toggle the paused variable. paused = not paused if paused: # Pause the music. pg.mixer.music.pause() else: # Unpause the music. pg.mixer.music.unpause() # When a song ends the SONG_END event is emitted. # I just pick a random song and play it here. if event.type == SONG_END: print('The song has ended. Playing random song.') pg.mixer.music.load(random.choice(SONGS)) pg.mixer.music.play(0) screen.fill((30, 60, 80)) pg.display.flip() clock.tick(30) if __name__ == '__main__': main() pg.quit()
score: 2
has comment: http://stackoverflow.com/comment/92187174
upvote count: 2
has comment: http://stackoverflow.com/comment/92191116

http://stackoverflow.com/q/52658905
favorite count: 0
has title: Pandas DataFrame convert date string
type: UnansweredQuestion
tagged with: datetime
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52658925
type: Question
tagged with: dataframe
score: 0
tagged with: pandas
has body: beginner question. If you run the below: df = pd.read_html('https://coinmarketcap.com/currencies/veritaseum/historical-data/?start=20180101&amp;end=20180105') df it creates a table: [ Date Open* High Low Close** Volume Market Cap 0 Jan 05, 2018 366.43 395.69 356.26 380.11 426543 746285248 1 Jan 04, 2018 376.58 397.02 353.17 368.46 734384 766956544 2 Jan 03, 2018 378.55 395.28 352.05 376.05 1000590 770974464 3 Jan 02, 2018 343.79 393.92 335.60 377.54 2011340 700168512 4 Jan 01, 2018 338.14 357.18 325.33 343.12 890956 688681984] but when you try creating a DataFrame: data_table = pd.DataFrame(df) data_table Nothing comes out. Is it due to the Date being a string? How can you overcome it? Thanks in advance.
tagged with: http://stackoverflow.com/tag/html
answer count: 1

http://stackoverflow.com/comment/92134107
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52599727
type: QuestionComment
has text: what are your headers here? could you provide all code?

http://stackoverflow.com/a/52693910
has comment: http://stackoverflow.com/comment/92314631
downvote count: 0
has comment: http://stackoverflow.com/comment/92314603
answers question: http://stackoverflow.com/q/52693860
type: Answer
has body: I suggest you build a list of factors first, instead of iterating at each step. def get_factors(n): factors = [] for i in range(1, n+1): if n % i == 0: factors.append(i) return factors Now you can define your other functions in terms of the list of factors: def is_prime(factors): return len(factors) == 2 def num_factors(factors): return len(factors) If you want to make your implementation more efficient, I suggest you read up on prime factorization.
score: 1
upvote count: 1

http://stackoverflow.com/comment/92266279
score: 0
type: AnswerComment
has text: @Herc01, in order to get the correct answer you need to show at least minimal code and desired result.
comment on: http://stackoverflow.com/a/52667083
type: Comment

http://stackoverflow.com/comment/92373451
type: QuestionComment
comment on: http://stackoverflow.com/q/52723869
has text: I'm running an older version of zipline due to legacy code.
score: 0
type: Comment

http://stackoverflow.com/a/52603783
score: 4
answers question: http://stackoverflow.com/q/52603071
has comment: http://stackoverflow.com/comment/92142635
has comment: http://stackoverflow.com/comment/92144940
type: AcceptedAnswer
has body: You can return a descriptor that returns an object that makes itself callable and has an enhanced attribute mapped to your enhanced wrapper function: from functools import partial def decorator(func): class EnhancedProperty: # this allows function.enhanced() to work def enhanced(self, *args, **kwargs): print('enhanced', end=' ') # this output is for the demo below only return func(*args, **kwargs) # this allows function() to work def __call__(self, *args, **kwargs): return func(*args, **kwargs) def __get__(self, obj, objtype): class Enhanced: # this allows x.function() to work __call__ = partial(func, obj) # this allows x.function.enhanced() to work enhanced = partial(self.enhanced, obj) return Enhanced() return EnhancedProperty() so that: @decorator def function(): print('function') class X: @decorator def function(self): print('method of %s' % self.__class__.__name__) x = X() function() function.enhanced() x.function() x.function.enhanced() would output: function enhanced function method of X enhanced method of X
has comment: http://stackoverflow.com/comment/92143110
type: Answer
has comment: http://stackoverflow.com/comment/92144521
has comment: http://stackoverflow.com/comment/92143123
has comment: http://stackoverflow.com/comment/92142665
has comment: http://stackoverflow.com/comment/92143712
upvote count: 4
has comment: http://stackoverflow.com/comment/92142542
accepted answer of: http://stackoverflow.com/q/52603071
downvote count: 0

http://stackoverflow.com/a/52603618
has body: How about: s = df.groupby(['time', 'color']).size() s = s.unstack(0).eq(2).all() valid_times = s.index[s] print(df[df.time.isin(valid_times)]) time color height weight value 1 t1 red hr1 wr1 vr1 2 t1 red hr1 wr1 vr1 3 t1 blue hb1 wb1 vb1 4 t1 blue hb1 wb1 vb1 5 t1 green hg1 wg1 vg1 6 t1 green hg1 wg1 vg1 11 t3 red hr3 wr3 vr3 12 t3 red hr3 wr3 vr3 13 t3 green hg3 wg3 vg3 14 t3 green hg3 wg3 vg3 15 t3 blue hb3 wb3 vb3 16 t3 blue hb3 wb3 vb3
type: Answer
score: 1
downvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92141819
accepted answer of: http://stackoverflow.com/q/52603467
answers question: http://stackoverflow.com/q/52603467
upvote count: 2

http://stackoverflow.com/a/63576721
upvote count: 2
has comment: http://stackoverflow.com/comment/112428026
answers question: http://stackoverflow.com/q/52649815
has comment: http://stackoverflow.com/comment/116511552
has body: These are 8 different solutions I've timed, some of my own and some posted in response to my question, that use 4 broad approaches: spatial cdist spatial KDtree Sklearn BallTree Kernel approach This is the code with the 8 test routines: import numpy as np from scipy import spatial from sklearn.neighbors import BallTree n=500 # size of 2D box f=200./(n*n) # first number is rough number of target cells... np.random.seed(1) # to make reproducable a=np.random.uniform(size=(n,n)) i=np.argwhere(a>-1) # all points, we want to know distance to nearest point j=np.argwhere(a>1.0-f) # set of locations to find distance to. # long array of 3x3 j points: for xoff in [0,n,-n]: for yoff in [0,-n,n]: if xoff==0 and yoff==0: j9=j.copy() else: jo=j.copy() jo[:,0]+=xoff jo[:,1]+=yoff j9=np.vstack((j9,jo)) global maxdist maxdist=10 overlap=5.2 kernel_size=int(np.sqrt(overlap*n**2/j.shape[0])/2) print("no points",len(j)) # repear cdist over each member of 3x3 block def dist_v1(i,j): dist=[] # 3x3 search required for periodic boundaries. for xoff in [-n,0,n]: for yoff in [-n,0,n]:ds=Dataset(path_file) jo=j.copy() jo[:,0]+=xoff jo[:,1]+=yoff dist.append(np.amin(spatial.distance.cdist(i,jo,metric='euclidean'),1)) dist=np.amin(np.stack(dist),0).reshape([n,n]) #dmask=np.where(dist<=maxdist,1,0) return(dist) # same as v1, but taking one amin function at the end def dist_v2(i,j): dist=[] # 3x3 search required for periodic boundaries. for xoff in [-n,0,n]: for yoff in [-n,0,n]: jo=j.copy() jo[:,0]+=xoff jo[:,1]+=yoff dist.append(spatial.distance.cdist(i,jo,metric='euclidean')) dist=np.amin(np.dstack(dist),(1,2)).reshape([n,n]) #dmask=np.where(dist<=maxdist,1,0) return(dist) # using a KDTree query ball points, looping over j9 points as in online example def dist_v3(n,j): x,y=np.mgrid[0:n,0:n] points=np.c_[x.ravel(), y.ravel()] tree=spatial.KDTree(points) mask=np.zeros([n,n]) for results in tree.query_ball_point((j), 2.1): mask[points[results][:,0],points[results][:,1]]=1 return(mask) # using ckdt…
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/92835898
has text: Thank You very much brother I need to learn Qt can you help me. how to start and where to learn it, perfectly
type: AnswerComment
comment on: http://stackoverflow.com/a/52737656
type: Comment
score: 0

http://stackoverflow.com/q/52689716
upvote count: 0
answer count: 1
has title: how filtre huge email list by domain with python
favorite count: 0
has comment: http://stackoverflow.com/comment/92306486
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52692339
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92306309
has comment: http://stackoverflow.com/comment/92306340
type: UnansweredQuestion
score: -4
has body: i need help with python how filtre huge email list by domain with python? my email list contain different email AOl Gmail Hotmail .... i want to select one domain ex Gmail and creat a new file contain only gmail adresses this is the regex function how can i edit it to get only gmail accounts ? regex = re.compile(("([a-z0-9!#$%&amp;*+\/=?^_{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+\/=?^_" "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|" "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))
has comment: http://stackoverflow.com/comment/92306313
type: Question
downvote count: 4

http://stackoverflow.com/a/52732316
accepted answer of: http://stackoverflow.com/q/52732094
answers question: http://stackoverflow.com/q/52732094
downvote count: 0
score: 2
type: AcceptedAnswer
upvote count: 2
type: Answer
has body: Using pd.get_dummies First, use get_dummies: tmp = df.set_index('Name').Activities.str.get_dummies(sep=',') Now using stack and agg: tmp.mask(tmp.eq(0)).stack().reset_index('Name').groupby(level=0).agg(', '.join) Name Baseball Eric, Mike Basketball Mike Soccer Eric, Natasha Swimming Eric Using str.split and melt (df.set_index('Name').Activities.str.split(',', expand=True) .reset_index().melt(id_vars='Name').groupby('value').Name.agg(', '.join))

http://stackoverflow.com/a/52594386
has body: In python, setting a variable actually sets a reference to the variable. Variable names in python are references to the original. The following code should make a copy of C and store in D C= DF.loc[:,'10'] print(C) D= DF.loc[:,'10'].copy() DF.loc[:,'10'] = None print(C)
has comment: http://stackoverflow.com/comment/92124730
type: Answer
answers question: http://stackoverflow.com/q/52594265
has comment: http://stackoverflow.com/comment/92125429
score: 0
accepted answer of: http://stackoverflow.com/q/52594265
type: AcceptedAnswer

http://stackoverflow.com/comment/92217997
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52636081
score: 0
has text: This topic discusses a numpy way to find the interval a value is in. You can use it to find the upper and lower value. https://stackoverflow.com/questions/17118350/how-to-find-nearest-value-that-is-greater-in-numpy-array

http://stackoverflow.com/q/52738452
has comment: http://stackoverflow.com/comment/92401434
score: 1
type: Question
has body: I have a list in python a=['one_foo','two_foo','bar_foo'] Expected output: ['one','two','bar'] I tried doing by first converting list into string and then using regex import re re.sub("_.*$","", str(a)) I know converting list to string is incorrect way to achieve this task,may be is there any elegant way without converting it to string?
has comment: http://stackoverflow.com/comment/92401555
has comment: http://stackoverflow.com/comment/92401442
linked to: http://stackoverflow.com/q/6696027
downvote count: 0
has answer: http://stackoverflow.com/a/52738517
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/92401673
favorite count: 0
duplicate of: http://stackoverflow.com/q/6696027
upvote count: 1
tagged with: python
has title: Delete a element using regex from list in python
tagged with: regex
duplicate of: http://stackoverflow.com/q/3094659
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/52738517

http://stackoverflow.com/a/62036469
answers question: http://stackoverflow.com/q/52699990
upvote count: 1
type: Answer
has body: Since you didn't mention rows with 0 count, may be this can help you def getRange(start, end, aggregate): query = db.select([ func.max(Simulation.timestamp).label('timestamp'), func.sum(Simulation.PVPowerOutput).label('PVPowerOutput'), func.sum(Simulation.ACPrimaryLoad).label('ACPrimaryLoad')\ ])\ .where(Simulation.timestamp &gt;= start)\ .where(Simulation.timestamp &lt;= end)\ if aggregate == 'hourly': # do nothing query = query.group_by(Simulation.timestamp) elif aggregate == 'daily': # group by date query = query.group_by(func.date(Simulation.timestamp)) elif aggregate == 'monthly': # group by month query = query.group_by(func.date_part('month', Simulation.timestamp)) else: raise ValueError('invalid aggregation') return [dict(r) for r in db.session.execute(query).fetchall()]
downvote count: 0
score: 1

http://stackoverflow.com/comment/92386786
type: Comment
has text: @MadPhysicist It is as relevant as assuming that all the OP wants to do is print out the values while the only thing being asked is how to iterate through every value. The fact of the matter is, we don't know what needs to happen with items in the dictionary. I also cannot (read will not) assume what research the OP has done prior to posting this question, or what specifically is misunderstood. This isn't laziness on my end. There are a lot of great explanations that are already out there. Some of them provided by users on stackoverflow.
comment on: http://stackoverflow.com/a/52684937
score: 0
type: AnswerComment

http://stackoverflow.com/a/52678485
score: 3
upvote count: 3
has body: lets take an example dataframe as below df = pd.DataFrame({"a":[1,2,3,4,5],"b":[2,4,9,16,25]}) index method prints as below In [4]: df.index Out[4]: RangeIndex(start=0, stop=5, step=1) and df.index &gt;3 prints as below In [5]: df.index&gt;3 Out[5]: array([False, False, False, False, True]) so, answer is y = df.index&gt;3 df['new_column'] = y.astype(int) df a b new_column 0 1 2 0 1 2 4 0 2 3 9 0 3 4 16 0 4 5 25 1 Edit: if you want to do between 3 and 9 indexes you do the following import numpy as np np.logical_and(df.index&gt;2, df.index&lt;5) array([False, False, False, True, True])
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52678422
type: Answer
answers question: http://stackoverflow.com/q/52678422

http://stackoverflow.com/comment/92400941
has text: I just edited the post. My issue is that I'm getting negative numbers which is making me doubt how I calculate my diversity, I think there's something wrong somewhere but I can't pinpoint it.
comment on: http://stackoverflow.com/q/52738057
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92268313
has text: What does `within a range of 3` mean? You have what seems to be a `DatetimeIndex` but it's not monotonic, so are we considering the dates or just the row index? Your question asks for `within a Time Range` but your output completely ignores the time
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52669112
score: 1

http://stackoverflow.com/a/61152866
downvote count: 0
answers question: http://stackoverflow.com/q/52625812
score: 9
has body: Got the same problem using S3 on Dell ECS object storage. The S3 protocol is implemented partially so there's no support for POST method with ECS. The workaround is to use correct headers in PUT methtod, then the ACL for the object are set correctly on the server. # Get the service client. s3 = boto3.client('s3') boto3.set_stream_logger(name='botocore') # Generate the URL to get 'key-name' from 'bucket-name' url = s3.generate_presigned_url( ClientMethod='put_object', Params={ 'Bucket': s3_bucket_name, 'Key': test_key, 'ACL': 'public-read' } ) files = StringIO("asdfasdfasdf") headers = {'x-amz-acl': 'public-read'} response = requests.put(url, data=files, headers=headers) print(str(response.content))
upvote count: 9
type: Answer

http://stackoverflow.com/a/52653832
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52653782
type: Answer
answers question: http://stackoverflow.com/q/52653782
score: 4
has body: If you aren't using an app, it is perfectly acceptable to remove it from your INSTALLED_APPS in your projects's settings.py. This is what I have, and I don't have unused apps clogging my migration history. INSTALLED_APPS = [ 'django.contrib.contenttypes', 'my_app_name_redacted', ] If you are using it, you need to do the migrations for them to work properly. Incidentally, if you want to only migrate for a specific app, but keep them installed so you can later, you can add the app name in the manage.py migrate command. python manage.py makemigrations my_app_name_redacted python manage.py migrate my_app_name_redacted

http://stackoverflow.com/comment/92410627
score: 2
comment on: http://stackoverflow.com/q/52736396
type: Comment
type: QuestionComment
has text: DO NOT poll the clipboard in a loop like this. The correct way to monitor for changes in real time is to use `AddClipboardFormatListener()` (Vista+) or `SetClipboardViewer()` (pre-Vista) instead

http://stackoverflow.com/comment/92294363
type: Comment
comment on: http://stackoverflow.com/q/52683118
type: QuestionComment
has text: There doesn't seem anything in this code that would cause the `while` loop to terminate *or* find a new `enemy` after the current one is defeated
score: 2

http://stackoverflow.com/comment/92345855
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52709667
type: Comment
has text: In my above example, letter 'a' indicate employer, while digits '12' etc indicate employee.

http://stackoverflow.com/comment/102772732
type: Comment
has text: @Jensenmann, Hi, that's exactly what I'm trying to do. Did you find a good solution?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52598157

http://stackoverflow.com/comment/92307169
score: 0
comment on: http://stackoverflow.com/q/52689967
type: Comment
type: QuestionComment
has text: maximum of ten words meaning it can be anything below 10?

sympy
tags question: http://stackoverflow.com/q/52733969
tag name: sympy
tags question: http://stackoverflow.com/q/52706723
tags question: http://stackoverflow.com/q/52722676
tags question: http://stackoverflow.com/q/52683383
tags question: http://stackoverflow.com/q/52692068
tags question: http://stackoverflow.com/q/52654760
tags question: http://stackoverflow.com/q/52744190
tags question: http://stackoverflow.com/q/52725708
tags question: http://stackoverflow.com/q/52649425
tags question: http://stackoverflow.com/q/52619164
tags question: http://stackoverflow.com/q/52638892
tags question: http://stackoverflow.com/q/52700878
type: Tag
tags question: http://stackoverflow.com/q/52619874
tags question: http://stackoverflow.com/q/52730086
tags question: http://stackoverflow.com/q/52683973

http://stackoverflow.com/q/52652522
has body: I have downloaded a sample dataset from here that is a series of JSON objects. According to the website, each JSON object looks like below { "id": "4cd223df721b722b1c40689caa52932a41fcc223", "title": "Knowledge-rich, computer-assisted composition of Chinese couplets", "paperAbstract": "Recent research effort in poem composition has focused on the use of automatic language generation...", "entities": [ "Conformance testing", "Natural language generation", "Natural language processing", "Parallel computing", "Stochastic grammar", "Web application" ], "s2Url": "https://semanticscholar.org/paper/4cd223df721b722b1c40689caa52932a41fcc223", "s2PdfUrl": "", "pdfUrls": [ "https://doi.org/10.1093/llc/fqu052" ], "authors": [ { "name": "John Lee", "ids": [ "3362353" ] }, "..." ], "inCitations": [ "c789e333fdbb963883a0b5c96c648bf36b8cd242" ], "outCitations": [ "abe213ed63c426a089bdf4329597137751dbb3a0", "..." ], "year": 2016, "venue": "DSH", "journalName": "DSH", "journalVolume": "31", "journalPages": "152-163", "sources": [ "DBLP" ], "doi": "10.1093/llc/fqu052", "doiUrl": "https://doi.org/10.1093/llc/fqu052", "pmid": "" } Eventually I need to work with the paperAbsrtract section only. I am loading this to a pandas dataframe like below filename = "sample-S2-records" df = pd.read_json(filename, lines=True) df.head() This shows all the doi and doiUrl column empty. Also if I only select abstract column and check out the head, I see 2 of the 5 rows empty abstract = df['paperAbstract'] abstract.head() 0 1 The search for new administrators in complex s... 2 The human N-formyl peptide receptor (FPR) is a... 3 Serum CA 19-9 (2-3 sialyl Le(a)) is a marker o... 4 Name: paperAbstract, dtype: object Looks like the way I have created the dataframe is not the right approach. I am pretty confident they don't have any missing column. What am I missing? Any suggestion?
has answer: http://stackoverflow.com/a/52652981
has title: Series of JSON objects to dataframe conversion
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/52652981
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
type: Question

http://stackoverflow.com/a/52618281
answers question: http://stackoverflow.com/q/52618197
type: Answer
accepted answer of: http://stackoverflow.com/q/52618197
score: 0
has body: You can use random.randrange to draw a value between 0 and the sum of all dict values, use itertools.accumulate to generate a sequence of cumulative sums from the values, and then use itertools.dropwhile to look for the first cumulative sum that isn't less than the draw, and return the key of the dict at that index, as accompanied by the cumulative sum through the use of enumerate: import random from itertools import accumulate, dropwhile def pick(d): draw = random.randrange(sum(d.values())) return list(d.keys())[next(dropwhile(lambda t: t[1] &lt; draw, enumerate(accumulate(d.values()))))[0]] so that: from collections import Counter d = {'A': 10, 'B': 30, 'C': 60} print(Counter(pick(d) for _ in range(1000))) can output: Counter({'C': 587, 'B': 286, 'A': 127})
type: AcceptedAnswer

http://stackoverflow.com/a/52670443
type: Answer
answers question: http://stackoverflow.com/q/52670383
score: 1
upvote count: 1
has body: import random l = [random.randint(0,50) for i in range(5)] l.extend([random.randint(0,12) for i in range(2)]) print(l)
downvote count: 0

http://stackoverflow.com/comment/92271039
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52670595
has text: @user2357112 so the output should start with digit that's more than 0

http://stackoverflow.com/q/52602311
type: Question
has answer: http://stackoverflow.com/a/52602413
accepted answer: http://stackoverflow.com/a/52602413
has comment: http://stackoverflow.com/comment/92171698
has comment: http://stackoverflow.com/comment/92145970
score: 0
tagged with: pandas
upvote count: 1
has body: I am trying to transition some code over to Python from Stata. The following code is used to drop duplicate observations for the same id variable on the same date: quietly by id date: gen dup = cond(_N==1,0,_n) drop if id &gt;= 1 The below code is used to generate a sample python dataset. What the above code in Stata does is drop the duplicate observations. For example, on date 2014-05-01, id 1 has the same data in twice, as well as date 2014-05-02, id 2 etc. However, I would only like the data to appear once. Would anyone happen to know the equivalent code in Python? data = {'date': ['2014-05-01', '2014-05-01','2014-05-01','2014-05-01','2014-05-01', '2014-05-02','2014-05-02','2014-05-02','2014-05-02','2014-05-03', '2014-05-03','2014-05-03','2014-05-03'],'id':[1, 1, 2, 3, 4, 1, 2, 2, 3, 1, 1, 2, 3],'obs': [10, 10, 5, 7, 3, 2, 4, 4, 3, 8, 8, 6, 11]} df1 = pd.DataFrame(data, columns = ['date', 'id','obs']) df1.index = df1['date'] del df1['date'] df1 Initial Data Out[1]: id obs date 2014-05-01 1 10 2014-05-01 1 10 2014-05-01 2 5 2014-05-01 3 7 2014-05-01 4 3 2014-05-02 1 2 2014-05-02 2 4 2014-05-02 2 4 2014-05-02 3 3 2014-05-03 1 8 2014-05-03 1 8 2014-05-03 2 6 2014-05-03 3 11 Wanted Data Out[2]: id obs date 2014-05-01 1 10 2014-05-01 2 5 2014-05-01 3 7 2014-05-01 4 3 2014-05-02 1 2 2014-05-02 2 4 2014-05-02 3 3 2014-05-03 1 8 2014-05-03 2 6 2014-05-03 3 11
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has title: Equivalence of Stata drop duplicates code in Python
tagged with: python
tagged with: stata
type: AnsweredQuestion
tagged with: duplicates

http://stackoverflow.com/q/52708821
answer count: 0
has comment: http://stackoverflow.com/comment/92454333
tagged with: machine-learning
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92452972
has comment: http://stackoverflow.com/comment/92453365
has body: I am trying to design bi-directional LSTM using word2vec features for binary classification problem. my_model=Sequential() my_model.add(Embedding(words,10,input_length=trainDataVecs.shape[1],weights=[embedding_matrix],trainable=True)) my_model.add(Bidirectional(LSTM(20,activation='tanh',init='glorot_uniform',recurrent_dropout = 0.2, dropout = 0.2))) Since there are two classes, my_model.add(Dense(2, activation='softmax')) def auc(y_true, y_pred): auc = tf.metrics.auc(y_true, y_pred)[1] K.get_session().run(tf.local_variables_initializer()) return auc Using AUC as the metrics print "Compiling..." optimizer=RMSprop(lr=0.0001, rho=0.9, epsilon=1e-08) my_model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=[auc]) my_model.fit(trainDataVecs, Y_train, shuffle = True, batch_size = 10, epochs=20) But I am getting : ValueError: Error when checking target: expected dense_2 to have shape (2,) but got array with shape (1,) as Y_train is 1-D. I can use sigmoid instead of softmax but that will give me the probability when I will predict. My labels are 0 or 1. Hence, I want to see the F-score between the predicted and the real values.
score: 0
has comment: http://stackoverflow.com/comment/92344502
tagged with: deep-learning
tagged with: keras
linked to: http://stackoverflow.com/q/42081257
has comment: http://stackoverflow.com/comment/92453449
type: UnansweredQuestion
tagged with: python
has title: Binary Classification using softmax LSTM

http://stackoverflow.com/comment/92189650
has text: One more question on your answer, how can I select the latest grade record for each grade value? e.g. `grade: AW, key1` and 'grade: AW, key2' will led to only `grade: AW, key1` because it's the latest one for `grade: AW`
comment on: http://stackoverflow.com/a/52623590
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52629789
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52610368
score: 1
has comment: http://stackoverflow.com/comment/92289639
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92512368
has comment: http://stackoverflow.com/comment/92231196
has body: Not sure what's going on, you can explicitly assign an alias using: fn.MAX(EquityModel.date).alias('date'). Is EquityModel.date a computed field, or is it a normal column?
answers question: http://stackoverflow.com/q/52610368

http://stackoverflow.com/q/52721083
has body: I have the following html code: 5 times 6 times I managed to navigate the tree, but when trying to print I get the following error: AttributeError: 'list' object has no attribute 'text' Python code working: x=soup.select('.f1') print(x) gives the following: [] [] [] [] [ 19 times] [ 12 times] [ 6 times] [] [] [] [ 6 times] [ 1 time] [ 11 times] but print(x.prettify) throws the error above. I am basically trying to get the text between the span tags for all instances, blank when none and string when available.
has title: Beautifulsoup AttributeError: 'list' object has no attribute 'text'
tagged with: python
accepted answer: http://stackoverflow.com/a/52721738
has answer: http://stackoverflow.com/a/52721534
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52721738
type: Question
has comment: http://stackoverflow.com/comment/92367652
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/52721463
has answer: http://stackoverflow.com/a/52721463
tagged with: beautifulsoup

http://stackoverflow.com/q/52596576
has title: What is the way to ignore/skip some issues from python bandit security issues report?
upvote count: 58
favorite count: 0
has answer: http://stackoverflow.com/a/72716219
tagged with: django
tagged with: python
tagged with: bandit-python
has answer: http://stackoverflow.com/a/52611552
accepted answer: http://stackoverflow.com/a/52611552
has answer: http://stackoverflow.com/a/72906810
tagged with: django-admin
possible better answer: http://stackoverflow.com/a/61447529
downvote count: 0
has answer: http://stackoverflow.com/a/61447529
answer count: 5
score: 58
has answer: http://stackoverflow.com/a/61704132
has body: I've got a bunch of django_mark_safe errors &gt;&gt; Issue: [B703:django_mark_safe] Potential XSS on mark_safe function. Severity: Medium Confidence: High Location: ... More Info: https://bandit.readthedocs.io/en/latest/plugins/b703_django_mark_safe.html 54 return mark_safe(f'&lt;a href="{url}" target="_blank"&gt;{title}&lt;/a&gt;') &gt;&gt; Issue: [B308:blacklist] Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed. Severity: Medium Confidence: High Location: ... More Info: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b308-mark-safe 54 return mark_safe(f'&lt;a href="{url}" target="_blank"&gt;{title}&lt;/a&gt;') And I'm curious if there is a way to skip or ignore such lines? I understand that using mark_safe could be dangerous, but what if I want to take the risk? For example this method is the only way to display custom link in Django admin, so I don't know any other option how to do it without mark_safe
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/92141561
comment on: http://stackoverflow.com/q/52603477
has text: Hi @Shaun, could you please post what you have tried so far? And could you please add example data to your code so that it's easier for people to help you out? Your question looks now a bit too broad to get a good answer...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52727681
upvote count: 4
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52728394
score: 4
has title: Why is a Django migration using the same random default on every row?
accepted answer: http://stackoverflow.com/a/52728394
favorite count: 0
tagged with: postgresql
tagged with: python
has comment: http://stackoverflow.com/comment/124042346
type: AnsweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/92380581
has body: Note: I understand and am well aware of the difference between passing a function as a parameter and invoking a function and passing the result as a parameter. I believe I am passing the function correctly. Specs Django 1.11 PostgreSQL 10.4 Scenario: I have dozens of models in my application, with many existing records. I need to add a random seed to each of these models that will get created and set when a new model instance is created. I also want to generate the random seed for the existing instances. My understanding of how Django model defaults and Migrations work is that when a new field is added to a model, if that field has a default value set, Djano will update all existing instances with the new field and corresponding default. However, despite the fact that I'm definitely passing a function as the default, and the function produces a random number, Django is using the same random number when updating existing rows (e.g. it seems that Djano is only calling the function once, then using the return value for all entries). Example A shortened version of my code: def get_random(): return str(random.random()) class Response(models.Model): # various properties random = models.CharField(max_length=40, default=get_random) user = models.ForeignKey(User, on_delete=models.CASCADE) content = JSONField(null=True) The random field is being added after the model and many instances of it have already been created. A makemigrations command appears to generate the proper migration file, with a migrations.AddField() call, passing in default=get_random as a parameter. However, after running makemigrations, all existing existing Response instances contain the exact same number in their random field. Creating and saving new instances of the model work as expected (with a pseudo-unique random number). Workaround An easy workaround is to just run a one-time script that does a for r in Response.objects.all(): r.random = get_random() r.save() Or override the model's save() method a…

http://stackoverflow.com/q/52595944
answer count: 1
has body: I working with SDN and network flows within mininet. I'm able to display flows between to hosts and write it into a file, now I want to output specific information. I want to display all n_bytes values from the file see picture below I was thinking about writeing all of these values into a list in Python and the use list operations to display n_bytes, with open("/path/to_myfile","r") as f n_bytes_num=[line.strip() for line in f] print(n_bytes_num[1] this just prints the whole output of the file shown above. print (n_bytes_num [ 1][ 1] just prints out c. How would I go by doing this, maybe its more efficient to use tuples and have all these as key_values? Later I was thinking about making the user type which values they want to see with input()
has title: Values from a list of of values
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52596043
tagged with: list
score: -1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/92126693
tagged with: tuples

http://stackoverflow.com/comment/92226736
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52642712
has text: Well, neither edit really made the question clearer to me. From the accepted answer, you are looking for *how many leading entries from ListA are found in ListB*. Is that correct? Thus you start to look through listA at the start. You go and look whether that item is in listB. And then you continue towards the end of listA and stop when you hit an element in A which you do not find in listB. That problem is not well explained so far, IMHO :) Especially that you are looking only at the start of listA and stop iteration when you find a non-match
score: 0

http://stackoverflow.com/comment/92338441
type: AnswerComment
has text: Thank you!!!. I cast the output of the function to float, then using your solution, I get the exact value.
type: Comment
comment on: http://stackoverflow.com/a/52701064
score: 0

http://stackoverflow.com/comment/92195007
comment on: http://stackoverflow.com/q/52619815
score: 0
type: Comment
type: QuestionComment
has text: If you click the checkmark beside an answer below you'll mark it as accepted for future readers to know it worked for you.

http://stackoverflow.com/a/52738011
answers question: http://stackoverflow.com/q/52735995
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has body: Password management is always a very delicate topic, but since you are just starting and not asking about security, let's se how we can load and write a simple JSON file in a very easy way. First, lets move the actual data to a separate file, wich we can name as database.json: {"email": "F7minlBDDuvMJuxESSKHFhTxFtjVB6", "blog": "VmALvQyKAxiVH5G8v01if1MLZF3sdt", "luggage": "12345"} Then we change the application code like this: #!/usr/env python3 """ pw.py - An insecure password locker program. """ import sys import pyperclip import json import os # The path to the database file DB_FILE = "~/Desktop/database.json" def main(): if len(sys.argv) &lt; 2: print('Usage: python pw.py [account] - copy account password') sys.exit() account = sys.argv[1] # first command line arg is the account name db = os.path.expanduser(DB_FILE) with open(db) as f: data = json.load(f) # Load a dictionary for disk if account in data: pyperclip.copy(data[account]) print('Password for ' + account + ' copied to clipboard.') else: print('There is no account named ' + account) print('Input the password for the said account to update the info.') new_passwd = {account: input()} # create a dictionary with the new account data data.update(new_passwd) # update the main dictionary with the new data with open(db, 'w') as f: json.dump(data, f) # convert to JSON and write to disk print('Info updated!') if __name__ == "__main__": main() For such a simple task, there are a number of file formats that you could use. JSON is a format that maps to Python dictionaries in a way that is both logical and easy to understand, but you could also implement it in CSV without adding much complication. But in this kind of applications, you will very soon feel the need for something more practical and robust. For instance, as your database grows, it may start to be impractical to load the whole database into memory. And it could raise even more security issues. Take your time learning the basics like these and then explore…
accepted answer of: http://stackoverflow.com/q/52735995

http://stackoverflow.com/comment/92304279
comment on: http://stackoverflow.com/q/52688527
type: Comment
has text: CGI programs work by sending HTML through the standard output stream, so that's what the print statement is doing. It is sending the header. `q` is a reference to an an object of class `CGI`.
score: 2
type: QuestionComment

http://stackoverflow.com/a/52713055
downvote count: 0
type: Answer
has body: You can use lookahead patterns: import re s = 'base_A23x4_B534x5_C654x6_D2363x45' basename, *numbers = re.match(r'([^_]+)(?=.*(?&lt;=_)A(\d+x\d+))(?=.*(?&lt;=_)B(\d+x\d+))(?=.*(?&lt;=_)C(\d+x\d+))(?=.*(?&lt;=_)D(\d+x\d+))', s).groups() A, B, C, D = [n.replace('x', '.') for n in numbers] so that basename, A, B, C, D will become: base 23.4 534.5 654.6 2363.45 and with the value of A moved to the end of the string: s = 'base_B534x5_C654x6_D2363x45_A23x4' the result will stay the same. EDIT: Given your new requirements that there may be any number of alphabet combinations in the string, you should split the string into tokens as convert them to a dict instead: import re s = 'base_A23x4_B534x5_C654x6_D2363x45_AA12x3' basename, *tokens = s.split('_') print({k: v.replace('x', '.') for k, v in dict(re.match(r'([A-Z]+)([\dx]+)', n).groups() for n in tokens).items()}) This outputs: {'A': '23.4', 'B': '534.5', 'C': '654.6', 'D': '2363.45', 'AA': '12.3'}
score: 1
has comment: http://stackoverflow.com/comment/92352140
has comment: http://stackoverflow.com/comment/92352111
answers question: http://stackoverflow.com/q/52712987
upvote count: 1

http://stackoverflow.com/q/52595584
has comment: http://stackoverflow.com/comment/92128787
has answer: http://stackoverflow.com/a/52599082
answer count: 1
downvote count: 0
tagged with: string
favorite count: 0
tagged with: python-3.x
has body: given a string, I want to find all the sub-strings which can be formed from the original string which are divisible by an integer k. For example the string 14917 can form 7 sub-strings which are divisible by the integer 7. The sub-strings are: 14, 1491, 14917, 49, 91, 917 and 7. I have come up with a solution but it does not run efficiently when a large string is inputted. My code is string = '14917' divider = 7 count = 0 for i in range(len(string)): for j in range(i+1, len(string)+1): sub_string = string[i:j] if int(sub_string) % divider == 0: count += 1 print(count) I have read about fast approaches for this kind of a problem, most of which talked about computing the rolling remainders of the string but I could not really implement it correctly. Is there any way in which this problem can be solved quickly. Thanks in advance.
has title: Find the number of substrings of a string which can be divisible by a number k
tagged with: python
accepted answer: http://stackoverflow.com/a/52599082
has comment: http://stackoverflow.com/comment/92126174
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92136539
has comment: http://stackoverflow.com/comment/92128611
has comment: http://stackoverflow.com/comment/92132112
has comment: http://stackoverflow.com/comment/92128778
has comment: http://stackoverflow.com/comment/92136474
has comment: http://stackoverflow.com/comment/92127020
type: Question
tagged with: algorithm
tagged with: math
score: 4
upvote count: 4

http://stackoverflow.com/comment/92290737
type: AnswerComment
type: Comment
has text: can you add hard coded pause `Thread.sleep` for few second and check ? just for debugging
comment on: http://stackoverflow.com/a/52677896
score: 0

http://stackoverflow.com/a/52649588
answers question: http://stackoverflow.com/q/52642756
has body: As requested by OP, I am posting my comment as an answer and try to elaborate more: It seems your model size is big and therefore you need to either use a smaller batch size (&lt; 32, since you mentioned it does not work with 32) or modify the model and decrease the number of parameters (e.g. removing some layers, decreasing the number of filter or units, etc.).
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52642756
downvote count: 0
score: 1

http://stackoverflow.com/comment/92287404
comment on: http://stackoverflow.com/q/52675374
has text: Even with a tuple, i'm still passing two arguments to the function: the bin_input and the tuples. The documentation for the library you posted shows parallel processing for 1 argument. @rishav could you perhaps provide a pseudocode for your suggestion?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92254318
has text: @brunodesthuilliers: well the nice thing about regexes (given these are well implemented) is that these use dynamic programming, and thus can convert an *O(m n)* approach, into an *O(m+n)* approach :)
comment on: http://stackoverflow.com/q/52661069
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92201414
has text: If I change the column names to random names the code does not do the job.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52615770
type: Comment

http://stackoverflow.com/q/52654327
has answer: http://stackoverflow.com/a/52654457
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92240428
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/92240366
type: Question
answer count: 2
downvote count: 0
has title: Python - How to create new Json file after every loop?
has comment: http://stackoverflow.com/comment/92240283
has comment: http://stackoverflow.com/comment/92240190
has answer: http://stackoverflow.com/a/52654452
has comment: http://stackoverflow.com/comment/92240344
has body: So I have a CSV file that I convert later on to a JSON file. However what I want to do is that I want to save to a new json file for every json objects that is new. Meaning something like this: { "first_name": "Hello", "last_name": "World", "color": "black" }, { "first_name": "Stack", "last_name": "Overflow", "color": "Red" } How I change it to a format from CSV to JSON is that I create it as a dict where I have the CSV format and a fieldsname that is created based on "first_name", "last_name_" and color. It would look like something like: jsonfile = open('newfilejson.json', 'w') fieldnames = ("first_name","last_name","color") reader = csv.DictReader(csvfile, fieldnames) for row in reader: jsonfile.write('"first_name": "' + row['first_name'] + '",\n') jsonfile.write('"last_name": "' + row['last_name'] + '",\n') jsonfile.write('"color": "' + row['color'] + '",\n') however this will just save into one file basically and my question is: How can I make so everytime it finished one "row" from the for-loop to create a new json file that contains whats inside the for-loop (With write) and then whenever there is new, it creates a new json file. Basically meaning that everytime a row is finished, create new json?
tagged with: python
has comment: http://stackoverflow.com/comment/92240312
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92240254
possible better answer: http://stackoverflow.com/a/52654457
accepted answer: http://stackoverflow.com/a/52654452

http://stackoverflow.com/a/52680068
has body: The problem is your command prompt uses cp437 character set, which doesn't support some characters that you have just scraped (for example, “ and ”) I don't think it is possible to print that characters to windows shell (maybe new PowerShells support it, I don't know). You may create a new file, select a rich character set for it, and write all your output there: import io out_file = io.open('output.txt', 'a', encoding='UTF-8') If you really want to use the default character encoding that your operating system uses, create the file like that: import io out_file = io.open('output.txt', 'a', errors='backslashreplace') With the latter option, you will see something like that: “The world as we have created it is a process of our thinking.”
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52678981

http://stackoverflow.com/comment/92379029
type: Comment
type: QuestionComment
score: 0
has text: @shmee would using the `setattr` function make the input attributes of the `Enum` instance?
comment on: http://stackoverflow.com/q/52712796

http://stackoverflow.com/q/52720634
has answer: http://stackoverflow.com/a/52721806
accepted answer: http://stackoverflow.com/a/52721806
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92366432
score: -1
type: Question
upvote count: 0
has title: Panda keep/ add column that was "lost" during groupby and agg
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92367036
has body: Hej guys, I am working on a cohorts script that shows the CM2 (= Contribution margin 2) development of a Google ad account for each day looking back the last 30 days. I have a dataframe, based on a last 30 days Campaign Performance Report, that looks like this and goes on for over 1000 rows: | Date |Sale| CM2 |Views|Click|CPC |CTR | CPM |Cost |Data_PullDate 0|2018-09-09|3 |37.44|1436 |77 |0.25|5.36|13.86|19.91|2018-10-09 1|2018-09-09|0 | 0.00|1359 | 6 |0.29|0.44| 1.31| 1.79|2018-10-09 2|2018-09-10|0 | 0.00| 98 | 3 |0.38|3.06|11.63| 1.14|2018-10-09 3|2018-09-10|3 |38.04|2524 |83 |0.30|3.29|10.08|25.46|2018-10-09 I group the data by the Date-column and then calculate the sum or mean for the KPI columns with Pandas' agg function: grouped_data = df.groupby(df['Date']).agg({'Sales':['sum'],'CM2':['sum'],'Views':['sum'],'Click':['sum'],'CPC':['mean'],'CTR':['mean'],'CPM':['mean'],'Cost':['sum']}) The outcome is as expected the sum and means of the columns by date: Date | Cost | CPM |CTR | Views|CPC | CM2 |Sale|Click sum mean mean sum mean sum sum sum 2018-09-09|1971.78|19.44|6.27|108821|0.40|4903.63|188 |5585 2018-09-10|1936.36|20.11|5.91| 94401|0.41|4263.38|194 |4914 As one can tell from the difference in the column count, from the initial dataframe's columns the column Data_PullDate is missing but this column is crucial for me to proceed with the cohorts. This column represents the date the data was pulled and is the date the script ran. How do I keep/ add the column Data_PullDate to the grouped_data dataframe? Also, how do I keep the initial order of the columns?
tagged with: pandas
has comment: http://stackoverflow.com/comment/92367179
tagged with: python

http://stackoverflow.com/a/52759335
has comment: http://stackoverflow.com/comment/92541512
has body: I think you have too low learning rate and too few epochs. try with lr = 0.001 and epochs = 100.
type: Answer
answers question: http://stackoverflow.com/q/52598959
downvote count: 1
score: 5
upvote count: 6

http://stackoverflow.com/a/52603460
score: 0
answers question: http://stackoverflow.com/q/52603029
has body: I see that the desired div content what you are looking at is generated by some javascript code. i.e: when you click on the "Wind" button displayed on page, javascript modify the HTML and generate the wind div for 7 days. With the soup you generated with the given URL, I see there is only a single entry of wind speed div. This is something which is shown on the page. In [7]: soup.findAll("span", text = re.compile("km/h")) Out[7]: [16 km/h] So, scraping these type of page which update HTML based on some javascript modification won't be a good idea to scrap using request module. I would suggest accessing these types of the page you should use python-selenium.
type: Answer
has comment: http://stackoverflow.com/comment/92141782

http://stackoverflow.com/comment/92301361
comment on: http://stackoverflow.com/a/52686956
has text: not working :( it just print nothing found while my browser are running
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92248268
comment on: http://stackoverflow.com/a/52658829
type: AnswerComment
score: 0
type: Comment
has text: You can easily do that with `print("You have selected '{}' which does '{}' damage".format('weapon1', inventoryitems["weapon1"])`.

http://stackoverflow.com/comment/92420614
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52740474
has text: Oh I'm certain I'm right on the ragged edge of memory of the bus. I designed the system to be about 5% less than the max. I separated the configuration commands from the pull commands to reduce traffick of 4 processors querying the same image. I'm just curious why it always works after a reset, but not consecutively.
score: 0

http://stackoverflow.com/q/52708618
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92343484
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52708754
tagged with: loops
type: Question
tagged with: for-loop
has body: Three-letter set, composed of 'A', 'U', 'G' or 'C', is defined as codon. Each codon corresponds to the one of 20 letter. Set of those letters (amino acids) is defined as protein. The file "codons.txt" contains codons and corresponding letters. The problem is next: The inner for loop works only once — it compares lines from the txt file only with the first codon. Then, as I understand, the method skips the inner loop. Code: path = r'C:\Users\...\codons.txt' f = open(path, 'r') def prot(DNA): protein = '' a = True for i in range (0, len(DNA)-2,3): codon = DNA[i:i+3:1] print(codon) for line in f: if line[0:3:1] == codon: protein += line[4:5:1] print(protein) return protein prot('AGUCAGGAUAGUCUUA') Output: AGU S CAG GAU AGU CUU The question is next: How to make the inner loop work for each codon?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92343604
answer count: 1
has title: How do I make the inner loop consider each iteration of the outer loop?
has answer: http://stackoverflow.com/a/52708754
has comment: http://stackoverflow.com/comment/92343599
tagged with: bioinformatics

http://stackoverflow.com/q/52612455
tagged with: lstm
has comment: http://stackoverflow.com/comment/92166656
tagged with: keras
score: 0
tagged with: python
tagged with: nlp
answer count: 0
has title: tensorflow.python.framework.errors_impl.InvalidArgumentError: in KERAS LSTM model
has comment: http://stackoverflow.com/comment/92359594
type: UnansweredQuestion
tagged with: tensorflow
type: Question
has body: I have the following lstm model: class LSTM_model(): def __init__(self): w2v_model = gensim.models.Word2Vec(sentences, size=150, window=10, min_count=2, workers=10) pretrained_weights = w2v_model.wv.syn0 vocab_size, emdedding_size = pretrained_weights.shape self.w2v_model = w2v_model self.keras_lstm_model = Sequential() self.keras_lstm_model.add(Embedding(input_dim = vocab_size, output_dim = emdedding_size, weights = [pretrained_weights])) self.keras_lstm_model.add(LSTM(units = emdedding_size)) self.keras_lstm_model.add(Dense(units = vocab_size)) self.keras_lstm_model.add(Activation('sigmoid')) self.keras_lstm_model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['mae','acc']) My aim is to predict probablity of a given word in a context. I have list of sentences and I want to train this model: def train_lstm_model(self, sentences): sentences_as_indexes = [] filtered_sentences = list(filter(lambda x : all([w in self.w2v_model.wv.vocab for w in x]) , sentences)) #filter to take only sentences with no OOV words for sentence in filtered_sentences: if all([w in self.w2v_model.wv.vocab for w in sentence]): #todo use filter indexes_row = [] for word in sentence: idx = self.w2v_model.wv.vocab.get(word).index indexes_row.append(idx) sentences_as_indexes.append(indexes_row) X = pd.DataFrame([sentence[:-1] for sentence in sentences_as_indexes]) y = pd.DataFrame([sentence[-1] for sentence in sentences_as_indexes]) print(datetime.datetime.now(), ": Fitting LSTM model , size of X is ", X.shape) self.keras_lstm_model.fit(X, y) #HERE the error Where sentences is list of around 1M sentences (my training set). I Get the following error in the fit(): tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[7,38] = -2147483648 is not in [0, 694415) [[Node: embedding_1/embedding_lookup = GatherV2[Taxis=DT_INT32, Tindices=DT_INT32, Tparams=DT_FLOAT, _class=["loc:@training/Adam/Assign_2"], _device="/job:localhost/replica:0/task:0/device:CPU:0"…

http://stackoverflow.com/q/52732565
answer count: 1
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52735547
tagged with: linux
tagged with: windows
tagged with: python
type: AnsweredQuestion
tagged with: django
type: Question
has title: Best way to run task on Windows from web server on Linux
has answer: http://stackoverflow.com/a/52735547
has body: I have a task written in Python with a 1-2 minute run-time that I want to run on-demand. The requests would come In very small volumes from a Django server on Linux. The return would be a file. Usually, I'd use a queue system like Celery. But, this task can only be run on Windows. What is the best way to make this happen? Remotely execute the task by establishing an SSH session? Still use Celery, go through a lot of workarounds to get it to work on Windows (seems messy)?
score: 0

http://stackoverflow.com/comment/92341431
type: Comment
has text: Thanks @Julien I've just added some raws which weren't in settings.py before then deployed it with changes, but it hasn't helped so far.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52689578

http://stackoverflow.com/comment/92224885
has text: You can fall back to numpy if you want to remove those elements and end up with a 1d structure: `df.values[boolean_filter]`.
comment on: http://stackoverflow.com/q/52646162
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52714613
favorite count: 0
upvote count: 3
tagged with: pandas
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/92354939
has title: Updating dataframe ID w.r.t missing dates column values
score: 3
accepted answer: http://stackoverflow.com/a/52714805
has body: I am trying to update the ID of dataframe with respect to the missing days of date column in dataframe, Date ID 0 2018-01-01 45.0-A 1 2018-01-02 45.0-A 5 2018-01-06 45.0-A 6 2018-01-07 45.0-A 12 2018-01-13 45.0-A 13 2018-01-14 45.0-A period = 2 If the dataframe has more than specified period (period =2 )of days missing ID should updated with extra number, I solved this with time difference and looping over dataframe, it is taking more time. Can someone suggest me the most efficient way to achieve this? T_diff = data.Date.diff() slic = [data.index[0]] + T_diff[T_diff.dt.days&gt;period].index.tolist() + [data.index[-1]] li = [] for i in range(len(slic)-1): temp_df = data.loc[slic[i]:slic[i+1]].copy() temp_df['ID'] = temp_df['ID'] + '_{}'.format(i) li.append(temp_df) pd.concat(li,axis=0) Date ID 0 2018-01-01 45.0-A_0 1 2018-01-02 45.0-A_0 5 2018-01-06 45.0-A_1 6 2018-01-07 45.0-A_1 12 2018-01-13 45.0-A_2 13 2018-01-14 45.0-A_2
has answer: http://stackoverflow.com/a/52714805
answer count: 1
has comment: http://stackoverflow.com/comment/92355017

http://stackoverflow.com/comment/92112721
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52588968
score: 0
has text: @jezrael actually works.. Whats the dt?

http://stackoverflow.com/a/52737330
has body: Since score is a dict, you can simply use x as an index to get its value: for x in word: print(x, score[x])
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92399615
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52737248
answers question: http://stackoverflow.com/q/52737248
has comment: http://stackoverflow.com/comment/92399579

http://stackoverflow.com/q/52741983
tagged with: python
has answer: http://stackoverflow.com/a/56200691
type: Question
answer count: 2
has body: Hey Im creating a jupyter notebook, would like to install: https://github.com/voice32/stock_market_indicators/blob/master/indicators.py which is a python program not sure how to do it directly so anybody that dowloads the notebook can just hit "Run All", and see the results option 1) do something like: from https://github.com/voice32/stock_market_indicators/blob/master/indicators.py import indicators.py of course this doesn't work
has title: import a github into jupyter notebook directly?
upvote count: 7
has answer: http://stackoverflow.com/a/52742572
downvote count: 1
tagged with: github
tagged with: jupyter-notebook
favorite count: 0
type: UnansweredQuestion
score: 6

http://stackoverflow.com/q/52711885
tagged with: tkinter
has comment: http://stackoverflow.com/comment/92396777
has comment: http://stackoverflow.com/comment/92433751
type: Question
has answer: http://stackoverflow.com/a/52717598
has title: How to avoid tkinter's IntVar.get() raising TclError on blank strings
has comment: http://stackoverflow.com/comment/92458586
has comment: http://stackoverflow.com/comment/92376317
has comment: http://stackoverflow.com/comment/92425085
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92353421
has comment: http://stackoverflow.com/comment/92385582
favorite count: 0
has comment: http://stackoverflow.com/comment/92457321
has body: I've got an Entry tied to an IntVar, but calling my_int_var.get() throws an exception that seems to complain that the variable is an empty string. I only expect integers to be input by the user in that field. Is there a better solution besides catching TclError? Here's the traceback I'm trying to avoid: || Traceback (most recent call last): || File "Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ || return self.func(*args) || File "/gui.py", line 172, in callback || print(f"Value is now: {my_int_var.get()}") || File "Python36-32\lib\tkinter\__init__.py", line 507, in get || return int(self._tk.getdouble(value)) || _tkinter.TclError: expected floating-point number but got "" This is triggered on a callback tied to the my_int_var's .trace() call. The exception is thrown when you erase the content of the Entry by selecting all the text with a mouse and hitting backspace, leading to a blank value. Here's some code you can run yourself to reproduce the issue, without having to use the mouse: import tkinter as tk root = tk.Tk() my_int_var = tk.IntVar() entry = tk.Entry(textvariable=my_int_var) entry.delete(0, tk.END) my_int_var.get() #throws TclError
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92461082
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/92353267
has comment: http://stackoverflow.com/comment/92353539
score: 3

http://stackoverflow.com/comment/92416046
type: QuestionComment
comment on: http://stackoverflow.com/q/52745343
score: 1
has text: When you point as the "." you are indicating that the .py is next to the executable, in the case of Qt Creator the executable is in the build folder, so I recommend using the complete path or copying the .py file to the build folder.
type: Comment

http://stackoverflow.com/comment/92318336
score: 0
type: AnswerComment
has text: Will this be sufficient when I try to deploy to Linux? Won't it complain about needing a C compiler? I want to know if there is a way to delegate that decision to the environment manager in Linux
type: Comment
comment on: http://stackoverflow.com/a/52694273

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/52629035

http://stackoverflow.com/q/52698078
tagged with: dictionary
has title: Nested dictionary from 3 different length lists in Python
has comment: http://stackoverflow.com/comment/92325008
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/92324985
upvote count: 1
type: Question
has body: I want to make a nested Dictionary out of three different lists which are unequal in length. These are the lists. jaren = ['2017', '2018'] wedstrijden = ['NED', 'GER', 'GBR', 'USA'] eventresults = [[1, 2, 3, 4], [1,2], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9,10], [3,2,1], [6,5,4,3,2,1], [4,5,6,3], [1,2,3,4,5,6,7]] The output should be like: main_dict = {'2017': {'NED':[1, 2, 3, 4], 'GER':[1,2], 'GBR':[1,2,3,4,5,6], 'USA':[1,2,3,4,5,6,7,8,9,10]},{'2018': {'NED':[3, 2, 1], 'GER':[6,5,4,3,2,1], 'GBR':[4,5,6,3], 'USA':[1,2,3,4,5,6,7]}} My current output is: main_dict = {'2017': {'NED':[1, 2, 3, 4], 'GER':[1, 2, 3, 4], 'GBR':[1, 2, 3, 4], 'USA':[1, 2, 3, 4]},{'2018': {'NED':[1,2], 'GER':[1,2], 'GBR':[1,2], 'USA':[1,2]}} And I use this code: main_dict = {} for jaar, eventresult in zip(jaren, eventresults): main_dict[jaar] = {} for wedstrijd in wedstrijden: main_dict[jaar][wedstrijd] = eventresult Actually my list eventresults is a list of DataFrames instead of lists with integers. Can someone give me a help with the code?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92323401
favorite count: 0
has answer: http://stackoverflow.com/a/52698144
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92322829
tagged with: python

http://stackoverflow.com/q/52652649
tagged with: python
has comment: http://stackoverflow.com/comment/92237842
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92237127
has comment: http://stackoverflow.com/comment/92237302
type: Question
possible better answer: http://stackoverflow.com/a/52653280
has answer: http://stackoverflow.com/a/52653280
accepted answer: http://stackoverflow.com/a/52653952
score: 0
has comment: http://stackoverflow.com/comment/92237695
answer count: 2
tagged with: pandas
has body: Good day, Problem: I have two data frames - performance per a firm aka output and input per a firm: `firms = ['1', '2', '3'] df = pd.DataFrame(firms) output = { 'firms': ['1', '2', '3'], 'Sales': [150, 200, 50], 'Profit':[200, 210, 90]} df1 = pd.DataFrame.from_dict(output) inputs = { 'firms': ['1', '2', '3'], 'Salary': [10000, 20000, 500], 'employees':[2, 4, 5]} df2 = pd.DataFrame.from_dict(inputs)` What I need is to divide every column from the output table to every column in the input table. As of now I am doing it in a very ugly manner - by dividing the entire output tbl by every individual column in the input table and then merging the result together. It's all good when I have two columns, but I wonder if there is a better way to do it as I might have 100 columns in one table and 50 in another. Ah, it's also important that the size might be different, e.g. 50 cols in the input and 100 in the output table. frst = df1.iloc[:,0:2].divide(df2.Salary, axis = 0) frst.columns = ['y1-x1', 'y2-x1'] sec = df1.iloc[:,0:2].divide(df2.employees, axis = 0) sec.columns = ['y1-x2', 'y2-x2'] complete = pd.DataFrame(df).join(frst).join(sec) Output: | Firm | y1-x1 | y2-x1 | y1-x2 | y2-x2 | | 1 | 0.0200 | 0.015 | 100.0 | 75.0 | | 2 | 0.0105 | 0.010 | 52.5 | 50.0 | | 3 | 0.1800 | 0.100 | 18.0 | 10.0 | I also tried with loops but if I remember correctly because in my actual example, I have tables of different size, it did not work out. I will be very grateful for your suggestions!
has answer: http://stackoverflow.com/a/52653952
has title: Divide every column in one df to every column in another df in Python
linked to: http://stackoverflow.com/q/2958684

http://stackoverflow.com/q/52721158
tagged with: python
tagged with: gspread
has body: I'm making a script that checks a google sheet from a google form and returns the result as a live-feed visualization of a poll. I need to figure out how to update the value counts, but only when the google sheet is updated, as opposed to checking every 60 seconds (or something). Here is my current setup: string = "" while True: responses = gc.open("QOTD Responses").sheet1 data = pd.DataFrame(responses.get_all_records()) vals = data['Response'].value_counts() str = "{} currently has {} votes. \n{} currently has {} votes.".format(vals.index[0], vals[0], vals.index[1], vals[1]) if(str != string): string = str print(string) time.sleep(60) # Updates 1440 times per day I'm almost certain that there has to be a better way to do this, but what would that be? Thanks!
upvote count: 1
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52729152
downvote count: 0
score: 1
has title: Python GSpead On-Change Listener?
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/92312398
type: QuestionComment
comment on: http://stackoverflow.com/q/52692700
has text: What is it supposed to do? Retrieve all the messages in a discord channel and then erase all the messages from a specific user?
score: 0
type: Comment

http://stackoverflow.com/q/52713016
type: UnansweredQuestion
type: Question
score: 3
has answer: http://stackoverflow.com/a/52713052
answer count: 1
has body: i ran the following code and got no errors def setup_static_routes(app): app.router.add_static('/static/', path=PROJECT_ROOT / 'static', name='static') but if i run PROJECT_ROOT="a" path=PROJECT_ROOT / 'static' i get the following error Traceback (most recent call last): File "&lt;pyshell#15&gt;", line 1, in &lt;module&gt; path=PROJECT_ROOT / 'static' TypeError: unsupported operand type(s) for /: 'str' and 'str' what is the / operator doing in the first example that doesn't throw an error code found at https://docs.aiohttp.org/en/v3.0.1/tutorial.html
downvote count: 0
favorite count: 0
tagged with: python
has title: in python what is the / operator doing in the following code
upvote count: 3

http://stackoverflow.com/q/52630158
has comment: http://stackoverflow.com/comment/92193956
score: -1
type: Question
has title: Create a dict from combinations in a list
answer count: 1
favorite count: 0
has body: I'm trying to create a dict from all possible pairs of elements in a list. This is what I've tried. &gt;&gt;from itertools import combinations &gt;&gt;l = ['a','b','c'] &gt;&gt;dict(combinations(l,2)) {'a': 'c', 'b': 'c'} This is wrong, as there are 3 possible combinations. It's missing 'a': 'b'. When I list(combinations(l,2)) however, it gives me all possible combinations: [('a', 'b'), ('a', 'c'), ('b', 'c')] What's the problem here?
has comment: http://stackoverflow.com/comment/92193758
downvote count: 1
has answer: http://stackoverflow.com/a/52630335
accepted answer: http://stackoverflow.com/a/52630335
tagged with: python-3.x
upvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92194000
tagged with: dictionary
has comment: http://stackoverflow.com/comment/92194055
tagged with: combinations
type: AnsweredQuestion

http://stackoverflow.com/comment/92391086
has text: Possible duplicate of [Check if two unordered lists are equal](https://stackoverflow.com/questions/9623114/check-if-two-unordered-lists-are-equal)
comment on: http://stackoverflow.com/q/52733105
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52591564
downvote count: 1
has comment: http://stackoverflow.com/comment/92134324
upvote count: 0
answers question: http://stackoverflow.com/q/52591339
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/92118119
has body: You can remove it using this code: list_main = ['a','b','c','d','e','f','g','h'] list_sub = ['c','f','d'] for sub_item in list_sub: if sub_item in list_main: list_main.remove(sub_item) list_main += sub_item Or just not add a duplicated items: list_main = ['a','b','c','d','e','f','g','h'] list_sub = ['c','f','d'] for sub_item in list_sub: if sub_item not in list_main: list_main.append(sub_item) Also if you don't want to have duplicated items you can use set. But be careful, set doesn't keep your initial order of elements. list_main = ['a','b','c','d','e','f','g','h'] list_sub = ['c','f','d'] result_list = list(set(list_main + list_sub))

http://stackoverflow.com/comment/92367340
type: Comment
has text: @MosheSlavin I fixed the problem with: /Applications/Python\ 3.6/Install\ Certificates.command
comment on: http://stackoverflow.com/q/52717319
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92291396
has text: nevermind that, i already used a variable called 'loop_count' that goes up everytime a loop is done, and i have an if statement for the first line.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52659950

http://stackoverflow.com/a/52599207
upvote count: 8
type: Answer
has body: You can sum Boolean data.groupby('id').day.apply(lambda x : x.diff().gt(1).cumsum()) Out[614]: 0 0 1 0 2 1 3 1 4 0 5 0 6 1 7 2 8 0 9 1 10 1 11 2 Name: day, dtype: int32
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/52599040

http://stackoverflow.com/comment/92209787
score: 0
has text: thanks a lot, could you explain me the sintax? i am new with python
type: Comment
comment on: http://stackoverflow.com/a/52638449
type: AnswerComment

http://stackoverflow.com/comment/92279773
comment on: http://stackoverflow.com/q/52675152
has text: Edited. I just use a with statement. When I call the session object normally, I use "with requests.session() as s:". requests.session is a function that, when called, creates a session object.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92225807
type: QuestionComment
type: Comment
has text: i've added the code the command i'm having trouble with is : ax.plot((sorted(X[:,0])),sorted((X[:,1])),sorted(Yhat)))
comment on: http://stackoverflow.com/q/52646527
score: 0

http://stackoverflow.com/q/52709281
has comment: http://stackoverflow.com/comment/92349641
upvote count: 1
downvote count: 0
has title: A function that finds the largest number at an index in a list of lists
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: list
answer count: 0
score: 1
tagged with: methods
has body: I am doing an online python course and I'm stuck on one of the tasks. I have a list of lists like below with a string and an int, the int is representative of a weight, and I have a certain weight limit of 10: WeightLimit = 10 MyList = [['ItemOne','9'],['ItemTwo','4'],['ItemThree','7'],['ItemFour','2'], ,['ItemFive','1']] I need to move these items to a new list based on my weight limit, and each new item is essentially a delivery. I need to deliver the heaviest items first. So essentially ItemOne would be my first and only delivery as my limit is now at 1 (10 - 9). My limit now resets to 10 as I can't deliver anymore. My next delivery would be ItemThree, ItemFour, ItemFive (7 + 2 + 1 = 10). My limit resets to 10 as I can't deliver anymore. My final delivery is now ItemTwo. My output would be: newList = [['ItemOne'],['ItemThree', 'ItemFour', 'ItemFive'], ['ItemTwo']] So far I have: heaviest = 0 lightest = 10 name = '' weightLimit = limit outputList = [] loopList = [] for item in MyList: if int(item[1]) &gt; heaviest: heaviest = int(item[1]) name = item[0] elif int(item[1]) &lt; lightest: lightest = int(item[1]) loopList.append(name) weightLimit = weightLimit - heaviest for item in myList: if name == item[0]: MyList.remove(item) if lightest &gt; weightLimit: weightLimit = 10 outputList.append(loopList) loopList = [] So that basically goes through and finds the heaviest item, and the lightest item. If the lightest item is larger than my remaining limit, everything resets, and the item(s) are added to the output list.
type: Question
has comment: http://stackoverflow.com/comment/92346508
has comment: http://stackoverflow.com/comment/92347531
has comment: http://stackoverflow.com/comment/92344911

http://stackoverflow.com/comment/92222280
comment on: http://stackoverflow.com/q/52644714
score: 0
type: QuestionComment
has text: @Andre Motta please give me exact pattern you have given ^[^a-zA-Z](.*) In first comment and in second comment you are giving ^[^a-zA-Z0-9]([*). Is it (.*) Or ([*) please be clear
type: Comment

http://stackoverflow.com/comment/92453048
type: Comment
comment on: http://stackoverflow.com/a/52749420
has text: Did you reinstall the pillow library after `sudo make install?`
score: 0
type: AnswerComment

http://stackoverflow.com/q/52606692
tagged with: lxml
has body: I have a well formed XML embedded in a zip file <?xml version="1.0" encoding="utf-8"?> <c name="Work" position="1"> <t id="9b860ebd-a18f-4944-bc0c-e6846c03a5a2" /> </c> <c name="Home" position="2"> <t id="6d6c6b90-5f06-49fe-90ea-50227c90bd8c" /> </c> <c name="Fun" position="3"> <t id="bd5f7e33-1011-4c96-8022-900dad135145" /> </c> <c name="Empty column" position="4"> </c> When that file is parsed and not embedded in a archive, lxml throws no parse/syntax error (this also "works" with standard python ElementTree). Thought this had to do with compression, but no. Work (not in archive) : import lxml.etree as etree # Yes, I could parse the file directly but wanted to check xml type with open("board.xml", "r") as bo: xml = bytes(bo.read(), "utf8") e = etree.fromstring(xml) Dont work (in archive) : import zipfile import lxml.etree as etree # import xml.etree.ElementTree as etree # Setting compression argument as zipfile.ZIP_DEFLATED because the archive's # files were compressed that way changed nothing. with zipfile.ZipFile("board.zip", "r") as boardzip: manifest_xml = boardzip.read("board.xml") or False # As seen from above, lxml.fromstring requires a bytes object. However, in # the case of the embedded file, ZipFile.read already return a bytes # object. Also, manifest_xml have a well-formed content. if manifest_xml: mxml = etree.fromstring(manifest_xml) The last code outputs : # With LXML lxml.etree.XMLSyntaxError: expected '>', line 7, column 10 # With standard python xml.etree.ElementTree.ParseError: mismatched tag: line 7, column 8 As the mismatched tag is , maybe it was <t> that was not parsed correctly. But transforming <t id="9b860ebd-a18f-4944-bc0c-e6846c03a5a2" /> into <t id="9b860ebd-a18f-4944-bc0c-e6846c03a5a2"></t> also changed nothing.
upvote count: 1
tagged with: python-zipfile
has comment: http://stackoverflow.com/comment/92149474
favorite count: 0
type: UnansweredQuestion
has title: Well formed XML throw XMLSyntaxError when read in a zipfile
has comment: http://stackoverflow.com/comment/92150047
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/92158306
type: Question
downvote count: 0

http://stackoverflow.com/q/52616127
score: 0
has comment: http://stackoverflow.com/comment/92166592
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: MultiOrderedDict not working on Python 2.6.6
linked to: http://stackoverflow.com/q/15848674
has comment: http://stackoverflow.com/comment/92167036
type: Question
has body: Using this answer and others in the thread. https://stackoverflow.com/a/15848928/25531 This works perfectly fine on my local 2.7 in my Ubuntu VM but on our Oracle Linux server that's running 2.6.6 it only returns the last entry and not all of them in a list. Is there a way to workaround for this by any chance? We can't upgrade the python either.

http://stackoverflow.com/q/52680729
has body: I'm download example from: http://xxxx.com/pysnmp/examples/v3arch/twisted/agent/cmdrsp/agent-side-mib-implementations.html And try to run: snmpwalk -v2c -c public 127.0.0.1 .1.3.6 Get: Unhandled Error Traceback (most recent call last): File "implementing-scalar-mib-objects1.py", line 81, in <module> reactor.run() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1261, in run self.mainLoop() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1270, in mainLoop self.runUntilCurrent() --- <exception caught here> --- File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 896, in runUntilCurrent call.func(*call.args, **call.kw) File "/usr/lib/python2.7/dist-packages/pysnmp/carrier/base.py", line 70, in _cbFun self, transportDomain, transportAddress, incomingMessage File "/usr/lib/python2.7/dist-packages/pysnmp/entity/engine.py", line 152, in __receiveMessageCbFun self, transportDomain, transportAddress, wholeMsg File "/usr/lib/python2.7/dist-packages/pysnmp/proto/rfc3412.py", line 433, in receiveMessage PDU, maxSizeResponseScopedPDU, stateReference) File "/usr/lib/python2.7/dist-packages/pysnmp/entity/rfc3413/cmdrsp.py", line 150, in processPdu self.handleMgmtOperation(snmpEngine, stateReference, contextName, PDU) File "/usr/lib/python2.7/dist-packages/pysnmp/entity/rfc3413/cmdrsp.py", line 293, in handleMgmtOperation rspVarBinds = mgmtFun(*varBinds, **context) File "/usr/lib/python2.7/dist-packages/pysnmp/smi/instrum.py", line 261, in readNextVars return self.flipFlopFsm(self.fsmReadNextVar, *varBinds, **context) File "/usr/lib/python2.7/dist-packages/pysnmp/smi/instrum.py", line 227, in flipFlopFsm rval = mgmtFun((tuple(name), val), **context) File "/usr/lib/python2.7/dist-packages/pysnmp/smi/mibs/SNMPv2-SMI.py", line 527, in readGetNext return node.readGetNext((nextName, val), **context) File "/usr/lib/python2.7/dist-packages/pysnmp/smi/mibs/SNMPv2-SMI.py", line 660, in readGetNext return MibTree.readGetNext(self…
type: Question
tagged with: pysnmp
score: 0
has title: Implementing scalar MIB objects in PySNMP not work
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: snmp
has answer: http://stackoverflow.com/a/52681737

http://stackoverflow.com/comment/92315505
type: Comment
type: QuestionComment
has text: haha didn't realise that. thx for the comment
score: 0
comment on: http://stackoverflow.com/q/52679322

http://stackoverflow.com/comment/92169910
comment on: http://stackoverflow.com/q/52617808
has text: Put your code in the question itself please.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92242196
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52655390
has text: thansk for the help and how do I make it so that my input values are underlined when I run the program.

http://stackoverflow.com/comment/92272107
type: QuestionComment
comment on: http://stackoverflow.com/q/52667762
score: 0
has text: Is the value of search three different parameters or is that all part of the search parameter for the api?
type: Comment

http://stackoverflow.com/q/52605067
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: how to make decoder in rnn, tensorflow, feeded previous output
tagged with: python
score: 3
answer count: 0
upvote count: 3
tagged with: seq2seq
tagged with: tensorflow
type: Question
has body: I'm wondering how to make decoder in tensorflow rnn, feed it's i th output to (i+1)th input my inputs have 20 sequence and 3680 dementions and my outputs have 39 sequence and 3680 dementions all data is 0~1 number here is my model with tf.variable_scope('encoder'): enc_input = tf.placeholder(tf.float32,[None, input_sequence_length, input_dim]) enc_cell = tf.contrib.rnn.BasicLSTMCell(num_units = input_sequence_length) _ , encoder_states = tf.nn.dynamic_rnn(enc_cell, enc_input , dtype=tf.float32) with tf.variable_scope('decoder'): dec_input = tf.placeholder(tf.float32,[None, output_sequence_length, output_dim]) dec_output = tf.placeholder(tf.float32,[None, output_sequence_length, output_dim]) dec_cell = tf.contrib.rnn.BasicLSTMCell(num_units = output_sequence_length) outputs , _ = tf.nn.dynamic_rnn(dec_cell, dec_input,dtype = tf.float32, initial_state = encoder_states) how can i make decoder model that feed previous outputs to next input? P.S I make my self-answer code like this with tf.variable_scope('decoder'): dec_input = tf.placeholder(tf.float32,[None, 1, output_dim]) dec_output = tf.placeholder(tf.float32,[None, output_sequence_length, output_dim]) outputs = [] state = encoder_states dec_cell = tf.contrib.rnn.BasicLSTMCell(num_units = dec_hidden_size) for i in range(output_sequence_length): if i==0: output , state = tf.nn.dynamic_rnn(dec_cell, dec_input, initial_state = state, dtype = tf.float32) outputs.append(output) else: output , state = tf.nn.dynamic_rnn(dec_cell, output, initial_state = state, dtype = tf.float32) outputs.append(output) outputs = tf.reshape(outputs,[-1,output_dim]) outputs = tf.reshape(outputs,[-1,output_sequence_length,output_dim]) I think this code's output is different from upper code's output but I'm not sure it worked properly. so still I wonder how to make decoder that has loop function((i)output->(i+1)input) with tensorflow method, because it takes more memory allocation than the upper code. (in my thought it has same cell count)
tagged with: encoder-decoder

http://stackoverflow.com/comment/92151723
type: AnswerComment
type: Comment
has text: @Matthias: I am a fan of one liner but I guess the OP might find it confusing. Anyway, would you mind if I add your one liner in my answer with proper acknowledgement to you?
comment on: http://stackoverflow.com/a/52608580
score: 0

http://stackoverflow.com/comment/92601937
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52743489
has text: The thing is that as soon as you want to throw methods or functions into the mix in order to apply some sort of logic to a new entry, dicts aren't that usefull and it is better to go with a class (IMO anyway).
type: AnswerComment

http://stackoverflow.com/a/52715078
has comment: http://stackoverflow.com/comment/92357572
has body: Try this fig, ax = plt.subplots() ax.set_xticks(df['day'].unique()) df.groupby(["day", "month"]).mean()['count'].unstack().plot(ax=ax) Above code will give you 12 lines representing each month in one plot. If you want to have 12 individual subplots for those months, try this: fig = plt.figure() for i in range(1,13): df_monthly = df[df['month'] == i] # select dataframe with month = i ax = fig.add_subplot(12,1,i) # add subplot in the i-th position on a grid 12x1 ax.plot(df_monthly['day'], df_monthly['count']) ax.set_xticks(df_monthly['day'].unique()) # set x axis
answers question: http://stackoverflow.com/q/52714658
has comment: http://stackoverflow.com/comment/92355998
type: Answer
has comment: http://stackoverflow.com/comment/92356085
has comment: http://stackoverflow.com/comment/92363475
accepted answer of: http://stackoverflow.com/q/52714658
score: 4
has comment: http://stackoverflow.com/comment/92359836
upvote count: 4
has comment: http://stackoverflow.com/comment/92356109
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92356029

http://stackoverflow.com/a/52671883
has body: You can use these two lines: &gt;&gt;&gt; np.nanmean(np.array(list(zip_longest(*a)),dtype=float),axis=1) array([2.8 , 2.6 , 3.75, 5. ]) &gt;&gt;&gt; np.nanstd(np.array(list(zip_longest(*a)),dtype=float),axis=1,ddof=1) array([2.48997992, 0.89442719, 0.95742711, 1.41421356]) nanmean and nanstd compute mean and std respectively, and ignoring nan. So you are passing it the array: &gt;&gt;&gt; np.array(list(zip_longest(*a)),dtype=float) array([[ 1., 2., 3., 1., 7.], [ 2., 3., 4., 2., 2.], [ 3., 4., 5., nan, 3.], [nan, nan, 6., nan, 4.]]) And computing the mean and standard deviation for each row, ignoring NaNs. The ddof argument stands for degrees of freedom, and I set it to 1 based on your desired output (default is 0)
score: 2
has comment: http://stackoverflow.com/comment/92273670
accepted answer of: http://stackoverflow.com/q/52671807
answers question: http://stackoverflow.com/q/52671807
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92273933
has comment: http://stackoverflow.com/comment/92273755
upvote count: 2
type: Answer

while-loop
tags question: http://stackoverflow.com/q/52729584
tags question: http://stackoverflow.com/q/52598007
type: Tag
tags question: http://stackoverflow.com/q/52636215
tags question: http://stackoverflow.com/q/52601848
tags question: http://stackoverflow.com/q/52708813
tags question: http://stackoverflow.com/q/52744812
tags question: http://stackoverflow.com/q/52631022
tags question: http://stackoverflow.com/q/52607862
tags question: http://stackoverflow.com/q/52685203
tags question: http://stackoverflow.com/q/52633915
tags question: http://stackoverflow.com/q/52679425
tags question: http://stackoverflow.com/q/52746653
tags question: http://stackoverflow.com/q/52713316
tag name: while-loop
tags question: http://stackoverflow.com/q/52731049
tags question: http://stackoverflow.com/q/52733173
tags question: http://stackoverflow.com/q/52681460

http://stackoverflow.com/comment/92221374
comment on: http://stackoverflow.com/q/52644217
score: 0
type: Comment
type: QuestionComment
has text: I updated my question

http://stackoverflow.com/q/52661772
favorite count: 0
has answer: http://stackoverflow.com/a/52662302
has answer: http://stackoverflow.com/a/52662386
has comment: http://stackoverflow.com/comment/92254114
has body: From the following sort of dataframe I would like to be able to both sort and rank the id field on date: df = pd.DataFrame({ 'id':[1, 1, 2, 3, 3, 4, 5, 6,6,6,7,7], 'value':[.01, .4, .2, .3, .11, .21, .4, .01, 3, .5, .8, .9], 'date':['10/01/2017 15:45:00','05/01/2017 15:56:00', '11/01/2017 15:22:00','06/01/2017 11:02:00','05/01/2017 09:37:00', '05/01/2017 09:55:00','05/01/2017 10:08:00','03/02/2017 08:55:00', '03/02/2017 09:15:00','03/02/2017 09:31:00','09/01/2017 15:42:00', '19/01/2017 16:34:00']}) to effectively rank or index, per id, based on date. I've used df.groupby('id')['date'].min() which allows me to extract the first date (although I don't know how to use this to filter out the rows) but I might not always need the first date - sometimes it will be the second or third so I need to generate a new column, with an index for the date - the result would look like: Any ideas on this sorting/ranking/labelling? EDIT My original model ignored a very prevalent issue. As there are feasibly some ids that have multiple tests performed on them in parallel, therefore they show in multiple rows in the datebase, with matching dates (date corresponds to when they were logged). These should be counted as the same date and not increment the date_rank: I've generated a model, with updated date_rank to demonstrate how this would look: df = pd.DataFrame({ 'id':[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6,6,6,7,7], 'value':[.01, .4, .5, .7, .77, .1,.2, 0.3, .11, .21, .4, .01, 3, .5, .8, .9, .1], 'date':['10/01/2017 15:45:00','10/01/2017 15:45:00','05/01/2017 15:56:00', '11/01/2017 15:22:00','11/01/2017 15:22:00','06/01/2017 11:02:00','05/01/2017 09:37:00','05/01/2017 09:37:00','05/01/2017 09:55:00', '05/01/2017 09:55:00','05/01/2017 10:08:00','05/01/2017 10:09:00','03/02/2017 08:55:00', '03/02/2017 09:15:00','03/02/2017 09:31:00','09/01/2017 15:42:00', '19/01/2017 16:34:00']}) And the counter would afford this:
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/52662302
type: Question
tagged with: group-by
tagged with: sorting
tagged with: ranking
answer count: 2
has title: Sorting and ranking by dates, on a group in a pandas df
tagged with: pandas
has comment: http://stackoverflow.com/comment/92253945
downvote count: 0
possible better answer: http://stackoverflow.com/a/52662386

http://stackoverflow.com/q/52715130
has comment: http://stackoverflow.com/comment/92355988
has answer: http://stackoverflow.com/a/52715261
has comment: http://stackoverflow.com/comment/92356001
has answer: http://stackoverflow.com/a/52715473
has comment: http://stackoverflow.com/comment/92356043
tagged with: tuples
has comment: http://stackoverflow.com/comment/92355857
tagged with: python
has answer: http://stackoverflow.com/a/52715283
has answer: http://stackoverflow.com/a/52715295
has comment: http://stackoverflow.com/comment/92355979
has body: Main question: How do you identify an element within a tuple within an array? Example: [(1,2),(1,4),(5,6),(4,8)] Sub question: I wanted to isolate the parent nodes of each tuple which had no other parents (I wanted to isolate 1 and 5 in the example above.) I tried to iterate through the first element of each tuple in the array so something like for i in array
has comment: http://stackoverflow.com/comment/92355944
has answer: http://stackoverflow.com/a/52715199
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92355952
has title: How do you identify an element in a tuple within an array
answer count: 6
type: Question
score: 0
has answer: http://stackoverflow.com/a/52715228

http://stackoverflow.com/comment/92133847
comment on: http://stackoverflow.com/a/52598005
score: 0
type: Comment
has text: You're amazing! This helped me a lot. Thank you!
type: AnswerComment

http://stackoverflow.com/comment/92404673
has text: @mkriger1 I edited the question by adding an example of what i want as an output. Is it clear now ? Thank you
comment on: http://stackoverflow.com/q/52739871
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92374131
comment on: http://stackoverflow.com/q/52724022
has text: @alec_djinn here you go.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52594265
tagged with: pandas
has comment: http://stackoverflow.com/comment/92123452
answer count: 1
has answer: http://stackoverflow.com/a/52594386
accepted answer: http://stackoverflow.com/a/52594386
has comment: http://stackoverflow.com/comment/92123449
tagged with: python
has comment: http://stackoverflow.com/comment/92124784
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2612802
tagged with: dataframe
tagged with: updates
type: Question
has title: Save dataframe column and update
score: 0
has body: I am trying to save a pandas dataframe column instance. but the instance disappears once I make an update in that column, I can't get access to the old instance anymore. C= DF.loc[:,'10'] print(C) DF.loc[:,'10'] = None print(C) In the first print I get the last instance of DF.loc[:,'10'], in the second one I get a None column. How should I do to save the old instance to use it later? Does python make an update on variables of the dataframe even when I already saved it? Thanks for helping.

http://stackoverflow.com/a/52654858
score: 0
type: Answer
has body: If you just want YYYY-MM-DD you could do a substring from position 0 through 9. Example in Python dateStr[:10]
answers question: http://stackoverflow.com/q/52654797

http://stackoverflow.com/q/52688527
has comment: http://stackoverflow.com/comment/92304279
answer count: 4
tagged with: python-3.x
has body: I'm really new to cgi and trying to convert a Perl cgi script to Python. I came across these statements in the script. my $q = new CGI; print $q-&gt;header(-type=&gt;'text'); By looking at it I can understand that q is a scalar variable which possess the form data from which the CGI script is being called. But what does the print statement above do? Will it check if the type header's value in form header dictionary and print True or False based on that? I don't have Perl interpreter to execute and check the output.
has comment: http://stackoverflow.com/comment/92327451
has answer: http://stackoverflow.com/a/52798216
tagged with: cgi
downvote count: 1
has comment: http://stackoverflow.com/comment/130503709
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76629272
score: -1
possible better answer: http://stackoverflow.com/a/52688657
has title: What does the header(-type=>'text') print in cgi in Perl
has comment: http://stackoverflow.com/comment/92304259
type: Question
tagged with: perl
has comment: http://stackoverflow.com/comment/92327417
upvote count: 0
tagged with: header
favorite count: 0
has answer: http://stackoverflow.com/a/52688612
accepted answer: http://stackoverflow.com/a/52688612
tagged with: python
has answer: http://stackoverflow.com/a/52688657

http://stackoverflow.com/q/52623338
tagged with: python
has comment: http://stackoverflow.com/comment/92180247
has answer: http://stackoverflow.com/a/52623647
downvote count: 6
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/18773474
has body: I have two while loops that are almost identical apart from a few numbers have changed. I've been looking around but I can't find a solution to my problem. Any help would be appreciated. I want to make the two while loops one loop but I dont know how. I've been looking around for an answer but nothing seems to apply to my problem. while True: print("User 1") login=input("Do you have an account? (yes/no) ") loggedin=False if login.lower()=="yes": login1=open("login.csv") reader = csv.reader(login1) username1=input("What is your username: ") password1=input("What is your password: ") for row in reader: if row[0]==username1: if row[1]==password1: print("Welcome " + username1) loggedin=True break if loggedin==False: print("Invalid username or password. Please try again.") continue elif login.lower()=="no": print(" ") print("Make an account.") print(" ") username1=input("What is your username: ") password1=input("What is your password: ") break else: print("Invalid input.") continue The only thing that has changed is the number 1 has changed to a number 2 (with the exception of row[1]) Again, any help would be appreciated.
has comment: http://stackoverflow.com/comment/92180320
possible better answer: http://stackoverflow.com/a/52623459
tagged with: loops
has comment: http://stackoverflow.com/comment/92180253
has answer: http://stackoverflow.com/a/52623459
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92180328
upvote count: 0
accepted answer: http://stackoverflow.com/a/52623647
has comment: http://stackoverflow.com/comment/92180432
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/92180297
has title: Make two while loops one loop
has comment: http://stackoverflow.com/comment/92180251

http://stackoverflow.com/comment/92247008
type: Comment
comment on: http://stackoverflow.com/a/52657911
type: AnswerComment
has text: From the link you provided, it looks like it's provided as a User object attribute too. Calling `User.in_reply_to_status_id` didn't work too?
score: 0

http://stackoverflow.com/a/66615498
has comment: http://stackoverflow.com/comment/117804106
has body: mpl_finance has been deprecated, just install the module as mplfinance.
type: Answer
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/52655847

http://stackoverflow.com/comment/92196850
comment on: http://stackoverflow.com/a/52629902
type: Comment
has text: @GRS That's because of the `Reshape` layer in the first solution. The given dimensions to this layer cannot be `None` (i.e. `n_steps`). You need to change it to this: `Reshape((-1, 160))(cat_merged)` or generally `Reshape((-1, sum_of_cat_embd_dim))(cat_merged)`.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52720552
tagged with: python
has comment: http://stackoverflow.com/comment/92366742
tagged with: python-3.x
has body: How do i get the speed value out of this in code? { "response": { "speed": "1000000", "lastUpdated": "2018-10-09 11:19:10.981000", "portMode": "access", "portType": "Ethernet Port", "description": " changed by DNAC", "series": "Cisco Catalyst 9300 Series Switches", "ifIndex": "31", "mediaType": "100/1000/2.5G/5G/10GBaseTX", "className": "SwitchPort", "interfaceType": "Physical", "ipv4Address": null, "ipv4Mask": null, "isisSupport": "false", "mappedPhysicalInterfaceId": null, "mappedPhysicalInterfaceName": null, "nativeVlanId": "1", "ospfSupport": "false", "pid": "C9300-24UX", "serialNo": "FCW2140L039", "voiceVlan": null, "status": "up", "deviceId": "4757da48-3730-4833-86db-a0ebfbdf0009", "macAddress": "f8:7b:20:71:4d:98", "portName": "TenGigabitEthernet1/0/24", "adminStatus": "UP", "duplex": "FullDuplex", "vlanId": "1", "instanceTenantId": "5b13fcf9651f93008acd0702", "instanceUuid": "8beed342-3718-4fa9-8377-4c7d94c77aef", "id": "8beed342-3718-4fa9-8377-4c7d94c77aef" }, "version": "1.0" } I tried the code below but it does not work. for items in data["response"] print(items['speed']) this wil give me the error TypeError: string indices must be integers
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92367015
has title: JSON data, TypeError: string indices must be integers
linked to: http://stackoverflow.com/q/11700798
has comment: http://stackoverflow.com/comment/92366349
duplicate of: http://stackoverflow.com/q/11700798
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/92366176
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52720620

http://stackoverflow.com/q/52667632
has title: lxml iterate through child divs
accepted answer: http://stackoverflow.com/a/52681441
type: Question
has answer: http://stackoverflow.com/a/52681441
has body: I have the below html code where i parse ratings/text etc. How can I iterate through all divs class contain "posting item" below the div "wrap" using lxml and tree? With the below I get all post divs selected at the same time, forumposts = tree.xpath("//div[@class='wrap']//div[contains(@class, 'posting item')]") # here i want to iterate through posting items # so i should have 1 text/rating to process in the parse function for post in forumposts: parse(post) The HTML: 6 7 Posting text 1 1 11 Posting text 2
score: 0
answer count: 1
tagged with: lxml
tagged with: python
tagged with: parsing
type: AnsweredQuestion

http://stackoverflow.com/a/52700755
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52699474
type: Answer
accepted answer of: http://stackoverflow.com/q/52699474
upvote count: 1
score: 1
has body: In Slack you can usually share files with others. (as described here) However, this is currently not possible with the Slack API, since it does not have a method for sharing a file, other then through files.upload. Alternatively you can use the files.share method from the undocumented Slack API. This comes with a couple caveats though, one being that the method requires a legacy token and will therefore not work well with distributed Slack apps. But if you are just building something for your own Slack workspace it will work fine. To share a file with another user provide the user ID as channel property for files.share. Note: If you need this functionality I would suggest to let the Slack team know about it. The more feedback they get the more likely this method will become part of the official API.

http://stackoverflow.com/q/52591137
has answer: http://stackoverflow.com/a/52603516
type: Question
has title: Fine tuning hdbscan parameters for clustering text documents
score: 0
upvote count: 1
tagged with: cluster-analysis
answer count: 1
downvote count: 1
tagged with: scikit-learn
tagged with: hdbscan
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have text documents which am clustering using hdbsca. When I have laser amount data around 35 documents and correct values of clusters around 14, then using following paramters I am getting correct result. def cluster_texts(textdict, eps=0.40,min_samples = 1): """ cluster the given texts Input: textdict: dictionary with {docid: text} Returns: doccats: dictionary with {docid: cluster_id} """ doc_ids = list(textdict.keys()) # transform texts into length normalized kpca features ft = FeatureTransform(norm='max', weight=True, renorm='length', norm_num=False) docfeats = ft.texts2features(textdict) X, featurenames = features2mat(docfeats, doc_ids) e_lkpca = KernelPCA(n_components=12, kernel='linear') X = e_lkpca.fit_transform(X) xnorm = np.linalg.norm(X, axis=1) X = X/xnorm.reshape(X.shape[0], 1) # compute cosine similarity D = 1 - linear_kernel(X) # and cluster with dbscan clst = hdbscan.HDBSCAN(eps=eps, metric='precomputed', min_samples=min_samples,gen_min_span_tree=True,min_cluster_size=2) y_pred = clst.fit_predict(D) return {did: y_pred[i] for i, did in enumerate(doc_ids)} Now I just replicated data, each document 100 times. And tried to finetune clustering, but now I am getting 36 cluster, each document in different cluster. I tried changing different parameters. but no change in clustering result. Any suggestion or reference much appreciated.

http://stackoverflow.com/a/52704064
downvote count: 0
has body: Use: #create index by column id df = df.set_index('id') #convert columns to datetimes and shift startTime per groups df['startTime'] = pd.to_datetime(df['startTime']).groupby(level=0).shift(-1) df['endTime'] = pd.to_datetime(df['endTime']) #subtract, remove first missing values per groups and set column from index df = df['startTime'].sub(df['endTime']).dropna().reset_index(name='time') print (df) id time 0 1 00:04:20 1 2 00:11:21 2 2 04:21:32
answers question: http://stackoverflow.com/q/52703835
type: Answer
accepted answer of: http://stackoverflow.com/q/52703835
upvote count: 2
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/52655948
score: 0
has body: I am trying to create a Bottle server that allows the user to save a file to the server (I know this has a big security hole, adding an auth system later). When I try to save a file using the webpage, I get this error. [Errno 2] No such file or directory: '/storage/test.txt' main.py from bottle import * class File(): def __init__(self, Path): self.Path = Path def read(self): self.File = open(self.Path, 'r') return [self.File.read(), self.File.close()][0] @route('/') def Request(): return File('responses/index.html').read() @route('/actions/save') def Request(): return File('responses/actions/save/index.html').read() @route('/actions/save', method='POST') def Request(): Source = request.forms.get('source') Path = request.forms.get('path') try: FileObj = open('/storage/{}'.format(Path), 'w') FileObj.write(Source) FileObj.close() return File('responses/actions/save/ok.html').read() except Exception as Message: return File('responses/actions/save/error.html').read().format(Message=Message) if __name__ == '__main__': run(host='0.0.0.0', port=8000) responses/actions/save/index.html Save File Save File Path: index.html POSTRun PostRun Save File
tagged with: python
tagged with: bottle
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52655974
has comment: http://stackoverflow.com/comment/92243550
has comment: http://stackoverflow.com/comment/92244887
type: Question
accepted answer: http://stackoverflow.com/a/52655974
answer count: 1
has title: Errno 2 No such file or directory: '/storage/test.txt'

http://stackoverflow.com/comment/92324428
type: Comment
comment on: http://stackoverflow.com/q/52698248
type: QuestionComment
has text: Possible duplicate of [Python SSL CERTIFICATE\_VERIFY\_FAILED](https://stackoverflow.com/questions/28858634/python-ssl-certificate-verify-failed). The Answer clearly explains why!
score: 0

http://stackoverflow.com/q/52603355
tagged with: python
has title: Beautifulsoup .text function returns no text
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52603672
has body: I attempted to extract the text within the h1 tag returned from running the code and received no output. However, the code was able to find the specified tag as follows: Mixed Brown Rice 2.5kg The link to the web page: https://giantonline.com.sg/product/mixed-brown-rice-5142760 This is the code I used: driver.get("https://giantonline.com.sg/product/mixed-brown-rice-5142760") driver.implicitly_wait(30) time.sleep(4) bs2=BeautifulSoup(driver.page_source, 'lxml') for z in bs2.find_all('div',class_="col-md-5 col-sm-5 col-xs-12"): try: name = z.find('h1',class_='product-name') print(type(name)) print(name) name = name.get_text(seperator=' ') print(name) size = z.find('h1',class_='product-size main-heading') size = size.text oldprice = z.find('div',class_='old-price') oldprice = oldprice.text price = z.find('div',class_='content_price') price = price.text except: continue Why was I unable to get the text out of the h1 tag?
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/52603672
type: Question
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/52607678
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/92149398
has title: Python Regular Expression for Stripping Terms
score: -3
upvote count: 0
has answer: http://stackoverflow.com/a/52608073
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92149446
type: UnansweredQuestion
tagged with: python
has body: I want to strip terms with these rules: strip all characters from left except alphanumeric characters strip all characers from right except apostrophe and alphanumeric characters I used str.lstrip and str.rstrip functions: term = term.lstrip(string.punctuation + string.whitespace) term = term.rstrip(punctuations + string.whitespace) I think this can be done in one line by using regular expression. How can I do that

dashboard
tags question: http://stackoverflow.com/q/52638897
tags question: http://stackoverflow.com/q/52643973
type: Tag
tags question: http://stackoverflow.com/q/52652789
tag name: dashboard

http://stackoverflow.com/comment/92176600
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52620817
has text: @3yanlis1bos Color is the cue. Healthy tree point is green. Maybe I should define a range of leaf green? But my programme is not only applied to one dataset. Is that fine?

http://stackoverflow.com/a/52710423
score: 0
type: Answer
has body: Your best bet is to try it. Try running: b=10 while b: print(b) b-=2 and see what happens
answers question: http://stackoverflow.com/q/52710396

http://stackoverflow.com/comment/92406610
type: Comment
comment on: http://stackoverflow.com/q/52740675
has text: @FrankAK Edited to include expected output, thanks!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92402482
type: AnswerComment
comment on: http://stackoverflow.com/a/52738406
has text: when I run it from terminal i get INFO tika (autodetecting type) . but when i call from python app i am getting INFO tika (application/x-www-form-urlencoded). how can i convert to autodetecting type
type: Comment
score: 0

http://stackoverflow.com/a/52642247
type: Answer
has comment: http://stackoverflow.com/comment/92218915
has comment: http://stackoverflow.com/comment/92219696
has comment: http://stackoverflow.com/comment/92218784
has comment: http://stackoverflow.com/comment/92217663
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52642070
accepted answer of: http://stackoverflow.com/q/52642070
has body: You should initialize item_list outside the for loop; otherwise its previous value gets overwritten with each iteration. You should also make item_list a set instead so that if there are multiple .jpg files under the same directory they won't result in duplicate directories in the list: item_list=set() for item in files_list: print(item) index_of_dir_path = item.rfind('\\') print(item[0:index_of_dir_path]) item_list.add(item[0:index_of_dir_path]) json_data = { "dirPath_not_include_01_jpg_file":list(item_list) } If you want to exclude directories containing 01.jpg you should also check it before you add the files to the list: for dirpath, dirnames, filenames in os.walk(file_dir): if all('01.jpg' not in file for file in filenames): for file in filenames : if os.path.splitext(file)[1] == '.jpg': L.append(os.path.join(dirpath, file))
has comment: http://stackoverflow.com/comment/92219213
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92217292
has comment: http://stackoverflow.com/comment/92216788

http://stackoverflow.com/comment/92355954
comment on: http://stackoverflow.com/a/52715007
type: Comment
has text: Thank you @Lutz Horn but I take the data from messagetype.txt looks like : with open('messagetype.txt', 'r') as f: how to take data from this file?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92181956
score: 0
has text: As an alternative, you can load dataset into pandas and it has it's own methods to send them to an SQL connection like psycopg2.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52622905

anaconda
tags question: http://stackoverflow.com/q/52672463
tags question: http://stackoverflow.com/q/52706888
tags question: http://stackoverflow.com/q/52693313
tags question: http://stackoverflow.com/q/52626198
tags question: http://stackoverflow.com/q/52695195
tags question: http://stackoverflow.com/q/52725892
type: Tag
tags question: http://stackoverflow.com/q/52721099
tags question: http://stackoverflow.com/q/52741538
tags question: http://stackoverflow.com/q/52743399
tags question: http://stackoverflow.com/q/52645253
tags question: http://stackoverflow.com/q/52730430
tags question: http://stackoverflow.com/q/52598422
tags question: http://stackoverflow.com/q/52733761
tags question: http://stackoverflow.com/q/52676843
tags question: http://stackoverflow.com/q/52632301
tags question: http://stackoverflow.com/q/52646961
tags question: http://stackoverflow.com/q/52691790
tags question: http://stackoverflow.com/q/52630324
tags question: http://stackoverflow.com/q/52726459
tags question: http://stackoverflow.com/q/52631475
tags question: http://stackoverflow.com/q/52638232
tags question: http://stackoverflow.com/q/52691611
tags question: http://stackoverflow.com/q/52700226
tags question: http://stackoverflow.com/q/52722072
tags question: http://stackoverflow.com/q/52655887
tags question: http://stackoverflow.com/q/52644215
tags question: http://stackoverflow.com/q/52700284
tags question: http://stackoverflow.com/q/52625796
tag name: anaconda
tags question: http://stackoverflow.com/q/52716461
tags question: http://stackoverflow.com/q/52648520
tags question: http://stackoverflow.com/q/52633549
tags question: http://stackoverflow.com/q/52601198
tags question: http://stackoverflow.com/q/52742370
tags question: http://stackoverflow.com/q/52731782
tags question: http://stackoverflow.com/q/52682545
tags question: http://stackoverflow.com/q/52693101
tags question: http://stackoverflow.com/q/52664293
tags question: http://stackoverflow.com/q/52618482
tags question: http://stackoverflow.com/q/52602576
tags question: http://stackoverflow.com/q/52735313
tags question: http://stackoverflow.com/q/52651741
tags question: http://stackoverflow.com/q/52661392
tags question: http://stackoverflow.com/q/52683834
tags question: http://stackoverflow.com/q/52728981
tags question: http://stackoverflow.com/q/52729986
tags question: http://stackoverflow.com/q/52701010
tags question: http://stackoverflow.com/q/52720074
tags question: http://stackoverflow.com/q/52629377

http://stackoverflow.com/comment/92238684
type: QuestionComment
comment on: http://stackoverflow.com/q/52652264
has text: I mean, you can do a lot. What use case is there where you would like to use those colors?
score: 0
type: Comment

http://stackoverflow.com/a/52649120
has body: Try the following approach. def adjust(x): # create a list of numbers to multiply (adjust) # the original data by if not len(x) % 2: r = range(-(len(x)//2), (len(x)//2)) else: r = range(-(len(x)//2), (len(x)//2)+1) mult = list(map(lambda x: 1+x/10, r)) return x*mult # find all duplicates dup = df.duplicated(subset='x', keep=False) # update the values of duplicates using the above function df.loc[dup, 'x'] = df[dup].groupby('x').x.apply(adjust) Example: Input Data: a, 10, 30 b, 10, 30 c, 10, 30 d, 50, 80 e, 90, 60 f, 100, 20 g, 120, 40 h, 120, 40 i, 120, 40 Output DataFrame: node x y 0 a 9.0 30 1 b 10.0 30 2 c 11.0 30 3 d 50.0 80 4 e 90.0 60 5 f 100.0 20 6 g 96.0 40 7 h 108.0 40 8 i 120.0 40 9 j 132.0 40 10 k 144.0 40
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52646676

http://stackoverflow.com/comment/92269647
comment on: http://stackoverflow.com/a/52663109
score: 0
type: Comment
has text: What would be a good data structure if I wanted to have the following for each track: track_number (could be the index) track_name (should be a string) track_time (should be a float) and how would you iterate over it?
type: AnswerComment

http://stackoverflow.com/a/52658499
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52658463
has body: You can use a character class that excludes .: s = re.sub(r'\(([^.])\)', r'\1', s) With this change, s would become: *CHI: &lt;that&gt; [/] (.) that is it . [+ bch]

http://stackoverflow.com/q/52613589
score: -2
has comment: http://stackoverflow.com/comment/92165838
has body: I want to make an command so when someone does #runtime it shows how much time the bot has been active. So far everything works, but the problem is that the while True: part is blocking the execution of the command. Anyone could help me? CODE: import os import discord import asyncio import chalk import time from discord.ext import commands from discord.ext.commands import Bot from discord.utils import get print("DONE LOADING!\n") bot = commands.Bot(command_prefix='#') client = discord.Client() num1 = 0 num2 = 0 num3 = 0 num4 = 0 while True: num1 = num1+1 if num1 == 60: num1 = 0 num2 = num2+1 if num2 == 60: num2 = 0 num3 = num3+1 if num3 == 24: num3 = 0 num4 = num4+1 time.sleep(1) @bot.command(pass_context=True) async def runtime(ctx): await bot.say("Running for {}d {}h {}m {}s".format(num4, num3, num2, num1))
has comment: http://stackoverflow.com/comment/92165478
answer count: 1
has comment: http://stackoverflow.com/comment/92164294
has comment: http://stackoverflow.com/comment/92162966
favorite count: 0
has comment: http://stackoverflow.com/comment/92165993
accepted answer: http://stackoverflow.com/a/52615782
tagged with: python
has comment: http://stackoverflow.com/comment/92163024
has comment: http://stackoverflow.com/comment/92164314
has comment: http://stackoverflow.com/comment/92163095
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92165772
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/52615782
has title: discord.py - Runtime Command (Help)
type: Question
tagged with: discord.py

http://stackoverflow.com/q/52694057
accepted answer: http://stackoverflow.com/a/52703539
tagged with: python
type: AnsweredQuestion
has title: Changing Data types of pandas dataframe columns based on template with matching column names in PYTHON
type: Question
tagged with: dataframe
tagged with: pandas-groupby
tagged with: pandas
score: 2
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52703539
has body: I have 2 dataframes. Template - I will be using data types from this data frame. df - I want to change datatypes of this data frame based on template. I want to change data types of second dataframe based on first. Lets suppose I have below data frame which I am using as template. &gt; template id &lt;- c(1,2,3,4) a &lt;- c(1,4,5,6) b &lt;- as.character(c(0,1,1,4)) c &lt;- as.character(c(0,1,1,0)) d &lt;- c(0,1,1,0) template &lt;- data.frame(id,a,b,c,d, stringsAsFactors = FALSE) &gt; str(template) 'data.frame': 4 obs. of 5 variables: $ id: num 1 2 3 4 $ a : num 1 4 5 6 $ b : chr "0" "1" "1" "4" $ c : chr "0" "1" "1" "0" $ d : num 0 1 1 0 I am looking for below things. To cast data types of template to be exactly same in df. It should have same columns which are there in template frame. **Note- It should add additional columns with all NA's if not available in df. &gt; df id &lt;- c(6,7,12,14,1,3,4,4) a &lt;- c(0,1,13,1,3,4,5,6) b &lt;- c(1,4,12,3,4,5,6,7) c &lt;- c(0,0,13,3,4,45,6,7) e &lt;- c(0,0,13,3,4,45,6,7) df &lt;- data.frame(id,a,b,c,e) &gt; str(df) 'data.frame': 8 obs. of 5 variables: $ id: num 6 7 12 14 1 3 4 4 $ a : num 0 1 13 1 3 4 5 6 $ b : num 1 4 12 3 4 5 6 7 $ c : num 0 0 13 3 4 45 6 7 $ e : num 0 0 13 3 4 45 6 7 Desired output- &gt; output id a b c d 1 6 0 1 0 NA 2 7 1 4 0 NA 3 12 13 12 13 NA 4 14 1 3 3 NA 5 1 3 4 4 NA 6 3 4 5 45 NA 7 4 5 6 6 NA 8 4 6 7 7 NA &gt; str(output) 'data.frame': 8 obs. of 5 variables: $ id: num 6 7 12 14 1 3 4 4 $ a : num 0 1 13 1 3 4 5 6 $ b : chr "1" "4" "12" "3" ... $ c : chr "0" "0" "13" "3" ... $ d : logi NA NA NA NA NA NA ... R SOLUTION BY @Frank. res = data.frame( lapply(setNames(,names(template)), function(x) if (x %in% names(df)) as(dfx, class(templatex)) else templatex[NA_integer_] ), stringsAsFactors = FALSE) NOTE- I am trying to do same thing in Python. I am new to python and have no clue how to approach. Any help will be really appreciated.
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/comment/92343107
score: 1
comment on: http://stackoverflow.com/q/52708418
has text: You say you're repeating this code; can you show one repetition so we can see what it is you're changing in each repetition? _(PS: Welcome to StackOverflow! )_
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92250380
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52659659
has text: Reading from sqs is slow and max 10 messages comes in a batch. So by 5 reader threads i can read SQS fast and once i have enough objects to process i operate on them as operate is a heavy process and preforming it per-message is inefficient.
score: 0

http://stackoverflow.com/q/52608088
has comment: http://stackoverflow.com/comment/92168536
has comment: http://stackoverflow.com/comment/92150803
answer count: 1
accepted answer: http://stackoverflow.com/a/52608147
linked to: http://stackoverflow.com/q/240178
tagged with: python
favorite count: 0
upvote count: 2
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92150296
tagged with: python-itertools
has answer: http://stackoverflow.com/a/52608147
score: 1
has body: As far, as I am able to understand, we are unpacking 3 identical iterators in both cases, but output is different. In first case, it, for some reason, similar to list(zip(c[::3], c[1::3], c[2::3])), in second, it behaves like normal zip(). c = [[a, b] for a, b in itertools.product(list(range(3)), list(range(3)))] # first example list(zip(*[iter(c)] * 3)) &gt;[([0, 0], [0, 1], [0, 2]), ([1, 0], [1, 1], [1, 2]), ([2, 0], [2, 1], [2, 2])] # second example list(zip(*[iter(c), iter(c), iter(c)])) &gt;[([0, 0], [0, 0], [0, 0]), ([0, 1], [0, 1], [0, 1]), ([0, 2], [0, 2], [0, 2]), ([1, 0], [1, 0], [1, 0]), ([1, 1], [1, 1], [1, 1]), ([1, 2], [1, 2], [1, 2]), ([2, 0], [2, 0], [2, 0]), ([2, 1], [2, 1], [2, 1]), ([2, 2], [2, 2], [2, 2])]
type: Question
has title: Why this examples of `zip()` code have different outputs?

http://stackoverflow.com/q/52684463
tagged with: python
has answer: http://stackoverflow.com/a/64344924
has answer: http://stackoverflow.com/a/52690018
has answer: http://stackoverflow.com/a/57227144
type: Question
has title: Trying to install trity and it gives me the error
has answer: http://stackoverflow.com/a/56520577
has body: I am trying to install trity and after install it any time I want to run it gives me the error The error is: sh: 1: route: not found Traceback (most recent call last): File "/opt/trity/trity.py", line 27, in &lt;module&gt; from searchs import * File "/opt/trity/searchs.py", line 1, in &lt;module&gt; from google import search ImportError: No module named google
score: 0
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53364613
tagged with: pip

http://stackoverflow.com/comment/92353485
type: AnswerComment
score: 0
type: Comment
has text: I used the try statement as my values that have letters also have numbers. Thanks again!
comment on: http://stackoverflow.com/a/52713093

http://stackoverflow.com/comment/92405535
type: Comment
has text: Then `batch_y` will have object dtype. You can check dtype of `np.array([[1,2,3],[1,2,3]])` and `np.array([[1,2,3],[1,2]])` , First one will be int, the second will be object.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52740208

http://stackoverflow.com/comment/92369736
comment on: http://stackoverflow.com/q/52712821
score: 0
type: Comment
type: QuestionComment
has text: Remove the "print(a, b, c, d)" in fitFunc and add "print(popt)" after the call to curve_fit.

http://stackoverflow.com/q/52681396
score: 1
has body: I have a few lists called find. I want to know if these find are part of full_list. Lists find 1-4 are part of full_list while lists find 5-7 are not. The example below returns "Yes". find1 = [[1, 1]] find2 = [[1, 1], [2, 2]] find3 = [[1, 1], [3, 3]] find4 = [[4, 4], [2, 2], [3, 3]] find5 = [[1, 0]] find6 = [[1, 1], [2, 0]] find7 = [[1, 1], [3, 0]] full_list = [[1, 1], [2, 2], [3, 3], [4, 4]] if find2[0] in full_list and find2[1] in full_list: print("Yes") else: print("No") Because len(find2) != len(find4), the current if statement is very clumsy and almost useless. How to make this work in a more universal way?
type: Question
possible better answer: http://stackoverflow.com/a/52681516
has answer: http://stackoverflow.com/a/52681516
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52681637
favorite count: 0
tagged with: python-3.x
has title: Compare/find a list in another list's nested lists
tagged with: python
has answer: http://stackoverflow.com/a/52681493
accepted answer: http://stackoverflow.com/a/52681493
type: AnsweredQuestion
tagged with: list
tagged with: nested-lists
downvote count: 0

http://stackoverflow.com/a/75154540
has body: As of PyTorch 1.13.0, one can access the list of learning rates via the method scheduler.get_last_lr() - or directly scheduler.get_last_lr()[0] if you only use a single learning rate. Said method can be found in the schedulers' base class LRScheduler (See their code). It actually returns the attribute scheduler._last_lr in the base class as Zahra has mentioned but calling the method should be more preferred. Edit: Thanks @igorkf for the reply
has comment: http://stackoverflow.com/comment/132773159
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/52660985
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/139983084

http://stackoverflow.com/comment/119527508
score: 2
comment on: http://stackoverflow.com/a/65079242
has text: Basically any string you would have on the command line, you make an entry in the array: PyInstaller.__main__.run([ 'some_script.py', '--name', 'my_exe_name', '--specpath', 'some_dir', '--paths', 'some_other_dir', '--onefile', '--windowed' ]) which means: write the full command line as you normally would, then break it into strings and then add a entry in the array, one for every string
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52745859
answer count: 2
has title: Attribute inherited from child class prints child object not string from parent
downvote count: 0
possible better answer: http://stackoverflow.com/a/52745990
tagged with: inheritance
favorite count: 0
has answer: http://stackoverflow.com/a/52745991
accepted answer: http://stackoverflow.com/a/52745991
tagged with: python
type: AnsweredQuestion
upvote count: 3
has body: I know many topics around class inheritance in Python have been addressed, but I could not find a thread that addressed this specific issue. Edit: I'm running Python 3.5.5. Code: class Parent(): def __init__(self, parentParam="parent param"): self.parentParam = parentParam class Child(Parent): def __init__(self, childParam = "child param"): self.childParam = childParam super().__init__(self) child = Child() print(child.childParam) print(child.parentParam) Output: child param &lt;__main__.Child object at 0x0000017CE7C0CAC8&gt; Why does does child.parentParam return the child object and not the string "parent param"? I feel like it should print out the default string set for the Parent class. This appears to be the same syntax as I have been following in this tutorial. Thanks, everyone.
has answer: http://stackoverflow.com/a/52745990
type: Question
score: 3
tagged with: class

http://stackoverflow.com/q/52612997
type: Question
accepted answer: http://stackoverflow.com/a/52613126
has answer: http://stackoverflow.com/a/52613122
has answer: http://stackoverflow.com/a/52613126
has body: my base data is a dictionary with keys being countries, and values being a list of names from position 0 to 9. #base data data {'Newyork': ['Don Willis', 'Lewis Hamilton', 'Kimi Raikkonen', 'Daniel Ricciardo', 'Fernando Alonso', 'Max Verstappen', 'Nico Hulkenberg', 'Valtteri Bottas', 'Stoffel Vandoorne', 'Carlos Sainz'], 'Chicago': ['Don Willis', 'Fernando Alonso',... find_city(name, rank) should, given the name of a contestant and a rank (number 1 rank being index position 0) and, returns a list of all the cities where contestant received a specific rank. find_city("Don Willis", 1) == ["Newyork", "Chicago", "Miami"] find_city("Lewis Hamilton", 6) == [] #None because Lewis Hamilton never ranked 6 in any of city Here's my attempt so far, but not much progress. Any help? def find_city(name, rank): data.get("Newyork",None) b=[] for i in enumerate(a): b.append(i) for (i,v) in b:
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52613188
possible better answer: http://stackoverflow.com/a/52613122
answer count: 4
type: AnsweredQuestion
has title: Dictionary look up by value and return rank based on position?
has answer: http://stackoverflow.com/a/52613225

http://stackoverflow.com/q/52731546
type: Question
has title: Trying to reshape a data frame for upload to a Google Big Query Table
has answer: http://stackoverflow.com/a/52755517
tagged with: pandas
has body: I have data that looks like this; Raw_Title Custom_Field Manager Ben Manager Ron Manager Liz Severity 4 - Low Severity 2 - High Severity 1 - Urgent Type of Dataset Private Type of Dataset Public Type of Dataset Public Request Category Company :: Add Request Category User :: Add User Request Category User :: Remove User Incident Category Pipeline :: Cloud Incident Category UI :: Other Incident Category UI :: Authentication Platform Environment Staging Platform Environment Development Platform Environment Production I am trying to reshape it into this: Manager Severity Type of Dataset Request Category Incident Category Platform Environment Ben 4 - Low Private Company :: Add Pipeline :: Cloud Staging Ron 2 - High Public User :: Add User UI :: Other Development Liz 1 - Urgent Public User :: Remove User UI :: Authentication Production I thought the solution would be like this: df = pd.DataFrame(filtered_df, columns = ['Manager','Severity','Type of Dataset','Request Category ','Incident Category','Platform Environment']) print(df) However that gives me a completely empty data frame!! All I want to do is take the 'Raw_Title' and pivot it from rows to columns, and then list the data points in 'Custom_Field' under each respective 'Raw_Title'. How can I do that? I have to get it into this format so I can export everything to a Google Big Query table. Thanks for the look.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/52755517
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: google-bigquery

http://stackoverflow.com/comment/92213041
comment on: http://stackoverflow.com/q/52595273
has text: can you post a sample image and template?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92217111
has text: code = "definition" to be specific in this case. As Vishal mentioned too.
comment on: http://stackoverflow.com/q/52642078
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52737631
answer count: 1
has comment: http://stackoverflow.com/comment/92402769
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5842903
tagged with: python
has title: Create block tridiagonal matrix
has body: Lets say i have a square numpy array B and an identity array I of the same size. I want to create a block tridiagonal matrix , given an integer n, in the following sense: n=1 return B n=2 return [[B,I],[I,B]] n=3 return [[B,I,0],[I,B,I],[0,I,B]] n=4 return [[B,I,0,0],[I,B,I,0],[0,I,B,I],[0,0,I,B]] and so on.. where 0 is just a zero array of the same size ofc. How can this be done?
linked to: http://stackoverflow.com/q/44641996
has comment: http://stackoverflow.com/comment/92400257
score: 1
has answer: http://stackoverflow.com/a/52740193
type: Question
linked to: http://stackoverflow.com/q/46509744
upvote count: 2
has comment: http://stackoverflow.com/comment/92401481
downvote count: 1

http://stackoverflow.com/comment/92224511
type: QuestionComment
comment on: http://stackoverflow.com/q/52645858
has text: Can you share the relevant models?
score: 0
type: Comment

http://stackoverflow.com/q/52631569
tagged with: python-sounddevice
type: Question
has title: How to Update Samplerate of Sounddevice?
tagged with: python-2.7
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92201116
type: UnansweredQuestion
tagged with: python
has body: I am using sd.Stream to output sound and record from mic simultaneously. I need to be able to get the input and output simultaneously for audio processing in real time which is why I'm using Stream. If I'm using all files that use the same samplerate, this works fine. If I have some audio files that don't have the same samplerate, I need to be able to change the samplerate used by Stream. try: stream = sd.Stream(device=(args.input_device, args.output_device), samplerate=args.samplerate, blocksize=args.blocksize, dtype='float32', latency=(0, 0), channels=len(args.channels), callback=callback, finished_callback=finished_callback) with stream: ani = FuncAnimation(fig, update_plot, interval=args.interval, blit=False, init_func=plot_init) plt.show() My First attempt is to close the stream in the finished_callback: def finished_callback(): global stream print "just closed" stream.close() and then reopen a stream in update_plot: if stream.closed and callback.fs_mismatch: args.samplerate = callback.new_fs callback.fs_mismatch = 0 stream = sd.Stream(device=(args.input_device, args.output_device), samplerate=args.samplerate, blocksize=args.blocksize, dtype='float32', latency=(0, 0), channels=len(args.channels), callback=callback, finished_callback=finished_callback) print "stopped stream and fs mismatch!\n" Reopening the stream does not seem to have any effect at all. I believe the reason for this is that I don't have anything blocking after the new stream like I use earlier (plt.show). I can't have anything blocking in this section because this is where I am updating my plot. Is there a way to change the samplerate of the stream after it is already open or is there another way to accomplish what I'm trying to do?
has answer: http://stackoverflow.com/a/52649238

http://stackoverflow.com/comment/112825490
comment on: http://stackoverflow.com/q/52720961
has text: JFYI `time.sleep()` in Python 3.5 or above does what you want. Source: [*time.sleep()*](https://docs.python.org/3/library/time.html#time.sleep)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52724789
has answer: http://stackoverflow.com/a/73926241
has title: Which is the best way to programatically terminate (cancel) a celery task
tagged with: celery
has body: According to Celery's documentation, we should not use the terminate option in revoke() function to cancel an executing task: The terminate option is a last resort for administrators when a task is stuck. It’s not for terminating the task, it’s for terminating the process that’s executing the task, and that process may have already started processing another task at the point when the signal is sent, so for this reason you must never call this programmatically. http://docs.celeryproject.org/en/latest/userguide/workers.html#revoke-revoking-tasks So, my question is, how should I properly do if I need to cancel some running tasks programmatically?
type: Question
upvote count: 4
answer count: 2
possible better answer: http://stackoverflow.com/a/73926241
has answer: http://stackoverflow.com/a/54880615
downvote count: 0
score: 4
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/54880615
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52681516
upvote count: 1
answers question: http://stackoverflow.com/q/52681396
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92291296
score: 1
has body: Try this: set1 = set(find1) full_set = set(full_list) if set1.issubset(full_set): print("Yes") else: print("No")

http://stackoverflow.com/a/52673787
type: AcceptedAnswer
upvote count: 10
type: Answer
accepted answer of: http://stackoverflow.com/q/52673728
downvote count: 0
answers question: http://stackoverflow.com/q/52673728
score: 10
has body: You can pass the bytes string into list() to convert back: &gt;&gt;&gt; lst = [1, 2, 3, 4, 5] &gt;&gt;&gt; bytes(lst) b'\x01\x02\x03\x04\x05' &gt;&gt;&gt; list(bytes(lst)) [1, 2, 3, 4, 5]

http://stackoverflow.com/q/52731801
score: 0
has comment: http://stackoverflow.com/comment/92388842
type: Question
has body: Given a contrived Python class: class Item(object): def __getattr__(self, name): print("In __getattr__ looking for '{}'".format(name)) if name.startswith("exists"): return "Here's a dummy string" message = "'{}' object has no attribute '{}'".format(type(self).__name__, name) raise AttributeError(message) def thing_a(self): return self.thing_b() def thing_b(self): return self.nonexistent_thing() Calling Item().thing_a() produces the expected output: In __getattr__ looking for 'nonexistent_thing' Traceback (most recent call last): File "debug.py", line 13, in &lt;module&gt; Item().thing_a() File "debug.py", line 8, in thing_a return self.thing_b() File "debug.py", line 11, in thing_b return self.nonexistent_thing() File "debug.py", line 5, in __getattr__ raise AttributeError(message) AttributeError: 'Item' object has no attribute 'nonexistent_thing' However, I really want thing_a, thing_b, and nonexistent_thing to be properties. So, if I change my code to: class Item(object): def __getattr__(self, name): print("In __getattr__ looking for '{}'".format(name)) if name.startswith("exists"): return "Here's a dummy string" message = "'{}' object has no attribute '{}'".format(type(self).__name__, name) raise AttributeError(message) @property def thing_a(self): return self.thing_b @property def thing_b(self): return self.nonexistent_thing and call Item().thing_a, I get an unexpected result: In __getattr__ looking for 'nonexistent_thing' In __getattr__ looking for 'thing_b' In __getattr__ looking for 'thing_a' Traceback (most recent call last): File "debug.py", line 15, in &lt;module&gt; Item().thing_a File "debug.py", line 5, in __getattr__ raise AttributeError(message) AttributeError: 'Item' object has no attribute 'thing_a' Uh-oh... the print() output appears to be the reverse of the execution order, and the message for AttributeError is for thing_a, which does exist. During my experimentation to figure this out, I discovered that changing AttributeError to a plain old Exce…
answer count: 1
has comment: http://stackoverflow.com/comment/92388785
has answer: http://stackoverflow.com/a/52732020
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92388916
tagged with: python
has title: Raising AttributeError has unexpected side effects with @properties

http://stackoverflow.com/a/52675343
answers question: http://stackoverflow.com/q/52675046
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/92280073
accepted answer of: http://stackoverflow.com/q/52675046
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: None of the pickle formats use offsets into the file or any kind of compression or encryption, so changing the name is fine even if it changes the length. You have to know that the text “ClassA” doesn’t appear for some other reason, of course, and that your editor won’t mangle the file—say, by trying to do character decoding/encoding. That said, in this situation I’d probably create a dummy package to give ClassA the correct name rather than edit the pickle.

http://stackoverflow.com/q/52642977
has body: I understand the concept of the gabor kernel and how it can be used to identify directional edges. So I want to use it to identify barcode lines in images. However when I filter an image with a gabor kernel I always get a blank/black result. Can you provide feedback on what I need to do to get Gabor to identify the vertical lines in an image, ie, produce a result that has white where the vertical edges are? Input image: Result: import cv2 import numpy as np def deginrad(degree): radiant = 2*np.pi/360 * degree return radiant def main(): src = cv2.imread('./images/barcode1.jpg', cv2.IMREAD_GRAYSCALE) # Introduce consistency in width const_width = 300 aspect = float(src.shape[0]) / float(src.shape[1]) src = cv2.resize(src, (const_width, int(const_width * aspect))) src = cv2.GaussianBlur(src, (7,7), 0) # Apply gabor kernel to identify vertical edges g_kernel = cv2.getGaborKernel((9,9), 8, deginrad(0), 5, 0.5, 0, ktype=cv2.CV_32F) gabor = cv2.filter2D(src, cv2.CV_8UC3, g_kernel) # Visual the gabor kernel h, w = g_kernel.shape[:2] g_kernel = cv2.resize(g_kernel, (20*w, 20*h), interpolation=cv2.INTER_CUBIC) cv2.imshow('src', src) cv2.imshow('gabor', gabor) # gabor is just black cv2.imshow('gabor kernel', g_kernel) cv2.waitKey(0) if __name__ == "__main__": main()
tagged with: python
has answer: http://stackoverflow.com/a/52643332
score: 0
answer count: 1
tagged with: opencv
tagged with: filtering
type: UnansweredQuestion
has title: Using gabor kernel to extract vertical lines results in black image
type: Question

http://stackoverflow.com/q/52654805
type: Question
has comment: http://stackoverflow.com/comment/92277390
has comment: http://stackoverflow.com/comment/92241120
has comment: http://stackoverflow.com/comment/92271236
has comment: http://stackoverflow.com/comment/92242195
has comment: http://stackoverflow.com/comment/92241997
has comment: http://stackoverflow.com/comment/92242117
upvote count: 2
has body: SOLVED - Solution posted as answer, thanks all for the help. After compiling my python application using PyQt5 to an executable file, the icons contained in my GUI are removed / not displayed. Specifically QIcon instances added to my Window(QMainWindow) class using self.setWindowIcon(QtGui.QIcon(fpath)) and a QPixmap(f2path) embedded in a QLabel via label.setPixmap(myPixmap). I have tried to search on this forum for possible solutions but couldn't find a problem solving thread. I've tried to set the absolute filepath as recommended here Bundling data files with PyInstaller (--onefile) and here Missing button icons in pyinstaller No idea where to start examining problems, there are no errors when compiling with pyinstaller and it runs fine as a python script. pyinstaller -w -F MY_GUI.py Thanks in advance! Example: import sys import os def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) return os.path.join(base_path, relative_path) import sys import resource_path # code taken from links above from PyQt5 import QtGui from PyQt5.QtWidgets import QApplication, QMainWindow class Window(QMainWindow): def __init__(self): super().__init__() self.title = "MyProg" self.top = 400 self.left = 400 self.width = 680 self.height = 540 icon_path = resource_path("icon.png") self.setWindowIcon(QtGui.QIcon(icon_path)) self.InitUI() def InitUI(self): self.setWindowTitle(self.title) self.setGeometry(self.top, self.left, self.width, self.height) self.show() App = QApplication(sys.argv) window = Window() sys.exit(App.exec())
has comment: http://stackoverflow.com/comment/92271340
tagged with: pyqt
has comment: http://stackoverflow.com/comment/92271317
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52673912
has comment: http://stackoverflow.com/comment/92241316
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92241152
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/92254363
has comment: http://stackoverflow.com/comment/92254341
tagged with: python
linked to: http://stackoverflow.com/q/44130289
has answer: http://stackoverflow.com/a/52673912
has comment: http://stackoverflow.com/comment/92241918
has comment: http://stackoverflow.com/comment/92241022
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/7674790
has comment: http://stackoverflow.com/comment/92241342
tagged with: pyqt5
has title: Icons missing from PyQt5 app after compiling to .exe using pyinstaller
linked to: http://stackoverflow.com/q/404744

http://stackoverflow.com/comment/92332547
type: QuestionComment
comment on: http://stackoverflow.com/q/52698202
score: 0
has text: Is this a correct statement of your problem: You have 65•512•5 floating-point numbers, say in some array x[64,512,5]. You add 1 to each x[i,j,k]. Let’s call the results y[i,j,k]. Let X be the sum of adding all the x[i,j,k], and let Y be the sum of adding all the y[i,j,k]. You expect Y−X to equal 163840 (65•512•6), but it is a slightly different number.
type: Comment

http://stackoverflow.com/comment/92377901
score: 0
type: Comment
has text: Right... In that case, how about trying using `np.genfromtxt()` instead? Or just include the absolute path of your `data.txt` file.
comment on: http://stackoverflow.com/a/52726248
type: AnswerComment

http://stackoverflow.com/q/52700417
tagged with: python
has title: Convert red line in image to numpy list
tagged with: opencv
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/52702710
type: Question
has comment: http://stackoverflow.com/comment/92328958
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/52702710
has body: I want to measure the height difference to ground of the detected object in this pipe. The lower red line shall be the marker for minimum height. I thought I might first convert the lower red line into a numpy list but how would I do that? The red circles are drawn with cv2.circle() function. Edit: Thanks to ZdaR I am closer to solving my problem. This is his solution rewritten to work with python3: import cv2 import numpy as np def get_center(arr): return sum(arr)/len(arr) def get_cluster_centers(arr, tolerance): clusters = [[arr[0]]] for ele in arr[1:]: if abs(clusters[-1][0] - ele) &lt; tolerance: clusters[-1].append(ele) else: clusters.append([ele]) clusters_centers = map(get_center, clusters) return clusters_centers img = cv2.imread("/home/artur/Desktop/0.png") # Segment the red color mask = cv2.inRange(img, np.array([0, 0, 255]), np.array([0, 0, 255])) for i in mask: print(i) # Let's iterate the middle column and get the distance between the two red lines. half_width = int(mask.shape[1]/2) middle_column = mask[:, half_width] idx = np.where(middle_column == 255) # Since the width of line is not 1 px so we need to cluster the pixels to get a single center value. centers = list(get_cluster_centers(idx[0], 5)) if len(centers) == 2: print("Distance between lines:", centers[1] - centers[0], "px") It measures the pixel distance between upper and lower red line with the help of the middle column of the image. How would I iterate over all columns to determine the minimum distance between those two line or better, between detected object and lower red line? Do I get it right that this solution only takes the middle column into account?
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92306095
type: Comment
type: AnswerComment
score: 0
has text: Thanks for your help, but this problem is not resolved. I update my question.
comment on: http://stackoverflow.com/a/52689105

http://stackoverflow.com/comment/92251581
type: QuestionComment
score: 0
has text: As per my knowledge, there is no ready to use solution available for this. You can write your own solution by finding successive NNP tags and combining them. There are many challenges in above approach so you have to tackle them.
comment on: http://stackoverflow.com/q/52660336
type: Comment

http://stackoverflow.com/comment/92342907
comment on: http://stackoverflow.com/q/52707891
has text: There's no way you got that error by calling the code you called. The interpreter would have exploded earlier: like when you call `add_to_bank_balance(balance)` without properly defining `balance`.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92219072
comment on: http://stackoverflow.com/a/52592378
type: AnswerComment
score: 0
type: Comment
has text: Thank you. Could you give me the full code? I don't know why but I couldn't do circle detection for the mask, cause my last purpose is to write the letter P into the pollen.

http://stackoverflow.com/q/52610160
has title: Function only returns desired value once
has comment: http://stackoverflow.com/comment/92154784
has comment: http://stackoverflow.com/comment/92155032
tagged with: python
has comment: http://stackoverflow.com/comment/92154736
has answer: http://stackoverflow.com/a/52610316
type: AnsweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/92154612
has comment: http://stackoverflow.com/comment/92154817
type: Question
has comment: http://stackoverflow.com/comment/92154909
tagged with: function
accepted answer: http://stackoverflow.com/a/52610316
has comment: http://stackoverflow.com/comment/92154840
has comment: http://stackoverflow.com/comment/92155918
score: 0
has body: I've created a script that will search a target file for a keyword. If that keyword is on a certain line of text, it will take the entire text and return the rest of the line not containing the keyword. For example, if there is a line of text that says: Title: Useless Data then the script will only take the part that says "useless data" and append it to a list. It will do this for every place in the file where the word "title" appears. The script is successful if only run once to get several lines from the file and output them into a list, but I want to search the file for two key words: title and icon, and then zip the title to the corresponding icon. Thus, if I take a line of text that looks like this: LINE 1: Title: Useless Data Icon: Fairly upset programmer Index: 12 filler data: LINE 2: Title: Line 2 Icon: Pancho Index: 69 filler data: The output should be: list1 = ['Useless Data', 'Line 2'] list2 = ['Fairly upset programmer', 'Pancho'] I then want to zip them into a dict that looks like this: final_dict = {'Useless Data' : 'Line 2', 'Fairly upset programmer': 'Pancho'} title_list = {} target_file = open('Meta.txt', 'r') # Searches for word in a line and removes all the useless data def splitter(files, word): output = [] for line in files: if word in line: output.append(line.split(':')[1].replace('\n', '').strip()) else: continue print(output) return output split1 = splitter(target_file, 'icon') split2 = splitter(target_file, 'title') final = zip(split1, split2)
answer count: 1

http://stackoverflow.com/q/52649867
linked to: http://stackoverflow.com/q/6319612
has title: Python 3: How to search for a list created from a user's input?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52649966
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/52650004
has answer: http://stackoverflow.com/a/52650004
accepted answer: http://stackoverflow.com/a/52649966
tagged with: list
answer count: 2
upvote count: 1
has body: I'm trying to create a dictionary of lists for an inventory. Example I add 'fruits', 'vegetables', 'drinks' as keys of a dictionary then I create a list for each of them. Once created, I add two items (e.g. 'apple','manggo') for each list so I can print them out like this: fruits is list items in fruits are apple, manggo veggies is list items in veggies are cabbage, cucumber drinks is list items in drinks are iced tea, juice However I am unable to identify the items of newly created list and I only get this: fruits is list items in fruits are fruits My code: class Inventory: def __init__(self): self.dict_inv = dict() self.count_inv = int(input("Enter the number of inventories: ")) for count in range(self.count_inv): self.name_inv = str(input("Enter Inventory #%d: " % (count+1))) self.dict_inv[self.name_inv] = count self.name_inv = list() sample_add = str(input("Add item here: ")) self.name_inv.append(sample_add) sample_add2 = str(input("Add another item here: ")) self.name_inv.append(sample_add2) for keys in self.dict_inv.keys(): if type([keys]) is list: print("%s is list" % keys) print("items in %s are %s" % (keys,str(keys))) Inventory()

http://stackoverflow.com/comment/92198177
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52631416
type: Comment
has text: Just to be clear, shouldn't the row with `IRS21231` come before the row with `YOU28137`? In other words, the last two rows should be swapped.

http://stackoverflow.com/comment/92276040
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52669417
has text: I tried but got an error stating AttributeError: 'str' object has no attribute 'text' AttributeErrorTraceback (most recent call last) <ipython-input-51-cc7f77a316d8> in <module>() 23 pass 24 ---> 25 Rank= Rank.text 26 Rank= Rank.replace(",",'|') 27 AttributeError: 'str' object has no attribute 'text'
score: 0

http://stackoverflow.com/q/52712295
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/52712415
favorite count: 0
has answer: http://stackoverflow.com/a/52712309
possible better answer: http://stackoverflow.com/a/52713197
has answer: http://stackoverflow.com/a/52713197
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: machine-learning
has body: I have two multidimensional array(matrix) in numpy, one being the training set(100,100 dimension) and other being the class label(100X1 dimension) I want to take random samples using np.random.choice but don't know how to figure out taking the same row no. from both matrices. for eg., k=np.random.choice(10,replace=False) temp_data=data.ix[k] temp_datat=datat.ix[k] would this work for sampling 10 same random rows from both my arrays data and datat?
type: Question
has answer: http://stackoverflow.com/a/52712415
score: 3
has title: random sample of two 100X100 multidimensional arrays, with same row no. in python numpy
tagged with: numpy
tagged with: numpy-ndarray
tagged with: random

http://stackoverflow.com/a/52612616
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: You should look at DataFrame.groupby. Also Consider using list comprehension to create your labels: bins = [15, 30, 40, 50, 60, np.inf] labels = [f'{i}+' if j==np.inf else f'{i}-{j}' for i, j in zip(bins, bins[1:])] dataset['AgeRange'] = pd.cut(dataset['Age'], bins, labels) dataset.groupby('AgeRange')['Purchased'].sum()
type: Answer
accepted answer of: http://stackoverflow.com/q/52612524
answers question: http://stackoverflow.com/q/52612524

http://stackoverflow.com/a/52660701
score: 0
answers question: http://stackoverflow.com/q/52645326
type: Answer
has body: In your urls.py, you have added, persondetails/pk.. hence it will redirect you to the url e.g. for id 3, http://127.0.0.1:4000/persondetails/3/ You can add it in ..person/persondetail/pk... For better arrangement, views.py, class PersonDetailPageView(DetailView): model = Your_Model_Name template_name = 'your_template_name.html' In html, &lt;a href="{% url 'persondetails' person.id %}"&gt; your template &lt;/a&gt;

http://stackoverflow.com/comment/92244838
score: 0
type: AnswerComment
has text: Great. What if we have more of these tags? Maybe use `find_all`? Can you edit your answer?
comment on: http://stackoverflow.com/a/52656366
type: Comment

http://stackoverflow.com/a/52610071
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92155727
type: Answer
answers question: http://stackoverflow.com/q/52608087
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52608087
has body: If you got script content, try below to get required values: import re result = re.findall('product.*"(.*)"', source_arr[0]) print(result) # ['Mobile', 'Smartphone', 'SM-N960', 'galaxy note9']
score: 1
has comment: http://stackoverflow.com/comment/92156047

http://stackoverflow.com/a/79164645
has comment: http://stackoverflow.com/comment/139594293
has comment: http://stackoverflow.com/comment/139597713
has body: Check out this simpler version. x = eval(input("Enter a number: ")) s = 0 for i in range(1, x): if x % i == 0: s += i print(s)
has comment: http://stackoverflow.com/comment/139594304
upvote count: 0
score: -2
answers question: http://stackoverflow.com/q/52592953
type: Answer
downvote count: 2

http://stackoverflow.com/comment/92230704
comment on: http://stackoverflow.com/q/52649416
type: Comment
score: 8
has text: `currencyName = currency.replace('/', '_') + '-'`…?!
type: QuestionComment

http://stackoverflow.com/comment/92164868
comment on: http://stackoverflow.com/q/52615130
score: 0
type: Comment
type: QuestionComment
has text: Try using `beautifulsoup` instead. You'll probably have much better luck!

http://stackoverflow.com/comment/92373094
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52709876
has text: In the SAS log files, the lines I'm looking for will always be a line counter, followed by spaces - with a total length of 11 before any other characters should be found. So - look at these https://regex101.com/r/m24BZk/2

http://stackoverflow.com/a/52717056
answers question: http://stackoverflow.com/q/52716511
has body: Please find a working chunk of code below: from datetime import date, timedelta import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np a = pd.Series(np.random.randint(10, 99, 10)) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) plt.gca().xaxis.set_major_locator(mdates.DayLocator()) plt.plot(pd.date_range(date(2016,1,1), periods=10, freq='D'), a) plt.gcf().autofmt_xdate() Hope it helps :)
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92361042
has comment: http://stackoverflow.com/comment/92361108
has comment: http://stackoverflow.com/comment/92361092
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52716511
type: Answer
has comment: http://stackoverflow.com/comment/92360272

http://stackoverflow.com/q/52738023
answer count: 1
has comment: http://stackoverflow.com/comment/92400652
type: UnansweredQuestion
has title: How to make api call in python?
tagged with: python
linked to: http://stackoverflow.com/q/17301938
tagged with: apache-tika
has answer: http://stackoverflow.com/a/52738406
type: Question
has comment: http://stackoverflow.com/comment/92400744
has body: I have ran tika server in my machine and call api using terminal which is working fine. I am able to extract text from image and pdf. But, I want to implement the api call in my python application. curl -T price.xls http://localhost:9998/tika --header "Accept: text/plain" Above is api call that i have to make. I can run this in my terminal and works fine but how to implement in python application. I have installed and tried requests. API_URL = 'http://localhost:9998/tika' APP_ROOT = os.path.dirname(os.path.abspath(__file__)) tika_client = TikaApp(file_jar=join(APP_ROOT,'../tika-app-1.19.jar')) data = { "url": join(APP_ROOT,'../static/image/a.pdf') } response = requests.put(API_URL, data) print(response.content) Any help will be appreciate. Thank you :) error output INFO tika (application/x-www-form-urlencoded) WARN tika: Text extraction failed org.apache.tika.exception.TikaException: Unexpected RuntimeException from org.apache.tika.server.resource.TikaResource$1@475b0e2 at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:282) at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:143) at org.apache.tika.server.resource.TikaResource.parse(TikaResource.java:402) at org.apache.tika.server.resource.TikaResource$5.write(TikaResource.java:513) at org.apache.cxf.jaxrs.provider.BinaryDataProvider.writeTo(BinaryDataProvider.java:177) at org.apache.cxf.jaxrs.utils.JAXRSUtils.writeMessageBody(JAXRSUtils.java:1391) at org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor.serializeMessage(JAXRSOutInterceptor.java:246) at org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor.processResponse(JAXRSOutInterceptor.java:122) at org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor.handleMessage(JAXRSOutInterceptor.java:84) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308) at org.apache.cxf.interceptor.OutgoingChainInterceptor.handleMessage(OutgoingChainInterceptor.java:90) at org.apache.cxf.phase.PhaseInterceptorCha…
score: 0

http://stackoverflow.com/q/52632301
tagged with: python
has comment: http://stackoverflow.com/comment/92199187
tagged with: cuda
has title: Can I program to avoid GPU memory errors? like cuMemAlloc results in CUDA_ERROR_LAUNCH_FAILED
tagged with: memory-management
answer count: 0
has comment: http://stackoverflow.com/comment/92197899
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/92199236
tagged with: tensorflow
type: Question
has body: I am doing some fun testing of my GPU Nvidia video card. Set up a nice program that does operations on the intel CPU and then does them by vectorizing them on the GPU. It is cool, because I get about an 80x speed improvement when I use the GPU. However, with some simple programs, I have been able to just blow out the memory constraint and one of my programs, trashes the kernal. import tensorflow as tf import numpy as np from timeit import default_timer as timer from numba import vectorize import gc @vectorize(['float32(float32, float32)'], target='cuda') def loopGPU(vStart, vEnd): vPosition=vStart vOriginal=vStart for vStart in range(vEnd): vPosition=vPosition+1 print('Counted from: ', vOriginal, ' to: ', vEnd, ' by: 1 ' ) return(vPosition) def loop2aTrillion(vStart, vEnd): start = timer() vNewStart=loopGPU(vStart, vEnd) duration = timer() - start print('GPU Loop Time',duration) loop2aTrillion(1,100000000) Counted from: 1.000000 to: 100000000.000000 by: 1 GPU Loop Time 3.7991681657728336 So it works great to about 100 million.. But If I go to a Billion or even 500 million.. I get this amazing error from CUDA See my try to see where the breaking point is.. loop2aTrillion(1,100) Counted from: 1.000000 to: 100.000000 by: 1 GPU Loop Time 0.10281342493556167 loop2aTrillion(1,1000000) Counted from: 1.000000 to: 1000000.000000 by: 1 GPU Loop Time 0.048263507262902294 loop2aTrillion(1,100000000) Counted from: 1.000000 to: 100000000.000000 by: 1 GPU Loop Time 3.7804056272377693 loop2aTrillion(1,100000000) Counted from: 1.000000 to: 100000000.000000 by: 1 GPU Loop Time 3.797257584627573 loop2aTrillion(1,1000000000) Traceback (most recent call last): File "", line 1, in File "", line 3, in loop2aTrillion File "D:\Anaconda\envs\tensorflow\lib\site-packages\numba\cuda\dispatcher.py", line 88, in call return CUDAUFuncMechanism.call(self.functions, args, kws) File "D:\Anaconda\envs\tensorflow\lib\site-packages\numba\npyufunc\deviceufunc.py", line 311, in call return devout.copy_to…
tagged with: anaconda
linked to: http://stackoverflow.com/q/6913206
duplicate of: http://stackoverflow.com/q/6913206

http://stackoverflow.com/q/52729693
has comment: http://stackoverflow.com/comment/92385491
has comment: http://stackoverflow.com/comment/92384525
upvote count: 1
has title: Parse Verizon PDF Bill Call Log
has answer: http://stackoverflow.com/a/52730323
tagged with: parsing
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52730428
answer count: 4
has answer: http://stackoverflow.com/a/52734170
type: Question
tagged with: powershell
score: -1
tagged with: string
has comment: http://stackoverflow.com/comment/92514721
has answer: http://stackoverflow.com/a/52732983
has body: I extracted the talk activity contents of my Verizon bill to a text file. I want to do some analysis of the data. I prefer using powershell, python or bash. Any ideas on how I can convert the following to a csv: Jan 6 12:30 PM Unavailable Las Vegas, NV Incoming, CL 2 Jan 7 11:06 AM 697.732.5672 Reno, NV Victorvl, CA 30 Jan 4 3:26 PM 702.792.2189 Las Vegas, NV VM Deposit, CL 1 Jan 24 4:24 PM 213.302.2581 Sacramento, CA Incoming, CL 105 Example of what the results should look like: "Jan 6 12:30 PM","Unavailable","Las Vegas, NV","Incoming, CL","2" "Jan 7 11:06 AM","697.732.5672","Reno, NV","Victorvl, CA","30" "Jan 4 3:26 PM","702.792.2189","Las Vegas, NV","VM Deposit, CL","1" "Jan 24 4:24 PM","213.302.2581","Sacramento, CA","Incoming, CL","105" Thanks for any advise.
has comment: http://stackoverflow.com/comment/92385086
downvote count: 2
tagged with: bash

http://stackoverflow.com/a/52736874
answers question: http://stackoverflow.com/q/52736840
type: Answer
has comment: http://stackoverflow.com/comment/92398501
has body: Actually the built in print function has a file keyword argument. You can use this to redirect your output to a file of your choice. input_file = 'test.txt' output_file = 'out.txt' with open(input_file, 'r') as fp: with open(output_file, 'w') as out_fp: line = fp.readline() cnt = 1 while line: i = int(line, 16) print(str(i), file=out_fp) line = fp.readline() cnt += 1 Assuming you have test.txt with the following content: ff 10 Then out.txt will contain: 255 16 As of python 2.7 or python 3.1 you can even combine those two with statements ... with open(input_file, 'r') as fp, open(output_file, 'w') as out_fp: ...
score: 0
has comment: http://stackoverflow.com/comment/92398618

http://stackoverflow.com/comment/92302568
type: QuestionComment
comment on: http://stackoverflow.com/q/52686490
has text: you may want to check `pd.options.display.float_format` for formatting options
score: 0
type: Comment

http://stackoverflow.com/comment/92277743
type: QuestionComment
type: Comment
has text: What exactly is the problem? You described what you want. So *just do it*?
comment on: http://stackoverflow.com/q/52673941
score: 0

http://stackoverflow.com/comment/92127099
type: Comment
type: QuestionComment
score: 0
has text: Oh that makes sense! I'm wanting to write out the distance matrix I computed to a text file. The portion of the code that does the distance matrix is: scipy.spatial.distance.cdist(coords, coords, 'euclidean') How would I make it output in a way I can capture everything and write it to a text file?
comment on: http://stackoverflow.com/q/52595201

http://stackoverflow.com/a/52644886
downvote count: 0
has comment: http://stackoverflow.com/comment/92223498
has comment: http://stackoverflow.com/comment/92223267
has comment: http://stackoverflow.com/comment/92223410
has comment: http://stackoverflow.com/comment/92222854
has comment: http://stackoverflow.com/comment/92223389
type: Answer
has comment: http://stackoverflow.com/comment/92222353
answers question: http://stackoverflow.com/q/52644597
has body: I believe you need list comprehension with loc and zip for list of DataFrames: t1=[4202, 6453] t2=[6203, 6492] dfs = [df.loc[i:j] for i, j in zip(t1, t2)] print (dfs[0]) print (dfs[1]) Sample: np.random.seed(142) df = pd.DataFrame({'column':np.random.rand(8)}) print (df) column 0 0.902062 1 0.557808 2 0.655985 3 0.832471 4 0.199884 5 0.127254 6 0.771439 7 0.432289 t1=[1, 3] t2=[2, 5] dfs = [df.loc[i:j] for i, j in zip(t1, t2)] print (dfs) [ column 1 0.557808 2 0.655985, column 3 0.832471 4 0.199884 5 0.127254] print (dfs[0]) column 1 0.557808 2 0.655985 print (dfs[1]) column 3 0.832471 4 0.199884 5 0.127254
score: 1
has comment: http://stackoverflow.com/comment/92222268
upvote count: 1
has comment: http://stackoverflow.com/comment/92223514
has comment: http://stackoverflow.com/comment/92223950
has comment: http://stackoverflow.com/comment/92222933
has comment: http://stackoverflow.com/comment/92235303

http://stackoverflow.com/comment/92225452
type: Comment
has text: @Gigaflop If you like, although `file.read()` is simpler. My objection in the previous comment was to `.readlines`, which is kind of pointless here.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52646429

http://stackoverflow.com/q/52673941
answer count: 1
favorite count: 0
has title: Print enumerated list of a class
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/92277743
has answer: http://stackoverflow.com/a/52674107
downvote count: 3
type: Question
upvote count: 0
has body: I have written the following code which creates a vector list and then a vector dictionary without the zeros. class SparseVec: def __init__(self, n): self.val = [0] * n self.len = len(self.val) def __len__(self): return self.len def __getitem__(self,*i): return self.val def __setitem__(self, i, n): self.val[i] = n self.len = max(i, self.len) print 'self.len = ', self.len def nonzeros(self): nonzeroDict = {} for i in range(len(self.val)): if self.val[i] != 0: nonzeroDict[i] = self.val[i] return 'Sparse Vector{}'.format(nonzeroDict) def __add__(self, other): length = self.len result = SparseVec(length) if self.len &lt; len(other.val): length = len(other.val) result = SparseVec(length) for i in range(self.len): result[i] = self.val[i] + other.val[i] for j in other.val: if j not in self.val: result[j] = other.val[j] return result def __str__(self): return '{}'.format(self.val) if __name__ == '__main__': a = SparseVec(5) a[2] = 9.2 a[0] = -1 a[3] = 0 print a print a.nonzeros() b = SparseVec(5) b[1] = 1 print b print b.nonzeros() c = a+b print c print c.nonzeros() How can I rewrite the __str__ method in order to get as a result something like this? print a [0] = 2 [1] = 5 etc... Also I want this: for ai, i in a: print 'a[%d]=%g' % (i, ai) to provide a similar result as above with an a in front of the list index: a[0] = 2 a[1] = 5
has comment: http://stackoverflow.com/comment/92277543

http://stackoverflow.com/a/52710441
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52710315
has body: You can reduce 3 branching statements to 2 if you use the math.copysign function: import math direction = 0 if left == right else math.copysign(1, left - right) copysign will copy the sign of left - right and apply it to the left operand (in this case, 1). If left and right are floats, use math.isclose to check for closeness accounting for floating inaccuracies. direction = 0 if math.isclose(left, right) else math.copysign(1, left - right) If you have numpy, you can handle the special case of left == right with the function itself using np.sign: import numpy as np direction = np.sign(left - right)
downvote count: 0
type: Answer

http://stackoverflow.com/a/52599319
score: 5
type: Answer
has body: We can take advantage of the fact that your data is sorted to eliminate the fillna, reduce two groupby calls to one, and eliminate the need for apply. df['session'] = df.day.diff().ge(2) df['session'] = df.groupby('id').session.cumsum() df id day session 0 1 1 0.0 1 1 2 0.0 2 1 10 1.0 3 1 11 1.0 4 2 3 0.0 5 2 4 0.0 6 2 12 1.0 7 2 15 2.0 8 3 1 0.0 9 3 20 1.0 10 3 21 1.0 11 3 24 2.0 In return, "session" will be a float column.
upvote count: 5
answers question: http://stackoverflow.com/q/52599040
downvote count: 0
has comment: http://stackoverflow.com/comment/92203517

http://stackoverflow.com/comment/92309383
has text: I would think that is very wasteful of bandwidth, indeed not a very elegant solution. Not going to upvote that, but happy that your issue is solved for now.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52681536
type: Comment

http://stackoverflow.com/a/52615751
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92166005
accepted answer of: http://stackoverflow.com/q/52615494
answers question: http://stackoverflow.com/q/52615494
type: Answer
has body: Since it appears that both lists are ordered in the sequence that you would like them joined, you can use list comprehension along with the * operator (splatting) to get the result you want. For example: list1 = [{'user':'John'},{'user':'Micheal'},{'user':'Sara'}] list2 = [{'Status':'Active'},{'Status':'Active'},{'Status':'Inactive'}] results = [{**list1[i], **list2[i]} for i in range(len(list1))] print(results) # OUTPUT # [{'user': 'John', 'Status': 'Active'}, {'user': 'Micheal', 'Status': 'Active'}, {'user': 'Sara', 'Status': 'Inactive'}]

http://stackoverflow.com/a/52684801
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52684644
answers question: http://stackoverflow.com/q/52684644
has body: I usually use something like this with numpy: tol = max(np.finfo(float).eps, np.finfo(float).eps * abs(a - b))
score: 0
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/52709059
has answer: http://stackoverflow.com/a/52709547
tagged with: pandas
downvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92345179
tagged with: python
has body: So I have the preceding dataframe to which I want to add a new column called "dload" which I achieve by coding df["dload"] = np.nan I then want to fill in the nan value with the returns of this function: def func_ret_value(soup,tables): for td in tables[40].findAll("td"): if td.text == "Short Percent of Float": value = list(td.next_siblings)[1].text.strip("%") #print(value) return value To do this I write the following code: for index in df.index: # print(index,row) # print(index,df.iloc[index]["Symbol"]) r = requests.get(url_pre+df.iloc[index]["Symbol"]+url_suf) soup = BeautifulSoup(r.text,"html.parser") tables = soup.findAll("table") #print(row["dload"]) df.loc[index,"dload"] = func_ret_value(soup,tables) Is there some iterrows or apply that is a faster way of doing this? Thank you.
upvote count: 0
has title: Pandas DataFrame Speed
type: Question
tagged with: dataframe
score: -1

http://stackoverflow.com/a/52716157
has comment: http://stackoverflow.com/comment/92372370
has body: Add the following lines of code to your script and run it : from distutils.sysconfig import get_python_lib print(get_python_lib()) Now check the output, you will get some path printed which points to the exact location of the packages the python interpreter is currently using e.g. "/usr/lib/python2.7/dist-packages" cd(change directory) to the above path and ls(list directory) to check if package exists ; if not : sudo pip3 install requests -t . # dot indicates current directory or else if you have a requirements.txt file then you could try: sudo pip3 install -r requirements.txt -t "/usr/lib/python2.7/dist-packages" #try this from the directory where "requirements.txt" file exists Now run your scripts and please let me know if it worked
score: 1
has comment: http://stackoverflow.com/comment/92372866
has comment: http://stackoverflow.com/comment/92379674
has comment: http://stackoverflow.com/comment/92379257
has comment: http://stackoverflow.com/comment/92359155
has comment: http://stackoverflow.com/comment/92372905
has comment: http://stackoverflow.com/comment/92372933
downvote count: 0
answers question: http://stackoverflow.com/q/52713154
has comment: http://stackoverflow.com/comment/92359176
has comment: http://stackoverflow.com/comment/92371339
has comment: http://stackoverflow.com/comment/92372159
type: Answer
upvote count: 1

http://stackoverflow.com/a/52603672
has comment: http://stackoverflow.com/comment/92143167
type: Answer
has comment: http://stackoverflow.com/comment/92143525
accepted answer of: http://stackoverflow.com/q/52603355
has comment: http://stackoverflow.com/comment/92143632
has comment: http://stackoverflow.com/comment/92143221
has comment: http://stackoverflow.com/comment/92143314
score: 0
answers question: http://stackoverflow.com/q/52603355
has body: This should work, check this code. from bs4 import BeautifulSoup html = """ Mixed Brown Rice 2.5kg """ soup = BeautifulSoup(html, 'html.parser') Title = soup.find('h1', attrs={'class':'product-name'}).text print(Title) Output: Mixed Brown Rice 2.5kg
type: AcceptedAnswer

http://stackoverflow.com/comment/92119806
type: Comment
type: QuestionComment
has text: For 100M runs, I get `5.633208999999624` for the imported, and `6.241973999996844` for the non-imported. But it is possible that due to "pagination" some function is faster than the other, but this is more "ad random" (sometimes the first function can be split over two pages, sometimes the other).
comment on: http://stackoverflow.com/q/52592520
score: 1

http://stackoverflow.com/comment/92379334
comment on: http://stackoverflow.com/a/52726982
score: 0
type: AnswerComment
type: Comment
has text: And if I set `blit=False`, the quality is really poor. I have to manually adjust the animation writer to get the desired quality. Not sure why.

http://stackoverflow.com/comment/100551733
has text: @keepAlive this still won't work for `np.array([np.array(True, True), np.array([True, True, True])]`. Indeed painful :)
comment on: http://stackoverflow.com/a/52715811
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92130457
comment on: http://stackoverflow.com/q/52597864
has text: anything that can be passed to `bool`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52693649
score: 2
has comment: http://stackoverflow.com/comment/92314982
accepted answer of: http://stackoverflow.com/q/52693081
has comment: http://stackoverflow.com/comment/92314774
answers question: http://stackoverflow.com/q/52693081
has comment: http://stackoverflow.com/comment/92314786
has body: (df['b'] &lt; 0).cummax().astype(int).max() simply checks if any value is less than 0. You can use (df['b'] &lt; 0).any() instead. There's also no need for int conversion as Boolean values are considered 1 / 0 for True / False respectively. As a side note, loc / iloc tend to be more efficient than other forms of slicing, but this isn't the main driver of poor performance, despite your tests. You can use a generator expression with sum for the equivalent algorithm: sum((v.loc[:250, 'b'] &lt; 0).any() for v in alldf.values()) Here's some performance benchmarking: np.random.seed(0) # use this to reproduce results numdfs = 10**2 # create 100 dataframes alldf = {i: pd.DataFrame({col: np.random.randn(250) for col in 'abcd'}) \ for i in range(numdfs)} def jpp(alldf): return sum((v.loc[:250, 'b'] &lt; 0).any() for v in alldf.values()) def original(alldf): count=250 runningsum = 0 for i in range(len(alldf)): df = alldf[i].head(count) df['is negative'] = (df['b'] &lt; 0).cummax().astype(int) runningsum += df['is negative'].max() return runningsum assert jpp(alldf) == original(alldf) %timeit jpp(alldf) # 46.6 ms %timeit original(alldf) # 6.46 s The algorithm is still pretty slow as you are needlessly checking every single value in 'b' when it's possible to short-circuit if a value less than zero is found. A loopy way is possible with numba which improves on the original algorithm by a factor of ~12,000x. from numba import njit @njit def any_below_zero(arr, k): for i in range(k): if arr[i] &lt; 0: return 1 return 0 def jpp_nb(alldf): return sum(any_below_zero(v['b'].values, 250) for v in alldf.values()) %timeit jpp_nb(alldf) # 525 µs For 10,000 dataframes, as in your tests, this works in less than a second: numdfs = 10**5 # create 10000 dataframes alldf = {i: pd.DataFrame({col: np.random.randn(250) for col in 'abcd'}) \ for i in range(numdfs)} %timeit jpp_nb(alldf) # 746 ms
has comment: http://stackoverflow.com/comment/92314793
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92314797
type: Answer

http://stackoverflow.com/comment/92140038
score: 0
comment on: http://stackoverflow.com/q/52602835
type: Comment
type: QuestionComment
has text: @RedCricket Done

http://stackoverflow.com/comment/92344909
score: 0
has text: `string[6:7] = 'CG'` - do you really want `6:7` (one symbol) or `6:7+1` (two?)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52709166

http://stackoverflow.com/q/52629441
linked to: http://stackoverflow.com/q/4693120
has answer: http://stackoverflow.com/a/52629934
has answer: http://stackoverflow.com/a/52629718
downvote count: 0
has answer: http://stackoverflow.com/a/52630195
favorite count: 0
has answer: http://stackoverflow.com/a/52629508
tagged with: python
has body: I have defined a function that would print a specific string depending on its value. However, I get an error message saying that global name 'must_print' is not defined. This is the code I have: def myfunction(must_print): must_print = True if bool(must_print) == True: print("Done") elif bool(must_print) == False: print("Change value") if __name__ == "__main__": myfunction(must_print) Do you know why I'm getting this error?
answer count: 4
type: UnansweredQuestion
has title: How to define a boolean parameter in Python
has comment: http://stackoverflow.com/comment/92192605
upvote count: 1
linked to: http://stackoverflow.com/q/291978
has comment: http://stackoverflow.com/comment/92192377
score: 1
has comment: http://stackoverflow.com/comment/92192305
type: Question

http://stackoverflow.com/q/52663313
answer count: 1
upvote count: 6
score: 4
has comment: http://stackoverflow.com/comment/92257386
favorite count: 0
has comment: http://stackoverflow.com/comment/92256989
has answer: http://stackoverflow.com/a/55414203
accepted answer: http://stackoverflow.com/a/55414203
tagged with: python
linked to: http://stackoverflow.com/q/52600729
has title: Use tensor to set a specific seed?
has body: I would like to build graph with some random values in it. Then I would like to evaluate the graph with different seeds. Here is an example what I'm trying to achieve: import tensorflow as tf seed = tf.placeholder(dtype=tf.int32, shape=(), name="seed") randoms = tf.random_normal(shape=[8], seed=seed) Then I was hoping to do something like this where first two calls would return same result: sess = tf.InteractiveSession() sess.run(randoms, {seed: 1}) sess.run(randoms, {seed: 1}) sess.run(randoms, {seed: 2}) Is there any way to work around this problem?
has comment: http://stackoverflow.com/comment/97558938
tagged with: tensorflow
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/92256763
downvote count: 2

http://stackoverflow.com/comment/92317662
type: Comment
has text: Please consider simplifying your code so people can more easily understand it and help you.
type: QuestionComment
comment on: http://stackoverflow.com/q/52695533
score: 0

http://stackoverflow.com/comment/92312748
type: QuestionComment
has text: @AndrewMcDowell so i've noticed something super strange, instead of `len(items)` returning the number of items on each page, it'll return `32` for the first page, then `64` for the second page (33-64), `96` for the third (65-96), so on and so forth... how can this be happening?? wth
comment on: http://stackoverflow.com/q/52692120
score: 0
type: Comment

http://stackoverflow.com/comment/92282019
score: 0
has text: you need to escape special character in regex. use \'
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52676396

http://stackoverflow.com/q/52660618
has title: How to test Python Code on Darwin (via virtualiziation)
downvote count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/92544577
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/92374313
has answer: http://stackoverflow.com/a/52881347
accepted answer: http://stackoverflow.com/a/52881347
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92251667
type: Question
has body: I wrote a little tool to dump the environment of a python interpreter: dumpenv I have only a linux operating system. Is there a way to test my code on darwin os? AFAIK running darwin in a docker container is not possible. Buying hardware is not an option.
answer count: 1
has comment: http://stackoverflow.com/comment/92545233
tagged with: darwin
score: 0
has comment: http://stackoverflow.com/comment/92251789

http://stackoverflow.com/comment/92142700
type: QuestionComment
comment on: http://stackoverflow.com/q/52604074
has text: check updated post please
score: 0
type: Comment

http://stackoverflow.com/q/52651598
has answer: http://stackoverflow.com/a/52651714
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52651714
has body: I'm trying to simply move files from folder path1 to folder path. import os import shutil path1 = '/home/user/Downloads' file_dir = os.listdir(path1) fpath = '/home/user/music' for file in file_dir: if file.endswith('.mp3'): shutil.move(os.path.join(file_dir,file), os.path.join(fpath, file)) ... but I get this error TypeError: expected str, bytes or os.PathLike object, not list
has comment: http://stackoverflow.com/comment/92234946
accepted answer: http://stackoverflow.com/a/52651685
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/92235011
favorite count: 0
has comment: http://stackoverflow.com/comment/92234949
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52651728
has title: Programmaticallly moving files in python
has answer: http://stackoverflow.com/a/52651685
type: AnsweredQuestion

http://stackoverflow.com/a/52689369
type: Answer
answers question: http://stackoverflow.com/q/52688645
score: 1
upvote count: 1
has body: Your data doesn't follow the conventions used by Python / Pandas datetime objects. There should be only one way of storing a particular datetime, i.e. '10/11/2006 24:00' should be rewritten as '11/11/2006 00:00'. Here's one way to approach the problem: # find datetimes which have '24:00' and rewrite twenty_fours = df['strings'].str[-5:] == '24:00' df.loc[twenty_fours, 'strings'] = df['strings'].str[:-5] + '00:00' # construct datetime series df['datetime'] = pd.to_datetime(df['strings'], format='%d/%m/%Y %H:%M') # add one day where applicable df.loc[twenty_fours, 'datetime'] += pd.DateOffset(1) Here's some data to test: dateList = ['10/11/2006 24:00', '11/11/2006 00:00', '12/11/2006 15:00'] df = pd.DataFrame({'strings': dateList}) Result after transformations described above: print(df['datetime']) 0 2006-11-11 00:00:00 1 2006-11-11 00:00:00 2 2006-11-12 15:00:00 Name: datetime, dtype: datetime64[ns]
downvote count: 0

http://stackoverflow.com/comment/92184081
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52601988
has text: @SargeATM for both, and double click on the script to run it too, no way work fine

http://stackoverflow.com/q/52610966
has comment: http://stackoverflow.com/comment/92159555
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/39472017
has comment: http://stackoverflow.com/comment/92156983
type: UnansweredQuestion
tagged with: animation
tagged with: python
tagged with: plot
has body: I was trying to make an animation using pcolormesh but my code was having problems, so I decided to use one of the answers in this post as a starting point. The answer had too many plots in it and I only needed the pcolormesh, so I removed the unnecessary plots. The puzzling thing is that removing the plots broke the animation for some reason. I made some minimal example that contains the pcolormesh and some text. The code works as long as I don't comment the text update but I'm unable to figure why. My questions are the following: Is there any reason the pcolormesh won't update in some scenarios? How can I fix the animation without adding other plots or text? Note: I'm using OSX which apparenlty has some issues with the blit option. import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation y, x = np.meshgrid(np.linspace(-10, 10,100), np.linspace(-10, 10,100)) z = np.sin(x)*np.sin(x)+np.sin(y)*np.sin(y) fig = plt.figure(figsize=(16, 8),facecolor='white') ax = plt.subplot() quad = ax.pcolormesh(x,y,z,shading='gouraud') ax.set_xlabel('time') ax.set_ylabel('amplitude') cb = fig.colorbar(quad,ax=ax) time_text = ax.text(0.02, 0.95, 'start', transform=ax.transAxes) def animate(iter): z = np.sin(x-iter/(2*np.pi))*np.sin(x-iter/(2*np.pi))+np.sin(y)*np.sin(y) time_text.set_text(str(iter)) #comment this line to break the animation quad.set_array(z.ravel()) anim = animation.FuncAnimation(fig,animate,frames=100,interval=50,blit=False,repeat=False) plt.show() Edit: As it was pointed out in the comments, it had to do with the backend. My updated questions are: why does this code fail for some backends? Shouldn't the behavior of pcolormesh be independent of the text added?
has comment: http://stackoverflow.com/comment/92160089
answer count: 0
has title: matplotlib's pcolormesh does not update during animation. Why?
score: 1
tagged with: matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/92163389
has comment: http://stackoverflow.com/comment/92156501
type: Question
linked to: http://stackoverflow.com/q/18797175
has comment: http://stackoverflow.com/comment/92165928
has comment: http://stackoverflow.com/comment/92158773
has comment: http://stackoverflow.com/comment/92156723

http://stackoverflow.com/q/52600892
has comment: http://stackoverflow.com/comment/92136363
has comment: http://stackoverflow.com/comment/92138362
tagged with: python
has comment: http://stackoverflow.com/comment/92136341
has comment: http://stackoverflow.com/comment/92136153
has comment: http://stackoverflow.com/comment/92136464
has comment: http://stackoverflow.com/comment/92136166
has comment: http://stackoverflow.com/comment/92136437
answer count: 0
has comment: http://stackoverflow.com/comment/92136326
type: UnansweredQuestion
has body: I just started learning Python a few weeks ago so I'm fairly new to Python. I'm trying to write a code that takes in user's numbers and turn them into a letter based grade. After finding the average of the user's input I want a letter based grade for the average as well. Here's my code def scores(): get_scores = [] for i in range(5): get_grades.append(input("Enter your 5 grades and positive numbers")) print(get_grades) def calculate_Average(get_scores): average = (get_scores) / 5 return average def assign_grade(get_scores): if (get_score &lt; 60): return "F" elif (get_score &lt; 70): return "D" elif (get_score &lt; 80): return "C" elif (get_score &lt; 90): return "B" elif (get_score &lt; 100): return "A" For some reason when I try to run the code I kept on getting SyntaxError: multiple statements found while compiling a single statement Any help is appreciated thanks!
has comment: http://stackoverflow.com/comment/92136195
has comment: http://stackoverflow.com/comment/92136254
has comment: http://stackoverflow.com/comment/92136138
has comment: http://stackoverflow.com/comment/92136396
has comment: http://stackoverflow.com/comment/92136511
has comment: http://stackoverflow.com/comment/92136477
has title: Why am I getting SyntaxError: multiple statements found while compiling a single statement?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92136753
linked to: http://stackoverflow.com/q/24588956

http://stackoverflow.com/a/52637741
downvote count: 0
score: 1
has body: import timeit from multiprocessing import Pool def appendNumber(x): return x start = timeit.default_timer() with Pool(4) as p: numbers = p.map(appendNumber, range(100000000)) end = timeit.default_timer() print('TIME: {} seconds'.format(end - start)) print('SUM:', sum(numbers)) So Pool.map is like the builtin map function. It takes a function and an iterable and produces a list of the result of calling that function on every element of the iterable. Here since we don't actually want to change the elements in the range iterable we just return the argument. The crucial thing is that Pool.map divides up the provided iterable (range(1000000000) here) into chunks and sends them to the number of processes it has (defined here as 4 in Pool(4)) then rejoins the results back into one list. The output I get when running this is TIME: 8.748245699999984 seconds SUM: 4999999950000000
answers question: http://stackoverflow.com/q/52636002
type: Answer
upvote count: 1

http://stackoverflow.com/q/52742364
type: Question
has body: I need some help getting my python script to work on both python2 and python3. In python3, when I run the script and get to the part where you select the ITAG, it says: From the lists above, find the ITAG number of the format you want to convert the video to. Type the ITAG number here: Traceback (most recent call last): File "/home/MrMcTiller/autopytubev2_working.py", line 299, in &lt;module&gt; Type the ITAG number here: """)) ValueError: could not convert string to float: &gt;&gt;&gt; Here is a link to my python script.
has comment: http://stackoverflow.com/comment/92415691
has answer: http://stackoverflow.com/a/52775523
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92409440
answer count: 1
has comment: http://stackoverflow.com/comment/92429495
favorite count: 0
has comment: http://stackoverflow.com/comment/92415492
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92421939
tagged with: python
linked to: http://stackoverflow.com/q/14152548
downvote count: 6
has comment: http://stackoverflow.com/comment/92472828
score: -5
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/92415600
has title: I need some help getting my python script to work

http://stackoverflow.com/comment/92266422
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52668103
has text: As per the docs: `The query string to evaluate. You can refer to variables in the environment by prefixing them with an ‘@’ character like @a + b.`
score: 1

http://stackoverflow.com/q/52737821
answer count: 1
downvote count: 0
favorite count: 0
has title: Python: why is this array an object instead of a float?
has answer: http://stackoverflow.com/a/52740208
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I am trying to order data and make an array for each unique ID. Data I'm using are columns of integers/floats or empty cells (NaN). I will paste a simplified version of the code below: import pandas as pd import numpy as np dtypes = {'starttime': 'str', 'endtime': 'str', 'hr': 'float', 'sofa_24hours': 'float'} parse_dates = [2,3] fields = [0,1,11,12,13,14,15,34,35,36] reader = pd.read_csv(filename, header=0, names=headers, dtype=dtypes, parse_dates=parse_dates, usecols=fields) print("Started loading data...") df = pd.DataFrame(data=reader) ids = list(df.iloc[:, 0]) id_list = np.unique(ids) x = df.iloc[:, 2:6].astype(float) y = df.iloc[:, 7].astype(float) t = df.iloc[:, 0].astype(float) x_data = [] y_data = [] t_data = [] for i in range(0,len(id_list)): idx = np.where(ids==id_list[i])[0] t_data.append(t.values[idx[0]:idx[-1]+1]) x_data.append(x.values[idx[0]:idx[-1]+1,:]) y_data.append(y.values[idx[0]:idx[-1]+1]) if np.mod(i,1000)==0: print("Data association... {}%".format(np.round(100*i/len(id_list)))) print("Finished loading data!") Now, when I check for the type: In [1]: y.dtype Out[1]: dtype('float64') That seems about right. Then I cut the data into batches using: batch_size=64 W=5 idx_pt = np.random.randint(W,len(x_data),batch_size) idx_t = [np.random.randint(0,len(x_data[i])-W-1) for i in idx_pt] batch_x = np.array([x_data[idx_pt[i]][idx_t[i]:idx_t[i]+W,:] for i in range(0,len(idx_pt))]) batch_y = np.array([y_data[idx_pt[i]] for i in range(0,len(idx_pt))]) When I check for dtype: In [2]: batch_x.dtype Out[2]: dtype('float64') In [3]: batch_y.dtype Out[3]: dtype('O') Why is batch_y treated as an object?
accepted answer: http://stackoverflow.com/a/52740208
type: Question
tagged with: numpy
tagged with: object
tagged with: arrays
tagged with: types

http://stackoverflow.com/comment/92325423
score: 0
type: Comment
type: QuestionComment
has text: `u'...'` creates an object of type `unicode`. Your `mystring` object is **already* such an object; it's not the `print()` function that turns it into something else.
comment on: http://stackoverflow.com/q/52699494

http://stackoverflow.com/comment/92116451
comment on: http://stackoverflow.com/q/52589982
score: 0
has text: yes sir i want background image
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/130210734
type: Comment
comment on: http://stackoverflow.com/a/72242984
score: 0
type: AnswerComment
has text: This answer has no context to it and no reason for the additional sleeps. I found only a sleep is needed after opening the compport, maybe do to initialization? Either way this answer is incorrect.

http://stackoverflow.com/q/52702788
possible better answer: http://stackoverflow.com/a/52703344
tagged with: python
tagged with: regex
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/52703423
accepted answer: http://stackoverflow.com/a/52703423
type: Question
has answer: http://stackoverflow.com/a/52703344
score: 1
has title: Extracting string with an optional ending pattern
answer count: 2
upvote count: 1
has body: I want to extract a substring that may either appear between two substrings or in the end of the original string. The starting delimiter is ab and the ending delimiter may be cd or the end of the original string. Examples: c = 'ab123:random text1 cd4576:text2' d = 'cd123:text2 ab75589:text1' e = 'ab35:rand text2 cd765:text1' Desired answer: c = 'random text1' d = 'text1' e = 'rand text2' I am able to match the starting substring with re.findall('ab\d+:(.*)', i). But when I try to add the ending pattern, I cannot find the desired answer: re.findall('ab\d+:(.*)', i) &gt;&gt;&gt; ['random text1 cd4576: text2'], [' text1'], ['rand text2 cd765: text1'] re.findall('^ab\d+:(.*)cd\d+:', i) &gt;&gt;&gt;['random text1 '], [], ['rand text2 ']
favorite count: 0

http://stackoverflow.com/q/52639774
has body: Is it possible for a file f that os.path.isfile(f) and os.path.isdir(f) both evaluate to false? What would a third category be named in this case? Szenario: I have created a contentless file using touch on ubuntu 18.04, which definitely is not a directory. Python (version 3.5) nevertheless returns false on isfile(f). Edit: It turns out that the file indeed returned True, the earlier output was a small mistake in my code. The question still remains as I thought about it this way: I have a set (Set A) of all files in a directory. I create a subset via isfile filtering (Set B). I create a subsets via isdir filtering (Set C). Would the union of B and C be equal to A?
linked to: http://stackoverflow.com/q/32741079
has title: Can isfile() and isdir() functions both evaluate to False?
has comment: http://stackoverflow.com/comment/92244912
answer count: 1
has comment: http://stackoverflow.com/comment/92244922
favorite count: 0
has comment: http://stackoverflow.com/comment/92211903
downvote count: 2
has answer: http://stackoverflow.com/a/52639891
tagged with: python
has comment: http://stackoverflow.com/comment/92211910
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92212242
has comment: http://stackoverflow.com/comment/92212054
has comment: http://stackoverflow.com/comment/92212245
has comment: http://stackoverflow.com/comment/92212582
upvote count: 7
has comment: http://stackoverflow.com/comment/92244917
type: Question
has comment: http://stackoverflow.com/comment/92237503
score: 5
accepted answer: http://stackoverflow.com/a/52639891
has comment: http://stackoverflow.com/comment/92212231

http://stackoverflow.com/a/52713435
downvote count: 0
answers question: http://stackoverflow.com/q/52713261
has body: As @Warren Weckesser says, the problem is that I'm not considering the dx term (the base size for the intergal) Fortunately this is easy to fix, so for completness, here it goes... import numpy as np from scipy.stats import norm def func(mu, sigma, gamma): # Notice the retstep=True param, it will return the dx needed x, dx = np.linspace(mu-4*sigma, mu + 4*sigma, 100, retstep=True) y = norm.pdf(x, mu, sigma) # multiply all with dx area = y[x&gt;=gamma].sum() * dx print(f"Area is ~ {area:.3f}") plt.plot(x,y, label=f'μ0 = {mu}, σ={sigma}') plt.fill_between(x[x&gt;gamma],y[x&gt;gamma], alpha=.5, label=f'area={area:.3f}') plt.title("Example") plt.legend(loc='best') plt.show() func(0,10,-20) Now output makes sence, it's Area is ~ 0.978 and the image is Thanks a lot @Warren Weckesser!!
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52713261
type: AcceptedAnswer

http://stackoverflow.com/q/52672068
type: Question
tagged with: indexing
tagged with: dataframe
has body: I have a pandas dataframe as shown below: Name ID1 ID2 Joe 248 248 Joe 248 326 Joe 721 248 Anna 295 295 Bob 721 248 Bob 721 326 Bob 248 566 I need to keep only the rows that do not have matching ID1 &amp; ID2, with the exception that, if both the IDs matched at least once for a Name, then drop them. For example: For Name = Joe, IDs match once (248), so remove all rows with Joe. For Name = Bob, IDs never match, so keep all rows with Bob. So far, I've tried: Dropping duplicates by sorting names and checking if IDs match or not. But this does not take into account IDs matching at least once. df = df.sort_values(['Name']).drop_duplicates(['Name'],keep='first') Not sure if pandas can drop duplicates with condition where something matches 'atleast once'.
answer count: 2
has title: Pandas - Filter rows where columns match atleast once
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/52672274
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92274407
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52672205
score: 2
accepted answer: http://stackoverflow.com/a/52672205
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52672274

http://stackoverflow.com/a/52650627
type: Answer
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52649778
has body: It's much easier to use manage.py instead of django-admin, because manage.py takes care of setting DJANGO_SETTINGS_MODULE for you. Start the project with django-admin: django-admin startproject myproject But after that, use manage.py instead, e.g. python manage.py makemigrations python manage.py migrate python manage.py runserver

http://stackoverflow.com/a/52643105
has comment: http://stackoverflow.com/comment/92219098
has comment: http://stackoverflow.com/comment/92219438
has comment: http://stackoverflow.com/comment/92219351
has comment: http://stackoverflow.com/comment/92219270
has comment: http://stackoverflow.com/comment/92219454
has comment: http://stackoverflow.com/comment/92219310
answers question: http://stackoverflow.com/q/52643037
type: Answer
has comment: http://stackoverflow.com/comment/92219205
score: 2
upvote count: 3
has body: You can do this perhaps: d = { "Fruit_1" : ["mango", "apple"], "Fruit_2" : ["apple"], "Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"] } # list comprehension mango_keys = [fruit for fruit in d.keys() if "mango" in d[fruit]] print(mango_keys) # ['Fruit_1', 'Fruit_3'] # or more traditional for-loop (but non pythonic) for fruit in d.keys(): if "mango" in d[fruit]: print(fruit)
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52643037
has comment: http://stackoverflow.com/comment/92219435
has comment: http://stackoverflow.com/comment/92219291
has comment: http://stackoverflow.com/comment/92219221
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92219241

http://stackoverflow.com/q/52646106
tagged with: python
tagged with: audio
has comment: http://stackoverflow.com/comment/92224627
downvote count: 3
upvote count: 1
type: Question
has body: probably this may be duplicate question. I had searched lot but didn't found the answer. I am working with audio analysis where a main audio file need to be broken down into chunks of audio files where each should of a single sentence. When I took ~3 seconds audio for which the process I am doing is taking around 5 minutes, But taking a bigger audio length the time required to complete the process is getting much higher. for example a 5 minutes audio is taking ~14 hours. What I did first I created a csv file containing time(in seconds) vs Amplitude, then took a threshold where the amplitude less than i will be 0 and greater will be 1. Later I check if the number of consecutive 0 is greater than another threshold j then took the time of that position. Hence, I found the time of end of sentence. This process taking too long so any other methods will be helpfull. My Dataset is as follows: 1.000000000000000000e+00,0.000000000000000000e+00,6.103515625000000000e+01 2.000000000000000000e+00,2.267999999999999969e-05,3.051757811999999959e+01 3.000000000000000000e+00,4.534999999999999779e-05,0.000000000000000000e+00 4.000000000000000000e+00,6.802999999999999748e-05,3.051757811999999959e+01 5.000000000000000000e+00,9.069999999999999558e-05,3.051757811999999959e+01 6.000000000000000000e+00,1.133800000000000020e-04,0.000000000000000000e+00 7.000000000000000000e+00,1.360500000000000001e-04,0.000000000000000000e+00 8.000000000000000000e+00,1.587299999999999931e-04,0.000000000000000000e+00 9.000000000000000000e+00,1.814100000000000131e-04,0.000000000000000000e+00 1.000000000000000000e+01,2.040800000000000112e-04,0.000000000000000000e+00 1.100000000000000000e+01,2.267600000000000041e-04,0.000000000000000000e+00 1.200000000000000000e+01,2.494299999999999751e-04,3.051757811999999959e+01 1.300000000000000000e+01,2.721099999999999951e-04,0.000000000000000000e+00 1.400000000000000000e+01,2.947800000000000203e-04,0.000000000000000000e+00 1.500000000000000000e+01,3.174599999999999861e-04,0…
has title: Large CSV file processing
score: -2
has comment: http://stackoverflow.com/comment/92224948
has comment: http://stackoverflow.com/comment/92224706
has comment: http://stackoverflow.com/comment/92225876
has comment: http://stackoverflow.com/comment/92225075
has comment: http://stackoverflow.com/comment/92224864
has comment: http://stackoverflow.com/comment/92226154
answer count: 1
tagged with: shell
has answer: http://stackoverflow.com/a/52652262
has comment: http://stackoverflow.com/comment/92224334
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/129256970
type: Comment
comment on: http://stackoverflow.com/a/52630923
has text: @DSM Is there a way to perform this conversion by preserving the values as integers? I don't want them to be moved to float.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52704126
has body: I have the folowing dataframe: cpf day startdate enddate 1234 1 08/01/2018 12:50:0 08/01/2018 15:50:0 1234 1 08/01/2018 14:30:0 08/01/2018 15:50:0 1234 1 08/01/2018 14:50:0 08/01/2018 15:50:0 1234 2 08/02/2018 20:20:0 08/02/2018 23:50:0 1234 2 08/02/2018 22:50:0 08/02/2018 23:50:0 1235 1 08/01/2018 11:50:0 08/01/2018 15:20:0 5212 1 08/01/2018 14:50:0 08/01/2018 15:20:0 I need to calculate conversation time of cpf column in one day. For example, the first cpf is 1234, so in day 1 this cpf initiate a conversation on 08/01/2018 12:50:0 and the end of conversation was 08/01/2018 15:50:0, what I need is exactly this substraction about enddate - startdate. How can I do this? cpf day startdate enddate Time_Conversation 1234 1 08/01/2018 12:50:0 08/01/2018 15:50:0 3:00:0 1234 1 08/01/2018 14:30:0 08/01/2018 15:50:0 3:00:0 1234 1 08/01/2018 14:50:0 08/01/2018 15:50:0 3:00:0 1234 2 08/02/2018 20:20:0 08/02/2018 23:50:0 3:30:0 1234 2 08/02/2018 22:50:0 08/02/2018 23:50:0 3:30:0 1235 1 08/01/2018 11:50:0 08/01/2018 15:20:0 4:30:0 5212 1 08/01/2018 14:50:0 08/01/2018 15:20:0 4:30:0
tagged with: data-science
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52704545
score: 1
upvote count: 1
type: Question
has title: How can I count repetitions of cpf in determinate day?
has comment: http://stackoverflow.com/comment/92772865
tagged with: dataframe
has answer: http://stackoverflow.com/a/52704676
answer count: 2
has comment: http://stackoverflow.com/comment/92337507
has comment: http://stackoverflow.com/comment/92772450
downvote count: 0

http://stackoverflow.com/comment/92306212
has text: Why don't you Google search for how to use dictionaries? As it is, your question is very unclear.
comment on: http://stackoverflow.com/q/52689640
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92225062
has text: You can get the sorted index of your sorted X-array and then use that to plot the Y-array
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52646527
score: 1

http://stackoverflow.com/q/52616489
has comment: http://stackoverflow.com/comment/92167216
score: 0
has comment: http://stackoverflow.com/comment/92167212
has comment: http://stackoverflow.com/comment/92167236
tagged with: idioms
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92167411
has body: Is there a more idiomatic way to do this in Python: a=1 b=a b=2 assert a==2 than by doing this "hack": a=[1] b=a b[0]=2 assert a[0]==2
tagged with: reference
answer count: 0
has comment: http://stackoverflow.com/comment/92167539
has comment: http://stackoverflow.com/comment/92167545
type: Question
has comment: http://stackoverflow.com/comment/92167465
has title: Python "reference trick"

http://stackoverflow.com/q/52639445
score: 3
answer count: 0
upvote count: 3
has title: Jupyter : [Errno -2] Name or service not known Error
type: Question
tagged with: cloud
tagged with: google-cloud-platform
downvote count: 0
tagged with: jupyter-notebook
favorite count: 0
type: UnansweredQuestion
has body: Jupyter notebook was working well for me. But just after I finished installing some packages. it crashed and stopped working. I could not even find similar case on the internet. I spent a lot of time trying to install a some special packages : cuda , imgaug, imageio, and others. I don't want to loose my work in case I tried to uninstall jupyter ! I don't know what to do here! Should I reinstall jupyter ? Any safe cmd line to do it safely ? I am afraid to do so because I don't want to take the risk to loose any installed packages (I spent a lot of time trying to install them) Any help ? PS : I am working with google cloud VM with ubuntu 16 as OS. chami_soufiane_fr:~$ jupyter notebook Traceback (most recent call last): File "/home/chami_soufiane_fr/anaconda3/lib/python3.6/site-packages/traitlets/traitlets.py", line 528, in get value = obj._trait_values[self.name] KeyError: 'allow_remote_access' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/chami_soufiane_fr/anaconda3/lib/python3.6/site-packages/notebook/notebookapp.py", line 869, in _default_allow_remote addr = ipaddress.ip_address(self.ip) File "/home/chami_soufiane_fr/anaconda3/lib/python3.6/ipaddress.py", line 54, in ip_address address) ValueError: '' does not appear to be an IPv4 or IPv6 address During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/chami_soufiane_fr/anaconda3/bin/jupyter-notebook", line 11, in &lt;module&gt; sys.exit(main()) File "/home/chami_soufiane_fr/anaconda3/lib/python3.6/site-packages/jupyter_core/application.py", line 266, in launch_instance return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs) File "/home/chami_soufiane_fr/anaconda3/lib/python3.6/site-packages/traitlets/config/application.py", line 657, in launch_instance app.initialize(argv) File "&lt;decorator-gen-7&gt;", line 2, in initialize File "/home/chami_soufiane_fr/anaconda3/lib/python3.6…
tagged with: python
tagged with: computer-vision

http://stackoverflow.com/comment/92145769
has text: Can you add the line `os.path.dirname(os.path.abspath(__file__))` to your script (before the `input` call) and check that the folder is the correct one containing the file you're trying to open? Also, try passing the absolute pat to the file you want to open and see if that works
comment on: http://stackoverflow.com/q/52605666
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/52709166
has answer: http://stackoverflow.com/a/53261119
type: Question
has comment: http://stackoverflow.com/comment/92344909
has answer: http://stackoverflow.com/a/52709442
has answer: http://stackoverflow.com/a/52709315
has comment: http://stackoverflow.com/comment/92344681
has comment: http://stackoverflow.com/comment/92344823
has answer: http://stackoverflow.com/a/52709419
score: 0
has title: Python: Adding integer elements of a nested list to a list
has comment: http://stackoverflow.com/comment/92344874
answer count: 4
has comment: http://stackoverflow.com/comment/92344592
tagged with: nested-lists
has comment: http://stackoverflow.com/comment/92344759
has comment: http://stackoverflow.com/comment/92344791
has comment: http://stackoverflow.com/comment/92344571
tagged with: bioinformatics
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has body: So, I have two lists whose integer elements need to be added. nested_lst_1 = [[6],[7],[8,9]] lst = [1,2,3] I need to add them such that every element in the nested list, will be added to its corresponding integer in 'lst' to obtain another nested list. nested_list_2 = [[6 + 1],[7 + 2],[8 + 3,9 + 3]] or nested_list_2 = [[7],[9],[11,12]] Then, I need to use the integers from nested_list_1 and nested_list_2 as indices to extract a substring from a string. nested_list_1 = [[6],[7],[8,9]] *obtained above* nested_list_2 = [[7],[9],[11,12]] *obtained above* string = 'AGTCATCGTACGATCATCGAAGCTAGCAGCATGAC' string[6:7] = 'CG' string[7:9] = 'GTA' string[8:11] = 'TACG' string[9:12] = 'ACGA' Then, I need to create a nested list of the substrings obtained: nested_list_substrings = [['CG'],['GTA'],['TACG','ACGA']] Finally, I need to use these substrings as key values in a dictionary which also possesses keys of type string. keys = ['GG', 'GTT', 'TCGG'] nested_list_substrings = [['CG'],['GTA'],['TACG','ACGA']] DNA_mutDNA = {'GG':['CG'], 'GTT':['GTA'], 'TCGG':['TACG','ACGA']} I understand that this is a multi-step problem, but if you could assist in any way, I really appreciate it.
has comment: http://stackoverflow.com/comment/92344770

http://stackoverflow.com/comment/92359313
has text: Yes I didnt notice the g inside loop. Now I did it. Thanks
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52716540

http://stackoverflow.com/comment/92312037
type: Comment
has text: @tsb I tried to be as informative as I could along the way, I didn't want to give you the answer but the only way I could explain what is going on and what you need to learn is to walk through it step by step, I added to the paragraph about `.split()` and will include some links
type: AnswerComment
comment on: http://stackoverflow.com/a/52692256
score: 0

http://stackoverflow.com/a/52751642
has body: Here's a working solution for Python(3.6): addr = None while addr is None: out = subprocess.check_output(["kubectl get ing | awk '{print $3}'"], shell=True) print(out) all_addr = out.decode().split('\n') if re.match(r"\d+\.\d+\.\d+\.\d+", str(all_addr[1])): addr = all_addr[1] print('Address is: {}'.format(addr)) else: addr = None
type: Answer
answers question: http://stackoverflow.com/q/52741990
score: 0

http://stackoverflow.com/comment/92286485
has text: @DušanMaďar ... that's their code. And it's still O(1), there is no search.
type: AnswerComment
comment on: http://stackoverflow.com/a/52678799
score: 0
type: Comment

http://stackoverflow.com/comment/92405787
type: Comment
comment on: http://stackoverflow.com/a/52740540
type: AnswerComment
has text: First of all thank you for solution @C.K. but it doesn't take`a3`
score: 0

http://stackoverflow.com/a/52709445
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52708886
has body: Sometimes writing out your question provides you with an answer. I'll write mine here in case any have commentary or have a similar question. When iterating through the nested dictionary, in addition to counting/collecting the terminal answers, I also collect the variables I'll need later for graphing, append them in lists. for field in data.keys(): if field.startswith('Header'): for subheading in data.get(field): for index, answer in data.get(field).get(subheading).get('Directory').items(): if answer=='yes': subheading_list.append(subheading) index_list.append(index) fig,axes = plt.subplots(len(index_list),3) for i in range (0,len(index_list)): axes[i,0].plot(index_list[i], seconddataset[subheading_list[i]]...
score: 2
downvote count: 0

pygame
tags question: http://stackoverflow.com/q/52691720
tags question: http://stackoverflow.com/q/52647466
tags question: http://stackoverflow.com/q/52666877
tags question: http://stackoverflow.com/q/52739619
tags question: http://stackoverflow.com/q/52689558
tags question: http://stackoverflow.com/q/52709642
tags question: http://stackoverflow.com/q/52730684
tags question: http://stackoverflow.com/q/52607405
tags question: http://stackoverflow.com/q/52600048
tags question: http://stackoverflow.com/q/52647626
tag name: pygame
tags question: http://stackoverflow.com/q/52713127
tags question: http://stackoverflow.com/q/52743872
tags question: http://stackoverflow.com/q/52669368
tags question: http://stackoverflow.com/q/52726889
tags question: http://stackoverflow.com/q/52648522
tags question: http://stackoverflow.com/q/52658247
tags question: http://stackoverflow.com/q/52637875
tags question: http://stackoverflow.com/q/52675636
tags question: http://stackoverflow.com/q/52622220
tags question: http://stackoverflow.com/q/52616695
tags question: http://stackoverflow.com/q/52684045
tags question: http://stackoverflow.com/q/52672529
tags question: http://stackoverflow.com/q/52673030
type: Tag

http://stackoverflow.com/comment/92207326
type: AnswerComment
has text: thanks but I am getting this "<generator object <genexpr> at 0x7fe874754aa0>"
type: Comment
comment on: http://stackoverflow.com/a/52636978
score: 0

http://stackoverflow.com/q/52599669
tagged with: aop
type: Question
upvote count: 1
tagged with: decorator
favorite count: 0
linked to: http://stackoverflow.com/q/157938
has title: Python hiding passwords in decorator
has body: I am building a project for deploying applications to servers using python scripts. I also use decorator to log inputs and outputs of functions. Since the logs will be available as Jenkins output, it is not an option to show passwords. I am looking for a way to annotate/tag parameters so that decorator does not show them as plain text. If this is not possible, I am looking for alternatives. I can make sure that I do not pass/return passwords in annotated functions, but considering future contributions from other developers I want to do this in a more easier to maintain way.
tagged with: python
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92134412

http://stackoverflow.com/q/52722817
answer count: 1
favorite count: 0
has title: Fetching release date of an episode using IMDBpy API in python
tagged with: imdb
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I want to fetch the release date of a episode e.g GOT S03E04 - 21 Apr. 2013 I have been able to get to the ID of the episode using this API but can't seem to find my way around to release date. I know that this API fetches release year so it must be fetching release date also somewhere. Can someone please help me.
type: Question
has answer: http://stackoverflow.com/a/52723084
accepted answer: http://stackoverflow.com/a/52723084
tagged with: imdbpy
upvote count: 1

http://stackoverflow.com/comment/92247696
type: QuestionComment
comment on: http://stackoverflow.com/q/52649213
has text: why not send as int array `print([ord(le) for le in "müller"]) #[109, 252, 108, 108, 101, 114]`
score: 0
type: Comment

class
tags question: http://stackoverflow.com/q/52699918
tags question: http://stackoverflow.com/q/52706200
tags question: http://stackoverflow.com/q/52679654
tags question: http://stackoverflow.com/q/52743305
tags question: http://stackoverflow.com/q/52598224
tags question: http://stackoverflow.com/q/52600173
tags question: http://stackoverflow.com/q/52658210
tags question: http://stackoverflow.com/q/52648720
tags question: http://stackoverflow.com/q/52706667
tags question: http://stackoverflow.com/q/52638187
tags question: http://stackoverflow.com/q/52677432
tags question: http://stackoverflow.com/q/52681456
tags question: http://stackoverflow.com/q/52625656
tags question: http://stackoverflow.com/q/52644466
tags question: http://stackoverflow.com/q/52682555
tags question: http://stackoverflow.com/q/52611754
tags question: http://stackoverflow.com/q/52685564
tags question: http://stackoverflow.com/q/52590791
tags question: http://stackoverflow.com/q/52695716
tags question: http://stackoverflow.com/q/52669613
tags question: http://stackoverflow.com/q/52679284
tags question: http://stackoverflow.com/q/52654734
tags question: http://stackoverflow.com/q/52618507
type: Tag
tags question: http://stackoverflow.com/q/52687918
tags question: http://stackoverflow.com/q/52671392
tags question: http://stackoverflow.com/q/52629288
tags question: http://stackoverflow.com/q/52652624
tags question: http://stackoverflow.com/q/52694555
tags question: http://stackoverflow.com/q/52654984
tag name: class
tags question: http://stackoverflow.com/q/52731009
tags question: http://stackoverflow.com/q/52744622
tags question: http://stackoverflow.com/q/52649186
tags question: http://stackoverflow.com/q/52620995
tags question: http://stackoverflow.com/q/52595510
tags question: http://stackoverflow.com/q/52629767
tags question: http://stackoverflow.com/q/52745859
tags question: http://stackoverflow.com/q/52618663
tags question: http://stackoverflow.com/q/52611553
tags question: http://stackoverflow.com/q/52665981
tags question: http://stackoverflow.com/q/52730728

http://stackoverflow.com/q/52722362
upvote count: 6
has answer: http://stackoverflow.com/a/63089522
has comment: http://stackoverflow.com/comment/92375928
has title: How to assign python requests sessions for single processes in multiprocessing pool?
score: 6
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/92370587
has comment: http://stackoverflow.com/comment/101068594
has body: Considering the following code example: import multiprocessing import requests session = requests.Session() data_to_be_processed = [...] def process(arg): # do stuff with arg and get url response = session.get(url) # process response and generate data... return data with multiprocessing.Pool() as pool: results = pool.map(process, data_to_be_processed) In example, Session is assigned as global variable, therefore after creating processes in Pool it will be copied into each subprocess. I am not sure whether the session is thread safe nor how pooling in session works, so I would like to assign separate session object for each process in pool. I am aware, that I could just use requests.get(url) instead of session.get(url), but I would like to work with session and I am also considering using requests-html (https://html.python-requests.org/). I am not very familiar with python's multiprocessing, so far I have used just pool, because it came to me as best solution to process data in parallel without having a critical section, so I am open for different solutions. Is there a way to do it clean and straightforward?
has comment: http://stackoverflow.com/comment/92391795
tagged with: session
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/92371657
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92375979
has comment: http://stackoverflow.com/comment/92370205
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/106076019
tagged with: python

http://stackoverflow.com/a/52682681
upvote count: 3
has comment: http://stackoverflow.com/comment/92293611
downvote count: 0
has comment: http://stackoverflow.com/comment/92293553
has body: yes, you're very close: def myfunc(cols,fun): return df.groupby('col_3')[cols].transform(lambda x: fun(x)) Or: def myfunc(cols,fun): return df.groupby('col_3')[cols].transform(fun)
score: 3
type: Answer
answers question: http://stackoverflow.com/q/52682614

http://stackoverflow.com/comment/92245283
comment on: http://stackoverflow.com/q/52657272
has text: you cant bro. this is a dataframe. what you can do, is to set up all the values behind the first row as `NaNs`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/133395093
has text: The equal sign is also limited to single value arguments (i.e. can't do this with nargs arguments).
type: AnswerComment
comment on: http://stackoverflow.com/a/52636344
score: 0
type: Comment

http://stackoverflow.com/a/52609047
has body: As the error message says, you should pass binary data, not strings. Instead of csv.write(my_text) write csv.write(my_text.encode()) to convert it to binary.
upvote count: 2
answers question: http://stackoverflow.com/q/52608995
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/92209500
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52638337
type: Comment
has text: I tried this, it doesn't work.

http://stackoverflow.com/a/52613154
score: 16
answers question: http://stackoverflow.com/q/52612812
type: Answer
upvote count: 16
has body: It's not possible with plt.arrow. I guess the reason plt.arrow still exists is purely for backwards compatibility. Arrows are better produced by matplotlib.patches.FancyArrowPatch. The easiest way to get such FancyArrowPatch in your plot is via plt.annotate. import matplotlib.pyplot as plt prop = dict(arrowstyle="-|&gt;,head_width=0.4,head_length=0.8", shrinkA=0,shrinkB=0) plt.annotate("", xy=(.5,.5), xytext=(0,0), arrowprops=prop) plt.annotate("", xy=(.2,.5), xytext=(0,0), arrowprops=prop) plt.annotate("", xy=(.0,.5), xytext=(0,0), arrowprops=prop) plt.axis((-1, 1, -1 ,1)) plt.show() Arrows are currently a bit underdocumented, but there is still a plan to write up some complete tutorial or guide.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52612812

http://stackoverflow.com/q/52673080
has comment: http://stackoverflow.com/comment/92275879
downvote count: 3
has comment: http://stackoverflow.com/comment/92276127
answer count: 1
has comment: http://stackoverflow.com/comment/92276018
has title: How to check if a certain field across list of dicts are equal?
has body: Given a list of dicts that all contain some common key (a in the below example), how can I Pythonically check whether the value associated with such a key is the same in all of them? Example: Check if a is the same across all dicts. dicts = [{'a': 1, 'b':2}, {'a': 1, 'c':2}, {'a': 1, 'd':2}, {'a': 1, 'e':2}] last_key = None for d in dicts: if last_key is None: last_key = d['a'] else: if last_key != d['a']: return False return True
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92275958
has comment: http://stackoverflow.com/comment/92276124
has answer: http://stackoverflow.com/a/52673188
has comment: http://stackoverflow.com/comment/92276130
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
tagged with: python
score: -1

http://stackoverflow.com/q/52681191
tagged with: python
type: AnsweredQuestion
downvote count: 0
duplicate of: http://stackoverflow.com/q/25471878
type: Question
score: 5
has answer: http://stackoverflow.com/a/52681223
accepted answer: http://stackoverflow.com/a/52681223
has title: Double elements in Python Numpy Array
linked to: http://stackoverflow.com/q/25471878
answer count: 1
favorite count: 0
upvote count: 5
tagged with: multidimensional-array
has body: I'm trying to copy every element into a 2d array in Python such that it doubles the size of the array and adds the element directly after the element that it intends to copy. For example: [[1,2,3], [4,5,6], [7,8,9]] becomes [[1,1,2,2,3,3], [4,4,5,5,6,6], [7,7,8,8,9,9]] Can anyone help with this problem? Thanks!

http://stackoverflow.com/a/52803482
has body: I was able to bring the epoch time down to 1.1 s by following the optimization recommended at Tips to Improve Performance for Popular Deep Learning Frameworks on CPUs Here is the code: import os N_CORES = int(os.cpu_count()/2) os.environ["OMP_NUM_THREADS"] = str(N_CORES) os.environ["KMP_BLOCKTIME"] = "30" os.environ["KMP_SETTINGS"] = "1" os.environ["KMP_AFFINITY"] = "granularity=fine,verbose,compact,1,0" config_sess = tf.ConfigProto(intra_op_parallelism_threads=N_CORES, inter_op_parallelism_threads=2, allow_soft_placement=True, device_count = {'CPU': N_CORES}) with tf.Session(config=config_sess) as sess:
type: Answer
answers question: http://stackoverflow.com/q/52734397
score: 0

http://stackoverflow.com/comment/92278300
type: Comment
type: QuestionComment
score: 1
has text: What if one of the dicts has two keys with the same value?
comment on: http://stackoverflow.com/q/52674378

http://stackoverflow.com/comment/92359791
comment on: http://stackoverflow.com/q/52717004
has text: You have to use `Qt::QueuedConnection`, here it does not matter if it is `QThread` or not, since the end `QThread` is just a thread handle. Another option is to use `QMetaObject`, that is, create an `@pyqtSlot` that performs the operation you want, for this you must pass the view to the GUI (pass it but not use any function) and then use `QMetaObject::InvokedMethod(...)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92158408
type: QuestionComment
score: 0
has text: I've already posted one for your kind consideration @sir Andersson and t.m.adam. Just I need to know whether what I did is right. Inspired by [this blog post](http://blog.adnansiddiqi.me/how-to-speed-up-your-python-web-scraper-by-using-multiprocessing/?utm_source=medium_post_multiprocessing&utm_campaign=c_post_multiprocessing&utm_medium=medium_site). Thanks.
comment on: http://stackoverflow.com/q/52593742
type: Comment

http://stackoverflow.com/a/52745681
answers question: http://stackoverflow.com/q/52745589
score: 0
type: Answer
has body: import string def problem(number): if number &gt; len(string.ascii_uppercase): return None return string.ascii_uppercase[number]

http://stackoverflow.com/a/55514080
upvote count: 1
answers question: http://stackoverflow.com/q/52602091
score: 1
has body: There is a known bug with importing external libraries more than once with the Python ReaScript API. It also happens with numpy (and thus all libraries that depend on it). I've been working on a way to solve it by writing the reapy library. It allows to call functions of the ReaScript API from outside REAPER (e.g. in a usual terminal), and thus to import safely any third-party libraries (including PyQt4). You can check the documentation or the repository if you're interested!
downvote count: 0
type: Answer

http://stackoverflow.com/q/52635661
upvote count: 1
type: Question
score: 1
tagged with: wtforms
tagged with: sqlalchemy
has title: Dynamically Populate WTForm SelectField with sqlAlchemy query
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92205505
tagged with: flask
favorite count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/92204752
tagged with: python
has answer: http://stackoverflow.com/a/52673608
accepted answer: http://stackoverflow.com/a/52673608
type: AnsweredQuestion
has body: I'm trying to dynamically populate options in a drop down with data from a column in my postgreSQL database. When I try to load my form I get: TypeError: 'NoneType' object is not iterable. Any help will be greatly appreciated. File "/usr/lib/python2.7/site-packages/wtforms/widgets/core.py", line 323, in __call__ for val, label, selected in field.iter_choices(): File "/usr/lib/python2.7/site-packages/wtforms/fields/core.py", line 454, in iter_choices for value, label in self.choices: TypeError: 'NoneType' object is not iterable Model.py class ReqCriterion(Base): __tablename__ = 'req_criteria' criteria_id = Column(Integer, primary_key=True, server_default=text("nextval('req_criteria_criteria_id_seq'::regclass)")) req_id = Column(Integer, nullable=False) req_name = Column(Text) coi_id = Column(Integer, nullable=False) coi_name = Column(Text, nullable=False) criteria = Column(Text) def __init__(self, criteria, req_name, coi_id, coi_name, req_id): self.criteria = criteria self.req_id = req_id self.req_name = req_name self.coi_id = coi_id self.coi_name = coi_name forms.py class NewProjForm(Form): pj_name = StringField('Project Name', validators=[InputRequired(), Length(min=1, max=1000)]) pj_desc = TextAreaField('Project Description', validators=[InputRequired(), Length(min=1, max=3000)]) coi_name = SelectField('COI:', validators=[InputRequired()]) pj_poc_first = StringField('POC First Name', validators=[InputRequired(), Length(min=1, max=500)]) pj_poc_last = StringField('POC Last Name', validators=[InputRequired(), Length(min=1, max=500)]) app.py @app.route('/addProjForm', methods=['GET','POST']) def addProjForm(): newProj = NewProjForm(request.form) newProj.coi_name.choices = db.session.query(ReqCriterion).filter(coi_name) if request.method == 'POST' and newProj.validate(): addProj = Project(request.form['pj_name'], request.form['pj_desc'], request.form['coi_name'], request.form['pj_poc_first'], request.form['pj_poc_last']) db.session.add(addProj) db.session.commit() ret…

http://stackoverflow.com/a/52655019
type: AcceptedAnswer
downvote count: 0
has body: You are not calling your methods. You are shown the representation of the method objects themselves, not their results. Add () calls: def __str__(self): return ( '&lt;' + self.get_recipient() + ', ' + self.get_priority_category() + ', ' + str(self.get_cost()) + ', ' + str(self.get_weight()) + '&gt;') I dropped redundant str() calls (get_recipient() and get_priority_category() are already producing strings), and added (...) around the expression so it can be broken up across multiple lines for readability. Not that you need most of those methods, because you could just access the underlying attributes directly: def __str__(self): return ( '&lt;' + self.name + ', ' + self.get_priority_category() + ', ' + str(self.cost) + ', ' + str(self.weight) + '&gt;') In Python, you generally don't use accessor functions, not when accessing the attribute directly would suffice. This differs from languages such as Java, where it is hard to replace attribute access with an accessor function after the fact. In Python, it is trivial to switch to using a property later on so there is no cost with just using attributes directly. The above can be simplified by using string formatting; for Python 3.6 and up, use an f-string: def __str__(self): return f'&lt;{self.name}, {self.get_priority_category()}, {self.cost}, {self.weight}&gt;' otherwise use str.format() to do the same: def __str__(self): return '&lt;{}, {}, {}, {}&gt;'.format( self.name, self.get_priority_category(), self.cost, self.weight) When using string formatting, no str() calls are necessary and you save your self a lot of typing out ' and + characters.
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52654984
answers question: http://stackoverflow.com/q/52654984

http://stackoverflow.com/comment/92371232
score: 0
has text: Before trying to make a car look like a bike I wanted to make sure that only a car can be used for this job. And I've seen bad advice before especially concerning GUIs where it says to use this and that and customize x and y to latter realize that there was a built in option to do what I wanted all along. If the answer is you can't do that with a Message widget that is fine too but I would still like to know
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52722821

http://stackoverflow.com/a/52637990
has comment: http://stackoverflow.com/comment/92240838
upvote count: 2
has comment: http://stackoverflow.com/comment/92219707
accepted answer of: http://stackoverflow.com/q/52624756
has comment: http://stackoverflow.com/comment/92278788
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92240852
has comment: http://stackoverflow.com/comment/92250605
has comment: http://stackoverflow.com/comment/92267904
type: Answer
answers question: http://stackoverflow.com/q/52624756
has comment: http://stackoverflow.com/comment/92220169
score: 2
has body: Florian's answer is almost certainly what's happening, which is the gzip file you are only partially decompressing must have multiple members. To decompress the next member, you can simply get the unused_data from the decompressobj object and start another decompression. Repeat until all of the input is used. This answer shows an example of processing a gzip file with multiple members in python. It sounds like what you should be using for the wbits parameter is 31, not 32. 31 expects a gzip wrapper as opposed to a zlib wrapper. Not specifying wbits results in the decompressor expecting a zlib wrapper, which is why it doesn't work on your gzip streams.

http://stackoverflow.com/a/52630586
accepted answer of: http://stackoverflow.com/q/52630059
has comment: http://stackoverflow.com/comment/92213904
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52630059
has body: d1={ 'test': 'baum', 'alter': 0, 'voegel': ['amsel'] } d2={ 'test': 'grosserbaum', 'alter': 3, 'voegel': ['meise'] } Lets try with your expected output {d1:d2} #TypeError: unhashable type: 'dict' The error is raised because the dict type cannot be hashed. similar to the list type as it does not comes with a hash function. Therefore, moral of the story is in order for an object to be hashable, it must be immutable types like string, integer or tuple. In case you are just looking to iterate over the dicts [d1,d2] # convert into a list OR (d1,d2)# convert into a tuple or create a new list with immutable keys {'d1':d1,'d2':d2} For further reference https://www.asmeurer.com/blog/posts/what-happens-when-you-mess-with-hashing-in-python/

http://stackoverflow.com/q/52723755
tagged with: python
has answer: http://stackoverflow.com/a/52724002
type: Question
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: dataframe
has title: split a pyspark.sql dataFrame into multiple tables based on one column
score: 0
answer count: 1
has body: Given a pyspark.sql.dataframe.DataFrame x: name day earnings revenue Oliver 1 100 44 Oliver 2 200 69 John 1 144 11 John 2 415 54 John 3 33 10 John 4 82 82 Is it possible to split the table into two tables based on the name column (that acts as an index), and nest the two tables under the same object (not sure about the exact terms to use). So in the example above, tables[0] will be: name day earnings revenue Oliver 1 100 44 Oliver 2 200 69 and tables[1] will be: name day earnings revenue John 1 144 11 John 2 415 54 John 3 33 10 John 4 82 82 Note that that the number of rows in each 'sub-table' may vary. I have tried the following: dict(tuple(x.groupby('name'))) which works great with a Pandas dataframe, but when I try to do the same on a pyspark.sql dataframe I get the error : TypeError: 'GroupedData' object is not iterable Any help would be appreciated. Cheers,
type: UnansweredQuestion

http://stackoverflow.com/q/52627668
score: 0
has comment: http://stackoverflow.com/comment/92190673
tagged with: pandas
tagged with: python
linked to: http://stackoverflow.com/q/19699367
has title: Error loading large csv file "'utf-8' codec can not decrypt" in python
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/19699367
linked to: http://stackoverflow.com/q/50185528
upvote count: 1
linked to: http://stackoverflow.com/q/46000191
downvote count: 1
has comment: http://stackoverflow.com/comment/92189991
has comment: http://stackoverflow.com/comment/92190933
has answer: http://stackoverflow.com/a/52627923
has comment: http://stackoverflow.com/comment/92190576
has body: I have 1 GB csv file and I can not read that log file and give same error in both python and pandas code in my csv file, it is not a value of more than one column because there is only a single column value and All of my CSV values is number with open("/Users/kiya/sep_sent.csv", encoding='utf-8') as f: for i in f: print(i.strip()) another method: with open("/Users/kiya/sep_sent.csv",encoding='cp1252') as f: for i in f: print(i.strip()) Traceback (most recent call last): File "/Users/kiya/test8.py", line 5, in &lt;module&gt; for i in f: File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 159: character maps to &lt;undefined&gt; pandas code: import pandas as pd df = pd.read_csv("/Users/kiya/sep_sent.csv", encoding="utf-8") print(df) my csv value like: 0 0 0 .... 5294751024 error: 0 0 0 0 0 Traceback (most recent call last): File "/Users/kiya//test8.py", line 4, in &lt;module&gt; for i in f: File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 52: invalid start byte
has comment: http://stackoverflow.com/comment/92191132
has comment: http://stackoverflow.com/comment/92190835
type: Question
has comment: http://stackoverflow.com/comment/92191714
answer count: 2
has comment: http://stackoverflow.com/comment/92190293
has comment: http://stackoverflow.com/comment/92190354
has answer: http://stackoverflow.com/a/52627799
favorite count: 0

http://stackoverflow.com/a/52678102
score: 0
answers question: http://stackoverflow.com/q/52672166
type: Answer
has body: Here is a shot in the dark but the following line: res_all = modified_mlr.do_mlr(df_x,df_y,soil_type=st,max_namber=max_number) looks like it has a typo max_namber=max_number. This would cause all the processes to fail with hidden exceptions.

http://stackoverflow.com/a/52729262
score: 0
accepted answer of: http://stackoverflow.com/q/52728459
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52728459
has body: Whilst not a direct answer may be a workaround.. (the below allows you to write to steve but it saves into _steve formatted to lowercase) class Bob(Base, ...): __tablename__ = "Alice" _steve = Column(String, nullable=False) @property . # hybrid_property for search queries? def steve(self): return self._steve @steve.setter def steve(self, value): self._steve = value.lower() You can query based on lowercase: Bob.query.filter(Bob._steve == 'SomE TexT'.lower()) This might also work depending on some other properties I think explained in SQLalchemy docs as hybrid_properties: Bob.query.filter(Bob.steve == 'SomE TexT'.lower())

http://stackoverflow.com/a/52725343
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52725195
type: Answer
has body: Using a list allows you to have the ages keep a normal order and access the values by their index. Since all your keys only increase by one, then using a list would be a more appropriate data structure. You can just store your range() result into a list variable. Then to access the correct year, you can get the age like I did in the GetAge function passing in the year and list. def DogYears(): small_dog = range(15, 80, 4) def GetAge(year, dog_list): index = year - 1 if index &gt;= 0 and index &lt; len(dog_list): return dog_list[index]
upvote count: 1

http://stackoverflow.com/comment/92144340
comment on: http://stackoverflow.com/q/52603997
has text: It would help if you included your code but this kind of error might occur when you are running out of space in your partition.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92294369
has text: @NathanMndz You can give it an up vote as well. If you like
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52674229

http://stackoverflow.com/q/52638294
downvote count: 1
has comment: http://stackoverflow.com/comment/92224745
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92209621
answer count: 3
has answer: http://stackoverflow.com/a/52638393
has comment: http://stackoverflow.com/comment/92209495
favorite count: 0
has answer: http://stackoverflow.com/a/52638377
type: UnansweredQuestion
has title: Need to associate two lists in Python
has comment: http://stackoverflow.com/comment/92209557
has body: I am working on an assignment in Python and need to associate rainfall amounts with each month. I need to print the low and high months for rainfall, but the way my code is currently written I can only print the actual amount, but not the month that corresponds with the amount. I think I would associate the two under the enter_rainfall function, but am not sure how to go about associating the two. Any advice is appreciated. def main(): months_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] rain = enter_rainfall() average = avg_rainfall(rain) lowhigh = low_High(rain) print(format(average, '.2f')) def enter_rainfall(): rain_fall = [] months = 12 for months_list in range(months): rain_amount = float(input('Please enter the amount of rain:',)) rain_fall.append(rain_amount) return(rain_fall) def avg_rainfall(rain): total = 0 for value in rain: total += value average = total / len(rain) return(average) def low_High(rain, months_list): low = min(rain) month = months_list[rain.index(low)] print(month) high = max(rain) print(high) main()
tagged with: python
has answer: http://stackoverflow.com/a/52638445
upvote count: 1

http://stackoverflow.com/a/52748051
answers question: http://stackoverflow.com/q/52734397
score: 0
has comment: http://stackoverflow.com/comment/92454872
type: Answer
has comment: http://stackoverflow.com/comment/92465775
has body: Colaboratory is optimized for Tensorflow, while a GCE instance is a regular machine. "When you create a new notebook on colab.research.google.com, TensorFlow is already pre-installed and optimized for the hardware being used." This is likely why you are seeing a performance difference between the two.
has comment: http://stackoverflow.com/comment/92455121
has comment: http://stackoverflow.com/comment/92627748
has comment: http://stackoverflow.com/comment/92427643

http://stackoverflow.com/q/52614977
has body: My question is closely related to Pandas Merge - How to avoid duplicating columns but not identical. I want to concatenate the columns that are different in three dataframes. The dataframes have a column id, and some columns that are identical: Ex. df1 id place name qty unit A 1 NY Tom 2 10 a 2 TK Ron 3 15 a 3 Lon Don 5 90 a 4 Hk Sam 4 49 a df2 id place name qty unit B 1 NY Tom 2 10 b 2 TK Ron 3 15 b 3 Lon Don 5 90 b 4 Hk Sam 4 49 b df3 id place name qty unit C D 1 NY Tom 2 10 c d 2 TK Ron 3 15 c d 3 Lon Don 5 90 c d 4 Hk Sam 4 49 c d Result: id place name qty unit A B C D 1 NY Tom 2 10 a b c d 2 TK Ron 3 15 a b c d 3 Lon Don 5 90 a b c d 4 Hk Sam 4 49 a b c d The columns place, name, qty, and unit will always be part of the three dataframes, the names of columns that are different could vary (A,B,C,D in my example). The three dataframes have the same number of rows. I have tried: cols_to_use = df1.columns - df2.columns dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer') The problem is that I get more rows than expected and columns renamed in the resulting dataframe (when using concat).
upvote count: 3
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/52615147
tagged with: concatenation
has answer: http://stackoverflow.com/a/52615187
has answer: http://stackoverflow.com/a/52615053
downvote count: 0
has answer: http://stackoverflow.com/a/52615051
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52615051
tagged with: python
tagged with: merge
accepted answer: http://stackoverflow.com/a/52615147
answer count: 4
favorite count: 0
has title: Concatenate distinct columns in two dataframes using pandas (and append similar columns)
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/19125091

http://stackoverflow.com/comment/92295496
type: AnswerComment
comment on: http://stackoverflow.com/a/52683704
type: Comment
has text: @raggot Do you understand that they are the `*args`, and `**kwargs`? Do you know the difference?
score: 0

http://stackoverflow.com/comment/92411633
type: Comment
has text: @rahlf23, nope it doesn't..I'm simply trying to show him how to DIY, it's more understandable but if pd's dfs is what he is looking for then your solution and Mohit's solutions above should suffice
type: AnswerComment
comment on: http://stackoverflow.com/a/52743187
score: 0

http://stackoverflow.com/comment/92265344
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52649179
has text: Thank you very much! Everything is completely clear to me now. It sounds confusing indeed, but Anaconda is just the python+packages installation, whereas conda is the environment managemant system (like venv).

http://stackoverflow.com/q/52618980
tagged with: qscrollarea
accepted answer: http://stackoverflow.com/a/52619211
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52619211
type: Question
has body: I tried to make some simple local chatting app for practice. I make a button to send a message every time i push the button the message displayed but the scrollarea become more narrow and not expanded the scrollarea. Am I missing something or added something i shouldn't in my code? how can i fix this? Here is my code: from PyQt4.QtCore import * from PyQt4.QtGui import * class Bubble(QLabel): def __init__(self,text): super(Bubble,self).__init__(text) self.setContentsMargins(5,5,5,5) def paintEvent(self, e): p = QPainter(self) p.setRenderHint(QPainter.Antialiasing,True) p.drawRoundedRect(0,0,self.width()-1,self.height()-1,5,5) super(Bubble,self).paintEvent(e) class MyWidget(QWidget): def __init__(self,text,left=True): super(MyWidget,self).__init__() hbox = QHBoxLayout() label = Bubble(text) if not left: hbox.addSpacerItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Preferred)) hbox.addWidget(label) if left: hbox.addSpacerItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Preferred)) hbox.setContentsMargins(0,0,0,0) self.setLayout(hbox) self.setContentsMargins(0,0,0,0) class Chatting(QWidget): def __init__(self, parent=None): super(Chatting, self).__init__(parent) self.vbox = QVBoxLayout() for _ in range(20): self.vbox.addWidget(MyWidget("Left side")) widget = QWidget() widget.setLayout(self.vbox) scroll = QScrollArea() scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setWidgetResizable(False) scroll.setWidget(widget) #Scroll Area Layer add vLayout = QVBoxLayout(self) vLayout.addWidget(scroll) send = QPushButton('') send.setIcon(QIcon('images/send.png')) send.setStyleSheet("background-color:#d00001; width: 44px") send.setIconSize(QSize(84,20)) send.clicked.connect(self.send_messages) vLayout.addWidget(send) self.setLayout(vLayout) def send_messages(self): self.vbox.addWidget(MyWidget('testing'))
tagged with: pyqt4
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
has title: Scrollarea can't expand (scroll) when new widget added
tagged with: python

http://stackoverflow.com/q/52703838
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92334486
possible better answer: http://stackoverflow.com/a/52703971
has body: import subprocess import sys video_link, threads = sys.argv[1], sys.argv[2] subprocess.call([ "youtube-dl", video_link, "--external-downloader", "aria2c", "--external-downloader-args", "-x"+threads ]) Whenever I run the code the following error pops up. Help me please _link, threads = sys.argv[1], sys.argv[2] IndexError: list index out of range
has answer: http://stackoverflow.com/a/52704373
type: Question
duplicate of: http://stackoverflow.com/q/4117530
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52703971
has comment: http://stackoverflow.com/comment/92334341
has comment: http://stackoverflow.com/comment/92334441
tagged with: python-3.x
linked to: http://stackoverflow.com/q/15121717
has title: IndexError: list index out of range in PyCharm
accepted answer: http://stackoverflow.com/a/52704373
tagged with: python

http://stackoverflow.com/comment/92376319
comment on: http://stackoverflow.com/q/52725477
type: QuestionComment
type: Comment
score: 3
has text: To be fair, "or" is a difficult thing to google about. Here's the relevant section of the docs: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not

http://stackoverflow.com/comment/92115420
has text: Possible duplicate of [Read .mat files in Python](https://stackoverflow.com/questions/874461/read-mat-files-in-python)
comment on: http://stackoverflow.com/q/52590331
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52680763
has comment: http://stackoverflow.com/comment/92290992
answers question: http://stackoverflow.com/q/52680619
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92291352
has body: We could use itertools.groupby here and by creating a list that holds dictionaries of each line from itertools import groupby with open('text.txt') as f: content = [line.strip('\n ') for line in f] content = [i.split(',') for i in content] lista = [] for i in content: lista.append(dict([j.split('=') for j in i])) total_eggs= sum([int(k) for k, g in groupby(lista, key=lambda x: x['eggs'])]) print(lista) # [{'eggs': '2', ' bread': '1', ' milk': '4'}, {'eggs': '5', ' bread': '2', ' milk': '2'}, {'eggs': '1', ' bread': '3', ' milk': '3'}] print(total_eggs) # 8 Another method would be to use defaultdict here to setup some dictionaries that will store the information from the text file in a organized fashion where you can access it and manipulate easier down the road from collections import defaultdict with open('text.txt') as f: content = [line.strip('\n ') for line in f] dd = defaultdict() content = [i.split(',') for i in content] for i, v in enumerate(content): dd[i] = dict([j.split('=') for j in v]) print(dd) # {0: {'eggs': '2', ' bread': '1', ' milk': '4'}, 1: {'eggs': '5', ' bread': '2', ' milk': '2'}, 2: {'eggs': '1', ' bread': '3', ' milk': '3'}}) print(sum([int(dd[k]['eggs']) for k in dd])) # 8 Working method with keys holding no value: with open('text.txt') as f: content = [line.strip('\n ') for line in f] content = [i.split(',') for i in content] lista = [] for i in content: for j in i: if len(j.split('=')) &gt; 1: lista.append({j.split('=')[0]: j.split('=')[1]}) else: lista.append({j: 0}) total_eggs = sum([int(v) for i in lista for k, v in i.items() if 'eggs' in k])
has comment: http://stackoverflow.com/comment/92290923
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52680619
downvote count: 0
has comment: http://stackoverflow.com/comment/92291051

http://stackoverflow.com/q/52698202
has comment: http://stackoverflow.com/comment/92329069
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/92328178
has comment: http://stackoverflow.com/comment/92327084
has comment: http://stackoverflow.com/comment/92332661
has comment: http://stackoverflow.com/comment/92332547
has comment: http://stackoverflow.com/comment/92332781
type: Question
tagged with: numpy
has title: Error preprocessing the input data when using Tensorflow Dataset API
downvote count: 0
tagged with: tfrecord
has comment: http://stackoverflow.com/comment/92356510
tagged with: floating-accuracy
favorite count: 0
has body: I have images of [64,512,5] stored in *.npy files which I convert into *.tfrecords files. I have verified that the reading of said records corresponds correctly with what is present in the *.npy files. However, when I perform some operation on the parser, like adding 1 to each pixel of the image, the result is not the expected one. The result should be 65*512*5 = 163840 but it is 163839.99980013957 (not always the same) I have tried to perform different operations like tf.subtract, but the results are the same. Could someone tell me what is wrong? import re import ast import sys, select import random as rn from glob import glob from tqdm import tqdm from datetime import datetime from configparser import SafeConfigParser import numpy as np import numpy.ma as ma import scipy.misc import os.path from os import mkdir, stat from os.path import exists, dirname, abspath from os.path import join as dir_join import tensorflow as tf ''' File hierarchy ''' _code_dir = dirname(abspath(__file__)) _python_dir = dirname(_code_dir) _model_dir = dirname(_python_dir) _project_dir = dirname(_model_dir) _ml_dir = dirname(_project_dir) _srv_dir = dirname(_ml_dir) _root_datasets_dir = dir_join(_srv_dir,'machine_learning','data_sets/ssd_prepared') _config_dir = dir_join(_python_dir, 'config') '''Data sets directories ''' THIS_DATA_SET_DIR = 'Sph_50m' #WARNING: Global variable also used in helper.py _data_dir = dir_join(_root_datasets_dir, THIS_DATA_SET_DIR) _data_set_dir = dir_join(_data_dir,'ImageSet') _data_npy_dir = dir_join(_data_dir,'data') _data_tfRecord_dir = dir_join(_data_dir,'tfRecord') ''' Configuration parser ''' cfg_parser = SafeConfigParser() cfg_parser.read(dir_join(_config_dir,'cfg_model.ini')) ''' Private variables ''' _batch_size = cfg_parser.getint(section='train', option='batch_size') _max_epoch = cfg_parser.getint(section='train', option='max_epoch') _standarize = cfg_parser.getboolean(section='train', option='standarize_input') _input_shape = ast.literal_eval(cfg_par…
tagged with: python

http://stackoverflow.com/q/52704827
linked to: http://stackoverflow.com/q/50239281
tagged with: python-3.x
type: Question
score: 0
tagged with: pickle
has title: Python 3 can not pickle dump
has comment: http://stackoverflow.com/comment/92336480
has body: I have been working on a project where I store some values in a tree data type.(I have used liblarch liblary's tree) and now I am trying to store these data in locally using Python pickle. However now I get this error and can not find a solution about the problem. Can anyone suggest anything about this? Here is the error: TypeError: can't pickle _thread.lock objects
has comment: http://stackoverflow.com/comment/92336242
has comment: http://stackoverflow.com/comment/92411568
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52653203
has comment: http://stackoverflow.com/comment/92238141
has comment: http://stackoverflow.com/comment/92237938
has body: I'm trying to send console commands from one machine to another using Python sockets. I want the server to send back the results of the command to the client. If the client types "ls" I want the server to send back the results of running that command. Instead of the expected result, the server just says "action completed: ls". How can I fix this so the server will run the expect commands and return the result? Server: import socket from subprocess import call def main(): host = '127.0.0.1' port = 5000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(1) c, addr = s.accept() print('Connection established: ' + str(addr)) while True: try: data = c.recv(1024).decode('utf-8') print('sending data: ' + data) c.send(data.encode('utf-8')) if data == 'q': break except NameError: error = 'Command does not exist' c.send(error.encode('utf-8')) continue except SyntaxError: error = 'Command does not exist' c.send(error.encode('utf-8')) continue c.close() Client: import socket from subprocess import call def main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.connect((host, port)) message = str(input('&gt; ')) while message != 'q': try: s.send(message.encode('utf-8')) data = s.recv(1024).decode('utf-8') print('Action completed: %s' % data) message = str(input('&gt; ')) except NameError: print("Command not recognized.") continue except SyntaxError: print("Command not recognized") continue
has comment: http://stackoverflow.com/comment/92238986
type: Question
has comment: http://stackoverflow.com/comment/92241790
has title: Python sockets and commands
answer count: 1
has comment: http://stackoverflow.com/comment/92238094
has answer: http://stackoverflow.com/a/64536750
score: 0
tagged with: sockets
tagged with: python
tagged with: command
has comment: http://stackoverflow.com/comment/92239105
has comment: http://stackoverflow.com/comment/92239563
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92238063
has comment: http://stackoverflow.com/comment/92238169
has comment: http://stackoverflow.com/comment/92237958

http://stackoverflow.com/a/52612926
has comment: http://stackoverflow.com/comment/92160758
type: Answer
has comment: http://stackoverflow.com/comment/92160456
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92160817
has body: I assume you want to create a figure, though your question is quite vague...but I have a few minutes to kill while my code runs. Anyway, it seems you MIGHT be having difficulty plotting. import numpy as np import pylab as pl x = np.arange(10) y = x * np.pi # you can calculate a line of best fit (lobf) using numpy's polyfit function lobf1 = np.polyfit(x, y, 1) # first degree polynomial lobf2 = np.polyfit(x, y, 2) # second degree polynomial lobf3 = np.polyfit(x, y, 3) # third degree polynomial # you can now use the lines of best fit to calculate the # value anywhere within the domain using numpy's polyval function # FIRST, create a figure and a plotting axis within the fig fig = pl.figure(figsize=(3.25, 2.5)) ax0 = fig.add_subplot(111) # now use polyval to calculate your y-values at every x x = np.arange(0, 20, 0.1) ax0.plot(x, np.polyval(lobf1, x), 'k') ax0.plot(x, np.polyval(lobf2, x), 'b') ax0.plot(x, np.polyval(lobf3, x), 'r') # add a legend for niceness ax0.legend(('Degree 1', 'Degree 2', 'Degree 3'), fontsize=8, loc=2) # you can label the axes whatever you like ax0.set_ylabel('My y-label', fontsize=8) ax0.set_xlabel('My x-label', fontsize=8) # you can show the figure on your screen fig.show() # and you can save the figure to your computer in different formats # specifying bbox_inches='tight' helps eliminate unnecessary whitespace around # the axis when saving...it just looks better this way. pl.savefig('figName.png', dpi=500, bbox_inches='tight') pl.savefig('figName.pdf', bbox_inches='tight') # don't forget to close the figure pl.close('all')
has comment: http://stackoverflow.com/comment/92160320
has comment: http://stackoverflow.com/comment/92160427
answers question: http://stackoverflow.com/q/52611997
downvote count: 0

http://stackoverflow.com/comment/92133440
type: QuestionComment
has text: @coldspeed , yes, this will be a good illustration of problem solutions! I can do that, but tomorrow i think. Its night right now in my country, so i will go to sleep ;)
comment on: http://stackoverflow.com/q/52599040
score: 0
type: Comment

http://stackoverflow.com/a/52626792
upvote count: 3
answers question: http://stackoverflow.com/q/52626655
has comment: http://stackoverflow.com/comment/108159928
score: 3
has comment: http://stackoverflow.com/comment/92844356
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52626655
type: Answer
has body: You can use a comprehension with itertools.chain and zip: from itertools import chain keys, values = map(chain.from_iterable, zip(*((k*len(v), v) for k, v in d.items()))) df = pd.DataFrame({'letter': list(keys), 'value': list(values)}) print(df) letter value 0 a 1 1 a 2 2 a 3 3 b 3 4 b 4 This can be rewritten in a more readable fashion: zipper = zip(*((k*len(v), v) for k, v in d.items())) values = map(list, map(chain.from_iterable, zipper)) df = pd.DataFrame(list(values), columns=['letter', 'value'])
has comment: http://stackoverflow.com/comment/92845720

http://stackoverflow.com/comment/92331465
type: QuestionComment
has text: Thanks a lot @IljaEverilä i solve my problem
score: 0
comment on: http://stackoverflow.com/q/52701303
type: Comment

http://stackoverflow.com/comment/92407722
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52735449
has text: Useless answers regarding my issue, as you can see by the answer at my question neither of the two posts you tagged contain it.

http://stackoverflow.com/q/52590878
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
has body: I'm trying to create a batch file to execute python scripts in different directories, something like that: C:\Test |---Test1\example.py |---Test2\example.py |---Test3\example.py |--run.bat I have multiple folders inside Test, 'Test1', 'Test2' and 'Test3', I need to run them simultaneously with different command prompts, but i'dont know how to do that, I got something like that: @echo off set back=%cd% for /d %%i in (C:\Test\*) do ( start cd "%%i" python example.py pause cd %back% ) But it only runs a script and goes back to the home directory, so I noticed, I believe it is running for only the first directory, any suggestions for this problem? Thanks!
has answer: http://stackoverflow.com/a/52591391
answer count: 2
has comment: http://stackoverflow.com/comment/92120316
downvote count: 0
has title: Batch File to acess a directory and execute a python script
possible better answer: http://stackoverflow.com/a/52590937
favorite count: 0
has answer: http://stackoverflow.com/a/52590937
tagged with: batch-file
tagged with: windows
tagged with: python
accepted answer: http://stackoverflow.com/a/52591391
has comment: http://stackoverflow.com/comment/92120477

http://stackoverflow.com/comment/92190851
has text: I added it at the very bottom
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52627739

http://stackoverflow.com/a/52665820
answers question: http://stackoverflow.com/q/52665291
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/92270531
downvote count: 0
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/52665291
has body: There can be two or more parse trees for a sentence. Natural language is ambiguous. One sentence can convey different meanings. This is because a word can have two different meanings. Ambiguity can also occur when punctuations are missing. Take a look at this example.

http://stackoverflow.com/comment/92311247
score: 3
has text: Seems OK to me, 4 channels (RGB+alpha which is at 255 all the time). Did you check that `data.shape` gives you the sizes you expect (i.e. (height, width, 4))?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52692150

http://stackoverflow.com/q/52694786
has comment: http://stackoverflow.com/comment/92316188
answer count: 2
has body: I have an array of coordinates test that I would like to turn into a string format print(test) [[[-122.45939656328747, 37.796690447896445], [-122.45859061899071, 37.785810199890264], [-122.44198816647757, 37.786535549757346], [-122.43578239539256, 37.789920515803715], [-122.42828711343275, 37.77444638530603]]] the expected output is "-122.45939656328747, 37.796690447896445 | 122.45859061899071, 37.785810199890264 | -122.44198816647757, 37.786535549757346 | -122.43578239539256, 37.789920515803715 | -122.42828711343275, 37.77444638530603" The following code only removes the outer brackets, how would one remove the inner brackets and place a pipe ("|") in between the coordinate pairs using python? import re print(str(test).strip('[]')) test = re.sub('[[]]', '', test)
tagged with: python
has answer: http://stackoverflow.com/a/52694868
score: 0
possible better answer: http://stackoverflow.com/a/52694828
has answer: http://stackoverflow.com/a/52694828
tagged with: geojson
type: AnsweredQuestion
has title: Strip and format coordinate pairs
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/92316170
accepted answer: http://stackoverflow.com/a/52694868
type: Question

http://stackoverflow.com/comment/92279441
comment on: http://stackoverflow.com/a/52674389
type: AnswerComment
has text: When replicating someone else's code you should definitely link to it.
type: Comment
score: 0

http://stackoverflow.com/comment/92419858
score: 0
has text: You can also do it in a single awk script. Look up how to print to a file instead of standard outout in an awk manual.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52747087

http://stackoverflow.com/a/52715825
upvote count: 2
has body: The behavior you are seeing is kind of documented here Deprecations¶ ... Object array equality comparisons In the future object array comparisons both == and np.equal will not make use of identity checks anymore. For example: > a = np.array([np.array([1, 2, 3]), 1]) b = np.array([np.array([1, 2, 3]), 1]) a == b will consistently return False (and in the future an error) even if the array in a and b was the same object. The equality operator == will in the future raise errors like np.equal if broadcasting or element comparisons, etc. fails. Comparison with arr == None will in the future do an elementwise comparison instead of just returning False. Code should be using arr is None. All of these changes will give Deprecation- or FutureWarnings at this time. So far, so clear. Or is it? We can see from @kmario23's answer that as of version 15.2 these changes are not fully implemented yet. To make matters worse, consider this: &gt;&gt;&gt; A = np.array([None, a]) &gt;&gt;&gt; A1 = np.array([None, a]) &gt;&gt;&gt; At = np.array([None, a[:2]]) &gt;&gt;&gt; &gt;&gt;&gt; A==A1 False &gt;&gt;&gt; A==At array([ True, False]) &gt;&gt;&gt; Looks like the current behavior is more a coincidence than the result of careful planning. I suspect it all comes down to whether an exception is raised during element-wise comparison, cf. here and here. If two corresponding elements of the containing arrays are arrays themselves and of compatible shapes as in A==A1, their comparison yields an array of bools. Trying to cast this to a scalar bool raises an exception. Currently, exceptions are caught and a scalar False is returned. In the A==At example an exception is raised when the last two elements are compared because their shapes don't broadcast. This is caught and the comparison for this element returns a scalar False which is why comparison of the containing arrays returns a "normal" array of bools. What about the workarounds suggested by @kmario23 and @Kanak? Do they work? Well, yes ... &…
answers question: http://stackoverflow.com/q/52715049
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/a/52746773
answers question: http://stackoverflow.com/q/52746702
has body: This is a typical wide_to_long question pd.wide_to_long(df,'Eaten ',i=['Food','Type'],j='Month').reset_index() Out[38]: Food Type Month Eaten 0 Apple Fruit 2018-01 3 1 Apple Fruit 2018-02 4 2 Apple Fruit 2018-03 0 3 Pizza Fast Food 2018-01 2 4 Pizza Fast Food 2018-02 1 5 Pizza Fast Food 2018-03 3 6 Cake Desert 2018-01 3 7 Cake Desert 2018-02 6 8 Cake Desert 2018-03 7
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/52746702

http://stackoverflow.com/a/52637449
score: 0
answers question: http://stackoverflow.com/q/52637362
type: Answer
has body: If you want set-like behaviour, use actual sets. new_set = set(seta) + set(setb) # seta &amp; setb are lists But if you really need to use a class which behaves like a list, change the union() function to this: def union(self, other_set): new_set = [i for i in self.elements] # which is actually a list for j in other_set: if j not in self.elements: new_set.append(j) return new_set First, new_set is being created as copy of self (seta). Then, each element of other_set (setb) which is not in self gets added, in order, to the new set.
has comment: http://stackoverflow.com/comment/92208095
has comment: http://stackoverflow.com/comment/92208027

http://stackoverflow.com/comment/92283306
comment on: http://stackoverflow.com/a/52673961
score: 0
type: AnswerComment
has text: For 1d arrays, yes. Unless axis is specified, `skew` is documented to operate on the whole array.
type: Comment

http://stackoverflow.com/comment/92386284
has text: @S.Caruso Sorry, that was a copy-paste error. Can you try again please
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52730472
type: Comment

http://stackoverflow.com/a/52598939
answers question: http://stackoverflow.com/q/52598901
type: Answer
has body: You need list(x) instead of x.split(): [list(x) for x in mystring.split()]
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/92179148
type: QuestionComment
has text: A simpler way than drawing all the segments manually would be to use [`turtle.circle()`](https://docs.python.org/3/library/turtle.html#turtle.circle) and specify a small number of steps to get it to draw an inscribed regular polygon.
comment on: http://stackoverflow.com/q/52622166
score: 1
type: Comment

http://stackoverflow.com/comment/92199975
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52632500
has text: @kurpingspaceproductions your welcome you should look for data structure that matches your requirement. creating a variable is okay if there are 2,3 values but same might not be feasible if there are millions of names. Good luck
type: AnswerComment

http://stackoverflow.com/a/52634042
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/92203314
upvote count: 3
has body: You can use pd.read_csv(), pd.to_csv() and drop_duplicates(): import pandas as pd df = pd.read_csv('test.csv', sep=', ', engine='python') new_df = df'minzoom','maxzoom'.drop_duplicates() new_df.to_csv('out.csv', index=False) Outputs to out.csv: minzoom,maxzoom 0,15 8,15 15,18 Note sep=', ' when reading test.csv, otherwise your column names with contain a leading space if left with default sep=','.
downvote count: 0
answers question: http://stackoverflow.com/q/52633819

http://stackoverflow.com/q/52637365
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52637847
has answer: http://stackoverflow.com/a/52637840
tagged with: urllib
type: Question
possible better answer: http://stackoverflow.com/a/52637847
has body: I would like to extract webpage like: https://www.glassdoor.com/Overview/Working-at-Apple-EI_IE1138.11,16.htm,so I would like to return the result as the following format. Website Headquarters Size Revenue Type www.apple.com Cupertino, CA 10000+ employees $10+ billion (USD) per year Company - Public (AAPL) I then use the following code with beatifulsoup to get this. all_href = com_soup.find_all('span', {'class': re.compile('value')}) all_href = list(set(all_href)) It returns tag with &lt;span&gt;. Also, it didn't show tag under &lt;label&gt; [&lt;span class="value"&gt; Computer Hardware &amp;amp; Software&lt;/span&gt;, &lt;span class="value"&gt; Company - Public (AAPL) &lt;/span&gt;, &lt;span class="value"&gt;10000+ employees&lt;/span&gt;, &lt;span class="value"&gt; $10+ billion (USD) per year&lt;/span&gt;, &lt;span class="value-title" title="4.0"&gt;&lt;/span&gt;, &lt;span class="value"&gt;Cupertino, CA&lt;/span&gt;, &lt;span class="value"&gt; 1976&lt;/span&gt;, &lt;span class="value-title" title="5.0"&gt;&lt;/span&gt;, &lt;span class="value website"&gt;&lt;a class="link" href="http://www.apple.com" rel="nofollow noreferrer" target="_blank"&gt;www.apple.com&lt;/a&gt;&lt;/span&gt;]
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52637840
has title: extract tag on html with python
tagged with: beautifulsoup

http://stackoverflow.com/a/52604630
type: Answer
answers question: http://stackoverflow.com/q/52604157
score: 2
has body: Try the following to get your desired output. I ignored the first tr by indexing it like [1:] as there is no td within it. Moreover, there is no such method .find.all() in BeautifulSoup. you can use .find_all() or .findAll() instead. import requests from bs4 import BeautifulSoup res = requests.get("https://www.hltv.org/stats/teams") soup = BeautifulSoup(res.text, "html.parser") for tr in soup.find("table",class_="player-ratings-table").find_all("tr")[1:]: team = tr.find_all('td')[0].text.strip() maps = tr.find_all('td')[1].text.strip() kd = tr.find_all('td')[3].text.strip() rating = tr.find_all('td')[4].text.strip() print(team, maps, kd, rating)
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/92327689
has text: Hi, unfortunately this solution doesn't work for me, modyifing hook-clr.py as suggested returns me ValueError: too many values to unpack (expected 2). I'll update my OP with more infos
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52667031

http://stackoverflow.com/a/52625285
has comment: http://stackoverflow.com/comment/92184600
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52625193
has comment: http://stackoverflow.com/comment/92184167
answers question: http://stackoverflow.com/q/52625193
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92184478
has body: Mongo uses BSON and they have a dedicated parser util implemented in python. From source: Deserialization: from bson.json_util import loads loads('[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$scope": {}, "$code": "function x() { return 1; }"}}, {"bin": {"$type": "80", "$binary": "AQIDBA=="}}]') # &gt;&gt;&gt; [{u'foo': [1, 2]}, {u'bar': {u'hello': u'world'}}, {u'code': Code('function x() { return 1; }', {})}, {u'bin': Binary('...', 128)}] Serialization: from bson import Binary, Code from bson.json_util import dumps dumps([{'foo': [1, 2]}, {'bar': {'hello': 'world'}}, {'code': Code("function x() { return 1; }", {})}, {'bin': Binary(b"")}]) # &gt;&gt;&gt; '[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }", "$scope": {}}}, {"bin": {"$binary": "AQIDBA==", "$type": "00"}}]' When the object you try to serialize/deserialize is BSON you need to use mongo's dumps and loads or it won't be parsed correctly. When it is a regular JSON you can use either one you like.

http://stackoverflow.com/q/52710165
has comment: http://stackoverflow.com/comment/92354522
type: Question
tagged with: regex-lookarounds
linked to: http://stackoverflow.com/q/15814592
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92346558
has comment: http://stackoverflow.com/comment/92346674
tagged with: regex
has body: I'm trying to find an elegant way for matching negative and positive numbers at the same time, but not to capture the + sign while capturing the - sign. So I have something like: re.findall("([+-] \d+)x", "6x2 + 4x + 5 - 2x2 - 7x + 4 + 87x - 100x") This gives me all multipliers for x, both positive and negative (great!). I would like the negative numbers to be - 2, for example, but not return the plus sign for positive numbers (4 instead of + 4). I failed with ?: option, maybe I just used it incorrectly.
type: UnansweredQuestion
tagged with: python
tagged with: optional-parameters
has comment: http://stackoverflow.com/comment/92382140
has comment: http://stackoverflow.com/comment/92404814
has title: Python Regex - optional match, do not capture one match
has answer: http://stackoverflow.com/a/52725817

http://stackoverflow.com/comment/92149181
has text: @ArthurLC: ok, properties allow you to still write `object.x = 5`, but instead of setting `x`, this calls the `set_x` method without the user changing anything or even knowing. In java you can't do that, so you add getters/setters *just in case* something changes (in most cases they are totally useless)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52607461

http://stackoverflow.com/q/52625864
favorite count: 0
type: UnansweredQuestion
has body: In my current project I'm doing data analysis of forest inventory data and fitting statistical distributions to the data by Max Likelihood Estimation. I calculate the results of each dataset for each required subset of data and get back the estimated distribution parameters and other metrics I need and then store them all in a pandas dataframe. So far I do all this in a big for loop through each subset of data and then assign the results row by row to the dataframe. What I want to know is there a more efficient way of doing this? I also don't want to have lots of copies of the data as often I have a million data points or so. I have created a very simplified example with artifical data and without the max likelihood estimation, but that shows the basic structure import pandas as pd import scipy as sp import numpy.random as sprd def Gen_UniformDist(seed=5, size=1000000): """ Create a set of random numbers uniformly distributed between 0 and 1 """ sprd.seed(seed) return sprd.uniform(size=size) # Generate some test data dataSet = Gen_UniformDist() # Create an array of truncation vales truncValue_arr = sp.linspace(0., 0.9, 20) df_Output = pd.DataFrame(index=truncValue_arr, columns=['mean', 'NumObs']) for i, truncValue in enumerate(truncValue_arr): # Truncate the data using the truncation value truncated_DataSet = dataSet[ dataSet &gt;= truncValue] # In my real code the function here is more complex max likelihood # rather than simple mean used for simplicity here mean = sp.mean(truncated_DataSet) numObs = len(truncated_DataSet) # Real code would calculate more than 2 values for each row df_Output.iloc[i] = [mean, numObs] What I would like to do is fill the dataframe efficiently without the for loop but also avoid having lots of copies of the data around. Is this possible?
tagged with: python
tagged with: performance
score: 1
upvote count: 1
has title: More efficient way than row by row calculation of Pandas Dataframe
type: Question
has answer: http://stackoverflow.com/a/52626069
has comment: http://stackoverflow.com/comment/92185022
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52747061
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/92418809
favorite count: 0
has comment: http://stackoverflow.com/comment/92419000
has body: For example, I have started coding an UNO! game I need to do the reverse card. The entire 'Main Game Code'where you place the card and re-sort the pile etc... The 'Main Game Code'is in this loop: while self.gamestr==True: for l in range(1,players+1): And I need the loop to be range(1,players+1,-1) whilst inside the loop and change it back again whilst still in the loop! Thanks in advance,
has answer: http://stackoverflow.com/a/52747813
tagged with: reverse
type: UnansweredQuestion
tagged with: python
has title: Is there a way to be inside a for loop, and then reverse that loop from the current position?
has comment: http://stackoverflow.com/comment/92418718
has comment: http://stackoverflow.com/comment/92418940
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/92418701
type: Question
has comment: http://stackoverflow.com/comment/92419028
has answer: http://stackoverflow.com/a/52747285
score: -2
has comment: http://stackoverflow.com/comment/92419222

http://stackoverflow.com/q/52692130
favorite count: 0
tagged with: udp
tagged with: python
has body: On the React-Native side, I'm binding to port 55555. import dgram from 'react-native-udp'; import { Buffer } from 'buffer' const foo = ()=&gt;{ var socket = dgram.createSocket('udp4') socket.bind(55555, '0.0.0.0', (e)=&gt;{ if(e) console.log(e) }) socket.once('listening', function() { var buf = Buffer.from(JSON.stringify('msg')) socket.send(buf, 0, buf.length, 5000, MACHINE_LOCAL_IP, function(err) { if (err) alert(err) console.log('Sent to', MACHINE_LOCAL_IP) }) }) } I'm seeing the following console log socket-0 bound to address: 0.0.0.0 port: 55555 Sent to [...] It works as expected maybe 8 / 10 times. On my server side, I'm opening a UDP socket in python sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(1) sock.bind(('0.0.0.0', 5000)) while True: try: data, in_address = sock.recvfrom(1024) print(in_address) except socket.timeout: pass except Exception as e: print(e) break When I run foo multiple times, here's my python output ('192.168.0.5', 55555) ('192.168.0.5', 55555) ('192.168.0.5', 55555) ('192.168.0.5', 55555) ('192.168.0.5', 55555) ('192.168.0.5', 55555) ('192.168.0.5', 52917) ('192.168.0.5', 49619) ('192.168.0.5', 63532) ('192.168.0.5', 55555) ('192.168.0.5', 55555) I'm not able to figure out why the port is changing!
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: react-native
score: 1
has title: react-native-udp - bound port not same as what my server is seeing
type: Question
upvote count: 1

http://stackoverflow.com/comment/92375511
score: 0
type: Comment
has text: Thank you so much!! It's exactly what I was looking for. I still don't understand it fully, but I'll stare at it for a while and see if I can. @WiktorStribiżew
type: AnswerComment
comment on: http://stackoverflow.com/a/52708373

http://stackoverflow.com/comment/92269374
comment on: http://stackoverflow.com/q/52669705
score: 0
has text: Try dropping the `cv2` from `cv2.xfeatures2d.SIFT_create()`. Looking at the documentation, everything references `cv.xfeature2d` rather than 'cv2'
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52674026
downvote count: 0
upvote count: 2
type: Answer
has body: SLICE_Z = 2 By design, arr[0:1] is not the same as arr[0]. Slices always return iterables.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52673933
answers question: http://stackoverflow.com/q/52673933
score: 2

http://stackoverflow.com/comment/125473384
score: 0
type: AnswerComment
has text: `from jsonschema import validate, FormatChecker validate({"2001-02"}, {"type": "string", "format": "date"}, format_checker=FormatChecker()) # throws validation error as expected validate({"dob": "2001-02"}, {"dob": {"type": "string", "format": "date"}}, format_checker=FormatChecker()) # Doesnt throw error which is wrong` Can someone help ? am i missing something ?
type: Comment
comment on: http://stackoverflow.com/a/52729888

http://stackoverflow.com/comment/92398173
score: 0
has text: You need a shared library, no a static one. But you have the right intuition. Look at the documentation to get to the shared library (.dll on Windows by default but you will have to change the suffix to pyd).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52736687

http://stackoverflow.com/comment/92330964
type: Comment
comment on: http://stackoverflow.com/a/52672082
has text: The docs state that `(batch_size, timesteps, input_dim)`should be the input shape. My training dataset has 21k datapoints with each point being an encoded vector (vocabulary) of length 1500. Reshaping it produces X_train with shape (21226, 1500,1) which again throws the same error.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52674911
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: python - dont print results that have already been printed
score: 2
has comment: http://stackoverflow.com/comment/92279315
has answer: http://stackoverflow.com/a/52674941
has body: I have a python script that prints out lists of numbers that are perfect cubes and add to 1978. Here is the output: `[1, 27, 729, 512, 8, 512, 1, 8] [1, 27, 729, 512, 8, 512, 8, 1] [1, 27, 729, 512, 512, 1, 8, 8] [1, 27, 729, 512, 512, 8, 1, 8] [1, 27, 729, 512, 512, 8, 8, 1] [1, 64, 8, 64, 125, 512, 512, 512] [1, 64, 8, 64, 512, 125, 512, 512] [1, 64, 8, 64, 512, 512, 125, 512] [1, 64, 8, 64, 512, 512, 512, 125] [1, 64, 8, 125, 64, 512, 512, 512]` I only want the results once, and not dupplacates, as I do not care what order the numbers are in, so out of this sample, I would only want 2 answers instead of 10. Is there a way to do this? Edit: also, the results take about a day to write out because there are so many, so I need something that can actively filter, so it goes faster
has comment: http://stackoverflow.com/comment/136475417
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52675010
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52600181
tagged with: algorithm
score: -2
has comment: http://stackoverflow.com/comment/92134867
has comment: http://stackoverflow.com/comment/92135094
accepted answer: http://stackoverflow.com/a/52600206
has comment: http://stackoverflow.com/comment/92134957
tagged with: runtime-error
has comment: http://stackoverflow.com/comment/92134858
answer count: 2
has body: So I'm trying to solve a challenge here, and I have a basic algorithm written to solve this problem. One of the functions of this algorithm is that it will convert the input of the function, n, to a string, slice every character but the first, and convert it back to an integer using this: o = int(str(n[:1])). When I do this however, it gives me this error: TypeError: 'int' object is not subscriptable. I have found another case here, but it does not seem to solve my problem. What does this error mean and how can I rid my code of it? Full function: def utopianTree(n): o = int(str(n[:1])) n = int(str(n[1:])) for i in range(1, n): if n == 0: o += 1 elif i % 2 == 0: o *= 2 elif i % 2 != 0: o += 1 i += 1 return o
has comment: http://stackoverflow.com/comment/92134982
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92134855
has comment: http://stackoverflow.com/comment/92134842
tagged with: python
possible better answer: http://stackoverflow.com/a/52600212
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52600212
has answer: http://stackoverflow.com/a/52600206
tagged with: compiler-errors
has comment: http://stackoverflow.com/comment/92135013
has comment: http://stackoverflow.com/comment/92135041
has comment: http://stackoverflow.com/comment/92135129
linked to: http://stackoverflow.com/q/8220702
has title: Why does converting an integer to a string, slicing it, and then converting it back to an integer give me this TypeError?
downvote count: 2
type: Question

http://stackoverflow.com/comment/92315999
comment on: http://stackoverflow.com/q/52694712
score: 1
has text: Please post the data format and what you have tried so far. It is hard to provide a solution when we don't have all the pieces of the problem.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92245409
has text: @ALollz ? @Wen?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52657193
type: AnswerComment

http://stackoverflow.com/q/52683685
type: Question
tagged with: boto3
has comment: http://stackoverflow.com/comment/92307693
score: 0
has comment: http://stackoverflow.com/comment/92297343
has comment: http://stackoverflow.com/comment/92302203
has title: Unable to Download Images from S3 Bucket in Python/Code has Access Keys already
answer count: 1
has body: For a project, I need to download some items in my S3 bucket. I have already seen similar posts about this topic; however, I hardcoded my access key ID and secret access key inside the program and am still unable to download them. Python keeps returning the error: "botocore.exceptions.NoCredentialsError: Unable to locate credentials" Despite providing my credentials, I am still unable to download. My code is provided below. Can anyone help me correct this? import boto3 import os """import sys import csv import pandas as pd import numpy as np import tensorflow as tf""" import nibabel as nib from boto3.session import Session aws_access_key_id = '********************' aws_secret_access_key = '****************************************' bucket1 = 'adnimcic' mcic = [[], [], []] mcicc = [[], [], []] bucket2 = 'adnimcinc' mcinc = [[], [], []] bucket3 = 'adniresults' results = [] s3_client = boto3.client('s3') #connecting to S3 session = Session(aws_access_key_id, aws_secret_access_key) s3 = session.resource('s3') bucket1obj = s3.Bucket(bucket1) #bucket2obj = s3.Bucket(bucket2) #'MCIc_Segmented/ADNI_002_S_0729_MR_MP-RAGE_REPEAT_br_raw_20070225105857428_72_S27091_I41585_be_be_pve_2.nii.gz_extracted' def concatenate(name): name = name.split('.') name.pop() name = name[0] + '.' + name[1] name = name.split('/') name = name[1] return name def download(bucketname, key): path = '/Volumes/LaCie Mac/' + concatenate(key.key) s3_client.download_file(bucketname, key.key, path) for key in bucket1obj.objects.all(): if 'pve_0' and 'extracted' in key.key: mcic[0].append(key) download(bucket1, key) for key in bucket1obj.objects.all(): if 'pve_1' and 'extracted' in key.key: mcic[1].append(key) download(bucket1, key) for key in bucket1obj.objects.all(): if 'pve_2' and 'extracted' in key.key: mcic[2].append(key) download(bucket1, key)
has answer: http://stackoverflow.com/a/52685118
type: UnansweredQuestion
tagged with: python
tagged with: amazon-s3

http://stackoverflow.com/q/52607301
has comment: http://stackoverflow.com/comment/92148818
has title: How do I format a tuple of strings?
possible better answer: http://stackoverflow.com/a/52607507
has answer: http://stackoverflow.com/a/52607507
tagged with: python
has body: I have a database, made by sqlite3: CREATE TABLE test_table ( username TEXT, langFrom TEXT, langTo TEXT, mode INT, PRIMARY KEY ( username )); Now I want to get a data from it by "SELECT..WHERE" command. For that, i'm making query: def getData(self, **kwargs): s = """SELECT * FROM test_table WHERE {} = {}"""\ .format(tuple(kwargs.keys()), tuple(kwargs.values())) I use this method like that: test_DB.getData(username = 'classtest', langFrom = 'ru') And now I have query, that looks like that: SELECT * FROM test_table WHERE ('username', 'langFrom') = ('classtest', 'ru') But I need it like that: SELECT * FROM test_table WHERE (username, langFrom) = ('classtest', 'ru') So how should I format my string to do that?
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52607543
type: Question
has comment: http://stackoverflow.com/comment/92149088
answer count: 2
tagged with: sql
accepted answer: http://stackoverflow.com/a/52607543
tagged with: sqlite
has comment: http://stackoverflow.com/comment/92148727

http://stackoverflow.com/comment/92248329
score: 0
type: Comment
has text: True! I am learning from many answers. I am really glad with that
comment on: http://stackoverflow.com/a/52658842
type: AnswerComment

http://stackoverflow.com/comment/92120266
type: Comment
comment on: http://stackoverflow.com/a/52592707
score: 1
has text: Finally, I would like to mention that it might make more sense to find the average RGB value of the biggest image segment rather than to find a single most common value. Look into [image segmentation, specifically clustering](https://en.wikipedia.org/wiki/Image_segmentation#Clustering_methods) and see if that is more apt to your application. You should also consider that image segmentation consumes a lot more resources.
type: AnswerComment

http://stackoverflow.com/comment/92384214
type: AnswerComment
has text: Basic example, but `mydict = {'a': 1, **{b: ' ' for b in {'Yearly', 'Monthly', 'Perday'}-{base}}}` runs just fine. Looking at what you posted, `**(base...` is incorrect because the `**` syntax unpacks a dictionary, while `(base` implies a tuple
type: Comment
comment on: http://stackoverflow.com/a/52727098
score: 0

http://stackoverflow.com/comment/92258173
has text: Python 3.6 running on 64bit Amazon Linux/2.7.3
comment on: http://stackoverflow.com/q/52653184
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52600964
has comment: http://stackoverflow.com/comment/92205448
downvote count: 1
upvote count: 0
has body: Without trying to set up a full test environment for this, it looks like the nested format is the projection you're explicitly requesting. I'd try this: response = table.query( KeyConditionExpression=Key('some_id').eq(some_id), ProjectionExpression="#p1, #s", ExpressionAttributeNames={'#p1': 'prop1', '#s': 'some_id'} ) Since you don't actually want #p or the nesting at all, I removed it from both the attribute names and the projection.
score: -1
type: Answer
answers question: http://stackoverflow.com/q/52590059

http://stackoverflow.com/q/52623789
has answer: http://stackoverflow.com/a/52624389
tagged with: python
tagged with: python-3.x
upvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52628269
has title: Change duplicate list items if they don't go one after another
has body: I have a list of integers that has duplicates. Example: 37 1 30 38 5 39 5 5 5 40 33 5 35 42 25 36 27 27 43 27 I need to change duplicate numbers to some other numbers if they don't go one after another. New numbers should not duplicates other numbers in a list. For example, the list above should become something like this: 37 1 30 38 5 39 8 8 8 40 33 2 35 42 25 36 27 27 43 55 This is what I got: a = [37, 1, 30, 38, 5, 39, 5, 5, 5, 40, 33, 5, 35, 42, 25, 36, 27, 27, 43, 27] duplicates = list(item for item, count in Counter(a).items() if count &gt; 1) for dup in duplicates: positions = [] for item in range(len(a)): if a[item] == dup: positions.append(item) for x in range(len(positions)-1): if positions[x+1] - positions[x] != 1: ran = random.randrange(1, len(a)) while ran in a: ran = random.randrange(1, len(a)) a[positions[x+1]] = ran else: y = x while positions[y+1] - positions[y] == 1: a[positions[y+1]] = a[positions[y]] y += 1 [37, 1, 30, 38, 5, 39, 17, 17, 17, 40, 33, 13, 35, 42, 25, 36, 27, 27, 43, 8] But I don't think it's a good solution.
type: Question
answer count: 2
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/92190009
favorite count: 0

http://stackoverflow.com/a/52621707
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52610862
answers question: http://stackoverflow.com/q/52610862
upvote count: 2
type: Answer
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/98677200
has body: What I finally did was converting my list to string as: my_list=str(my_list) And upload it to Blob Storage as: BlockStorage('&lt;account_name&gt;', '&lt;account_key&gt;').block_service.create_blob_from_text('&lt;container_name&gt;', '&lt;file_name&gt;', my_list) And finally, to download it: my_file_as_str = BlockStorage('&lt;account_name&gt;', '&lt;account_key&gt;').block_service.get_blob_to_text('&lt;container_name&gt;', '&lt;file_name&gt;') To get back my list I just needed to do now: my_list = eval(my_file_as_str.content)

http://stackoverflow.com/comment/92191721
comment on: http://stackoverflow.com/a/52628895
type: Comment
has text: You are the best!! Thank you so much!! This works exactly like I needed it to. I just had to change the key and vals to v and k.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52676426
tagged with: pandas
answer count: 1
has title: How to set transparency and background colour for a pie chart matplotlib
favorite count: 0
upvote count: 9
tagged with: python
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52678032
tagged with: matplotlib
has body: I'm sure this is somewhere in SO but I can't see to find it anywhere. I'm trying to alter the colour transparency or alpha for a pie chart in matplotlib. I'm also hoping to set the background colour to grey. import pandas as pd import matplotlib.pyplot as plt d = ({ 'C' : ['X','Y','Z','X','Y','Z','A','X','Y','Z'], }) df = pd.DataFrame(data=d) fig, ax = plt.subplots(figsize = (20,12)) ax.grid(False) plt.style.use('ggplot') df['C'].value_counts().plot(kind = 'pie') plt.show I cant seem to change the pie chart colour transparency or use the background generally created by 'ggplot'?
score: 9
type: Question
has comment: http://stackoverflow.com/comment/92282208
has answer: http://stackoverflow.com/a/52678032

http://stackoverflow.com/comment/92379286
has text: `csv` isn't dropping leading zeros. You are. Why are you calling `int`?
comment on: http://stackoverflow.com/q/52727032
score: 5
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/104162015
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52644615
has text: @Nihal, the html you posted is truncating some columns' contents. How do I work around this problem?

http://stackoverflow.com/q/52615888
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52633129
has title: output changes while appending dictionary data into list in python
has body: I have a dictionary containing data in a certain format. When I am printing the dictionaries individually, it is printing the data correctly but when I am adding all dictionaries into a list and then printing the list, it is printing wrong output. May I know the solution to this problem? my code: import glob import os list_for_dictionary = [] list_for_dictionary_2 = [] data_location = 'D:\\sample_data' # folder containing all the data for root, directories, files in os.walk(data_location): for directory in directories: loc = (data_location + '/' + directory + '/*') all_files = glob.glob(loc) for filename in all_files: list_for_dictionary.clear() f = open(filename) for line_number, line in enumerate(f, 1): dictionary = {"fileLine": line.strip(), "lineNumber": int(line_number), "fileName": filename.split("\\")[-1]} list_for_dictionary.append(dictionary) dictionary_2={"collection":[], "documentName":filename.split("\\")[-1],"returnId":0,"docData":{"Matches":list_for_dictionary}} print(dictionary_2) list_for_dictionary_2.append(dictionary_2) print(list_for_dictionary_2) Expected output: [{'collection': [], 'documentName': 'sample.txt', 'returnId': 0, 'docData': {'Matches': [{'fileLine': 'Name of Person: John', 'lineNumber': 1, 'fileName': 'sample.txt'}, {'fileLine': 'Age: 24 years', 'lineNumber': 2, 'fileName': 'sample.txt'}]}} {'collection': [], 'documentName': 'sample2.txt', 'returnId': 0, 'docData': {'Matches': [{'fileLine': 'Name of Person: Matthews', 'lineNumber': 1, 'fileName': 'sample2.txt'}, {'fileLine': 'Age: 32 years', 'lineNumber': 2, 'fileName': 'sample2.txt'}]}} {'collection': [], 'documentName': 'sample3.txt', 'returnId': 0, 'docData': {'Matches': [{'fileLine': 'Name of Person: Alisa', 'lineNumber': 1, 'fileName': 'sample3.txt'}, {'fileLine': 'Age: 40 years', 'lineNumber': 2, 'fileName': 'sample3.txt'}]}} {'collection': [], 'documentName': 'sample4.txt', 'returnId': 0, 'docData': {'Matches': [{'fileLine': 'Name of Person: Jacob', 'lineNumber': 1, 'fileName…
answer count: 1
has comment: http://stackoverflow.com/comment/92172874
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92166407
tagged with: data-extraction
has comment: http://stackoverflow.com/comment/92175614
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52633129
type: AnsweredQuestion
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/92171577
upvote count: 1

http://stackoverflow.com/q/52634085
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/52635115
favorite count: 0
possible better answer: http://stackoverflow.com/a/52634154
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I need to match street names to gps coordinates in a pandas dataframe. I use OSRM for this; I can give OSRM a list of GPS coordinates and it will give me the names, but my series contains NaNs and OSRM does not accept nulls or zeros, so I need to filter them out (easy) but then put the results back in the corresponding rows; how do I do this? Edit: there are other columns in the dataframe (symbolised by t here, but there are more) that I cannot lose. import pandas as pd import numpy as np import requests import json path = [ 51.954974, 5.857131, 51.955014, 5.860725, np.nan, np.nan, 51.954168, 5.866390, 51.954889, 5.868611, ] path = [ {'t': t, 'lat': c[0], 'lon': c[1]} for t, c in enumerate(zip(*[path[i::2] for i in range(2)]))] df = pd.DataFrame(path) path = ';'.join(list(df[pd.notnull(df.lat)].apply(lambda x: str(x.lon) + ',' + str(x.lat), axis=1))) osrm = 'http://router.project-osrm.org' # currently down #osrm = 'http://localhost:5000' url = osrm + '/match/v1/car/' + path + '?overview=full&amp;annotations=nodes&amp;tidy=true' # OSRM is down now but this return [ "Metamorfosenallee", "Burgemeester Matsersingel", "Burgemeester Matsersingel", "Batavierenweg" ] matched = [tp['name'] for tp in requests.post(url).json()['tracepoints']] # how do I now get # t lat lon name # 0 51.954974, 5.857131, Metamorfosenallee # 1 51.955014, 5.860725, Burgemeester Matsersingel # 2 np.nan, np.nan, np.nan # 3 51.954168, 5.866390, Burgemeester Matsersingel # 4 51.954889, 5.868611, Batavierenweg (edited to add extra column I do not want to lose)
type: Question
has answer: http://stackoverflow.com/a/52634154
accepted answer: http://stackoverflow.com/a/52635115
has title: Apply a function to a pandas column where that function does not accept NaNs
answer count: 2

http://stackoverflow.com/comment/92418333
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52746510
has text: Yes. I was just confused by it being `-c`. My train of thought was as follows: "`argv[0]` == `-c` looks like an argument I've passed, not like a program name. That means that Python only has arguments in `argv`, not the program. But why does it include the `-c` arg that it has parsed?" I won't have been fooled if `argv[0]` contained anything other that `-c`.

blocking
tags question: http://stackoverflow.com/q/52607405
type: Tag
tags question: http://stackoverflow.com/q/52674040
tag name: blocking

http://stackoverflow.com/comment/92341166
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52693941
type: Comment
has text: Thanks, it worked :) (I didn't know that b"" could be a value and less what it means :P)

http://stackoverflow.com/a/52721179
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92367865
answers question: http://stackoverflow.com/q/52720961
has body: sleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds has elapsed or until a signal arrives which is not ignored. You can define a custom sleep function as follows: import datetime import time def busy_sleep(seconds): start_time = datetime.datetime.now() seconds_slept = 0 while seconds_slept &lt; seconds: time.sleep(seconds - seconds_slept) seconds_slept = (datetime.datetime.now() - start_time).total_seconds() Just call busy_sleep(10) instead of time.sleep(10).
upvote count: 1

http://stackoverflow.com/a/52841259
answers question: http://stackoverflow.com/q/52741742
has comment: http://stackoverflow.com/comment/92598867
has body: Using OpenCV for Python is really straightforward. Here I created a function to plot a sample image. Note that for this function the image must be RGB or BGR. import cv2 import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D image_BGR = np.uint8(np.random.rand(50,50,3) * 255) #this image above is just an example. To load a real image use the line below #image_BGR = cv2.imread('path/to/image') def toLAB(image, input_type = 'BGR'): conversion = cv2.COLOR_BGR2LAB if input_type == 'BGR' else cv2.COLOR_RGB2LAB image_LAB = cv2.cvtColor(image, conversion) y,x,z = image_LAB.shape LAB_flat = np.reshape(image_LAB, [y*x,z]) colors = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if input_type == 'BGR' else image colors = np.reshape(colors, [y*x,z])/255. fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xs=LAB_flat[:,2], ys=LAB_flat[:,1], zs=LAB_flat[:,0], s=10, c=colors, lw=0) ax.set_xlabel('A') ax.set_ylabel('B') ax.set_zlabel('L') plt.show() return image_LAB lab_image = toLAB(image_BGR) The result is something like this: I hope it helped!
has comment: http://stackoverflow.com/comment/92599083
has comment: http://stackoverflow.com/comment/92599617
upvote count: 9
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92599415
score: 9
has comment: http://stackoverflow.com/comment/92599462
type: Answer
accepted answer of: http://stackoverflow.com/q/52741742
has comment: http://stackoverflow.com/comment/92599542

http://stackoverflow.com/q/52714444
type: Question
score: -1
favorite count: 0
tagged with: lighttpd
has title: Calling a Python script from PHP does not work
tagged with: python
tagged with: php
has body: I'm creating a webpage in PHP wherein if a button is pressed, the PHP script executes a python script using shell_exec() command. The python script creates a pdf file using fpdf python library. When I run the same from command shell, it works prefectly but when I try to run python script from PHP, it gives me nothing. Here is PHP code: &lt;!doctype html&gt; &lt;?php $command = escapeshellcmd('/home/amogh/server/test.py'); $output = shell_exec($command); echo $output; ?&gt; Python script: #! /usr/bin/python #print ('hello') from fpdf import FPDF fp = open('downloads/boot.txt', 'r') pdf = FPDF() pdf.add_page() pdf.set_font('Arial', '', 11) line = fp.read() pdf.multi_cell(200, 5, line, 0, 1) pdf.output('test.pdf', 'F') Also, I'm using lighttpd server. Can anyone tell me where am I going wrong?
answer count: 1
has answer: http://stackoverflow.com/a/52714497
tagged with: ubuntu-16.04
downvote count: 1
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92364861
tagged with: python-2.7

http://stackoverflow.com/q/52706667
tagged with: oop
tagged with: class
has comment: http://stackoverflow.com/comment/92340143
upvote count: 3
has answer: http://stackoverflow.com/a/52706688
has title: Checking whether function contains pass
answer count: 2
has comment: http://stackoverflow.com/comment/92339587
tagged with: python-3.5
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I have one parent class P and several child classes. The parent class contains the method doSomething(x) defined only as: def doSomething(self, x): pass Now, some of P's subclasses may have implemented this method, and some have not. Is there any way I can check if doSomething(x) is going to do nothing but pass, at runtime (e.g. if it is implemented, execute it, if not, skip it)?
tagged with: python
has comment: http://stackoverflow.com/comment/92339582
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52706688
has answer: http://stackoverflow.com/a/52706738
accepted answer: http://stackoverflow.com/a/52706738
type: Question
score: 3

http://stackoverflow.com/a/52682005
has comment: http://stackoverflow.com/comment/92294650
downvote count: 0
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52681762
has body: Your logic is correct when used in natural language, however not in python. The "all" method True returns if all elements is True, and the "any" method returns True if any element is True. The shortest way to express what you want is avgs = rotation / speed if ((55 &lt;= avgs) &amp; (avgs &lt;= 55.2)).all(): return True return False

http://stackoverflow.com/comment/92326663
type: Comment
type: QuestionComment
has text: The closest parent that still exists is `r.html.find('#dp-container')`, and it is empty. That's probably where the problem started.
comment on: http://stackoverflow.com/q/52699466
score: 0

http://stackoverflow.com/a/52606689
answers question: http://stackoverflow.com/q/52595623
score: 0
has comment: http://stackoverflow.com/comment/92171708
has body: SELECT id, CONVERT_FROM(x, 'UTF8') as x, CONVERT_FROM(y, 'UTF8') as y FROM `dfs.root`.`./data` You can find this info in Apache Drill documentation: https://drill.apache.org/docs/data-type-conversion/#convert_to-and-convert_from I think you mean fixed_len_byte_array. It is a primitive Parquet data type. It can be used for INTERVAL and DECIMAL logical data types. Looks like Drill supports both of them out of the box. If you didn't specify the logical datatype for your fixed_len_byte_array, it is not clear how to interpret this data.
type: Answer
has comment: http://stackoverflow.com/comment/92155672
has comment: http://stackoverflow.com/comment/92168388

http://stackoverflow.com/comment/124146651
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/70229480
has text: yeah but if possible to call `cv2.cvtColor()` method?

http://stackoverflow.com/q/52593874
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52600160
favorite count: 0
type: Question
tagged with: code-coverage
answer count: 2
score: 5
tagged with: python
has title: interpret python coverage unit testing
has answer: http://stackoverflow.com/a/52600160
has body: I am currently unit testing and was confused on the the below: Name Stmts Miss Branch BrPart Cover Missing ------------------------------------------------------------------- src/__init__.py 0 0 0 0 100% src/__main__.py 33 2 8 3 88% 76-78, 50-&gt;exit, 57-&gt;exit, 70-&gt;76 what exactly does the 50-> exit mean?
upvote count: 5
possible better answer: http://stackoverflow.com/a/78578134
downvote count: 0
has answer: http://stackoverflow.com/a/78578134

http://stackoverflow.com/q/52684338
type: UnansweredQuestion
tagged with: python
tagged with: meta
linked to: http://stackoverflow.com/q/15578918
tagged with: web-scraping
tagged with: scrapy
type: Question
linked to: http://stackoverflow.com/q/12276663
has body: strong textMy code based on examples that I searched did not seem to function as intended so I decided to use a working model found on github: https://github.com/scrapy/quotesbot/blob/master/quotesbot/spiders/toscrape-xpath.py I then modified it slightly to showcase what I am running into. The code below works great as intended but my ultimate goal is to pass the scraped data from first "parse" to a second "parse2" function so that I can combine data from 2 different pages. But for now I wanted to start very simple so I can follow what is happening, hence the heavily stripped code below. # -*- coding: utf-8 -*- import scrapy from quotesbot.items import MyItems from scrapy import Request class ToScrapeSpiderXPath(scrapy.Spider): name = 'toscrape-xpath' start_urls = [ 'http://quotes.toscrape.com/', ] def parse(self, response): item = MyItems() for quote in response.xpath('//div[@class="quote"]'): item['tinfo'] = quote.xpath('./span[@class="text"]/text()').extract_first() yield item but then when I modify the code as below: # -*- coding: utf-8 -*- import scrapy from quotesbot.items import MyItems from scrapy import Request class ToScrapeSpiderXPath(scrapy.Spider): name = 'toscrape-xpath' start_urls = [ 'http://quotes.toscrape.com/', ] def parse(self, response): item = MyItems() for quote in response.xpath('//div[@class="quote"]'): item['tinfo'] = quote.xpath('./span[@class="text"]/text()').extract_first() yield Request("http://quotes.toscrape.com/", callback=self.parse2, meta={'item':item}) def parse2(self, response): item = response.meta['item'] yield item I only have one item scraped and it says the rest are duplicates. It also looks like "parse2" is not even read at all. I have played with the indentation and the brackets thinking I am missing something simple, but without much success. I have looked at many examples to see if I can make sense of what could be the issue but I still am not able to make it work. I am sure its a very simple issue for those gurus out th…
has title: simple scrapy based on https://github.com/scrapy/quotesbot/blob/master/quotesbot/spiders/toscrape-xpath.py not passing data using yield Request
score: 0
has answer: http://stackoverflow.com/a/52685017
answer count: 1

http://stackoverflow.com/a/52733504
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/92394415
answers question: http://stackoverflow.com/q/52717485
has body: You seem to have a slight misunderstanding landscape is an orientation not a page size, here i'm assuming you want your last page to be in the landscape orientation. Having a page in the landscape orientation means that it is the same size as your previous pages just that it will be horizontally presented rather than vertically. You can change this property by setting the layout property of the last page to landscape.

http://stackoverflow.com/comment/92153909
type: QuestionComment
has text: thanks for the tip!
comment on: http://stackoverflow.com/q/52595858
score: 0
type: Comment

http://stackoverflow.com/a/52596527
has comment: http://stackoverflow.com/comment/92165431
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92164311
has comment: http://stackoverflow.com/comment/92165463
answers question: http://stackoverflow.com/q/52595386
has comment: http://stackoverflow.com/comment/92153539
upvote count: 1
has comment: http://stackoverflow.com/comment/92166075
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92165939
has comment: http://stackoverflow.com/comment/92164619
accepted answer of: http://stackoverflow.com/q/52595386
has comment: http://stackoverflow.com/comment/92166214
has body: For demonstration purposes, I shuffled a list of 300 integers, to get the 10 highest values, you would use sorted and then take the range [-10:] import random l = [*range(300)] random.shuffle(l) print(sorted(l)[-10:]) [290, 291, 292, 293, 294, 295, 296, 297, 298, 299] Update random.shuffle(folder) for i in range(len(folder)): max_powers = [] if i &lt; 3: max_powers = [] phaseresult_i = [] data = np.loadtxt(dir + folder[i]) time = data[:,0]-2450000 magnitude = data[:,1] print ('\n File:', folder[i],'\n','Time:',time,'\n', 'Magnitude:', magnitude) t = 10000 * time y = np.sin(2 * np.pi * t) * time # Lomb Scargle Periodogram frequency, power = LombScargle(t, y).autopower() for period in folder[i]: period = np.log(1/frequency)[np.argmax(power)] maxpower = power.max() max_powers.append((maxpower, i)) print('\n Max Power = ', maxpower) print('\n Period = ', period, '\n ---------------------------') print('\n Max Powers, Folder = {}'.format(sorted(max_powers, key=lambda x: x[0])[:-10])) else: break
has comment: http://stackoverflow.com/comment/92164392
type: Answer
has comment: http://stackoverflow.com/comment/92164840
has comment: http://stackoverflow.com/comment/92164070
has comment: http://stackoverflow.com/comment/92163912

http://stackoverflow.com/q/52678369
score: 0
has body: I am relatively new to coding. I am trying to create a program where you are able to type information into boxes about a book. This info can either be submitted and saved into a txt file, cleared. I want you to also be able to search for books by clicking the search button where you can search for a book by typing in its name. The condition tab is meant to have the dropdown menu in with options but I can't format it. As I am new to code I expect there is plenty of problems with my code but it would be greatly appreciated if I could get some help with this. Thank you. from tkinter import * bookshopFile=open("bookshop.txt","a") root=Tk() root.geometry("1000x600") root.title("Book Shop") root.resizable(False,False) root.configure(bg="#d9e7fc") frame_heading=Frame(root) frame_heading.grid(row=0,column=0,columnspan=2, padx=100,pady=5) frame_entry=Frame(root) frame_entry.grid(row=1,column=0,columnspan=2, padx=25,pady=10) def Submit(): Book_Title_get=Book_Title.get() Author_get=Author.get() Genre_get=Genre.get() YoP=Year_of_Publication.get() Condition_get=Condition.get() bookshopFile.write(Book_Title_get+","+Author_get+", "+Genre_get+","+YoP+","+Condition_get+"\n") bookshopFile.close() def Clear(): Book_Title.delete(0,END) Author.delete(0,END) Genre.delete(0,END) Year_of_Publication.delete(0,END) Condition.delete(0,END) def Search(): Label(frame_entry,text="Name of Book").grid(row=6,column=0, padx=10,pady=0) Name_of_Book=Entry(frame_entry,width=20,bg="white") Name_of_Book.grid(row=6,column=1, padx=10,pady=0) Label(frame_heading, text= "Book Shop").grid(row=0,column=0, padx=0,pady=0) Label(frame_entry,text="Book Title").grid(row=1,column=0, padx=10,pady=0) Label(frame_entry,text="Author").grid(row=2,column=0, padx=10,pady=0) Label(frame_entry,text="Genre").grid(row=3,column=0, padx=10,pady=0) Label(frame_entry,text="Year of Publication").grid(row=4,column=0, padx=10,pady=0) Label(frame_entry,text="Condition").grid(row=5,column=0, padx=10,pady=0) Book_Title=Entry(frame_entry…
answer count: 1
tagged with: drop-down-menu
tagged with: python
has answer: http://stackoverflow.com/a/52678576
has comment: http://stackoverflow.com/comment/92285762
type: AnsweredQuestion
tagged with: tkinter
has title: I'm trying to format the dropdown menu next but it doesn't seem to be letting me
type: Question
accepted answer: http://stackoverflow.com/a/52678576

http://stackoverflow.com/comment/92403927
has text: @Willemvanonsem Thank you for your answer. However, as you can see in the code, I do not measure the time taken to serialize data and communicate through the processes (the measurements are done inside `myfunc`), so it cannot be the explanation?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52739526

http://stackoverflow.com/a/52678956
has comment: http://stackoverflow.com/comment/92286662
score: -1
answers question: http://stackoverflow.com/q/52678722
has body: If you don't have to use standard python, take a look at the json library. Besides this, you can use the builtin sorted() function python has.
type: Answer
downvote count: 2
upvote count: 1

http://stackoverflow.com/a/52643084
score: 0
answers question: http://stackoverflow.com/q/52642497
type: Answer
has body: You can use islice on the items of the Counter (which is a dict subclass so no need for dict conversion) object and then convert the sliced items to a dict using the dict constructor. For example, dict(islice(Counter('abbcccddeeff').items(), 3)) returns: (note the absence of d, e and f) {'a': 1, 'b': 2, 'c': 3}

http://stackoverflow.com/comment/92279563
type: Comment
has text: But this is the wrong outcome for n = 1... set `while j<n` instead.
comment on: http://stackoverflow.com/a/52674887
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92158639
comment on: http://stackoverflow.com/q/52609136
type: QuestionComment
type: Comment
has text: Have you tried removing the "alow all;" in the location /media section?
score: 0

http://stackoverflow.com/comment/92320822
comment on: http://stackoverflow.com/q/52642700
score: 0
type: Comment
type: QuestionComment
has text: This is a large export job. If the Database resources are busy, then it sends sigterm.

http://stackoverflow.com/a/52697554
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52695732
downvote count: 0
answers question: http://stackoverflow.com/q/52695732
upvote count: 2
type: AcceptedAnswer
has body: It is quite simple. If you click all the 'country', 'states', and 'cities' sections it moves to a certain page. In the HTML source of that page, there exists source code as below: &lt;select name="state" id="state" class="radius" required&gt; == $0 which has a list of option values of state names. Also, the next sibling of the above code is stated as: &lt;select id="city" name="city" class="radius" onchange="this.form.submit()"&gt; that has list of city names. What you have to do is iterate through the state names and get the list of the city names. Method such as .find_element_by_id and .find_element_by_name will be extremely helpful. Hope this helps!

http://stackoverflow.com/q/52656013
tagged with: pandas
has comment: http://stackoverflow.com/comment/92243900
type: Question
has body: I have a jupyter notebook .ipynb that includes the code I wrote to generate some data and a pandas dataframe. I need to deploy a web app that renders the location data and allows users to perform some basic analysis. I think Dash Framework offers everything that I am looking for. My question is how do I reference the pandas dataframe in app.py (file which includes all the front-end code for the Application) Here's a example from the site Dash - getting started. I need my application code (app.py file) to reference the pandas dataframe from the python notebook file and parse the location data and display on a map/create visualization.
tagged with: python
tagged with: jupyter-notebook
tagged with: plotly
score: 0
has comment: http://stackoverflow.com/comment/92243664
has comment: http://stackoverflow.com/comment/92261295
has comment: http://stackoverflow.com/comment/92243943
linked to: http://stackoverflow.com/q/50382248
tagged with: plotly-dash
has title: Referencing pandas dataframe in a different file
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52668862
possible better answer: http://stackoverflow.com/a/52668972
tagged with: arrays
has answer: http://stackoverflow.com/a/52669097
score: 0
answer count: 2
has title: find the index of largest, 2nd largest or third largest in a row of multidimensional array pyhton
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52668972
tagged with: python
type: AnsweredQuestion
has body: Let say I have the following two numpy arrays: a = numpy.array([[1,4,6,2,5],[3,2,7,12,1],[8,5,3,1,4],[6,10,2,4,9]]) b = numpy.array([0, 1, 4]) now, I want to first search for the index of the max value in a specific row (just say second row a[1,:]), I have another array b with some numbers in it and if the index of the max value is present as an element in the other b, i use that index number for some more calculation. If the index of max value from a row of a is not present as an element in b, I need to look for the index of the 2nd largest number, and if that index value is present in b as an element, i go for it otherwise look for the index of third largest number and so on. I do not want to sort the array a. In the above example, I have [3,2,7,12,1] in the second row.The index of the max number is 3 but that 3 is not present in b, then index of 2nd largest is 2, which is also not present in b, then i look for the index of third largest which is 0 and that is present in b. So I then assign 0 to a new variable. Any quick and fast way of doing it? Thanks in advance.
has comment: http://stackoverflow.com/comment/92267610
accepted answer: http://stackoverflow.com/a/52669097
type: Question
tagged with: numpy

http://stackoverflow.com/comment/92396194
type: Comment
type: QuestionComment
has text: Zeitkanal_Sec float64 ; Zeitkanal_Min object
comment on: http://stackoverflow.com/q/52735653
score: 0

http://stackoverflow.com/q/52690110
has comment: http://stackoverflow.com/comment/92329998
downvote count: 0
has comment: http://stackoverflow.com/comment/92308301
favorite count: 0
has comment: http://stackoverflow.com/comment/92308327
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I have a relatively simple optimisation problem of a nonlinear loss/objective function of two parameters whose algebraic solution I'm unable to find, but whose value, Jacobian and Hessian are easy to compute numerically. In fact, they are so easy to compute that I think the overhead per iteration of typical solvers/optimisers from scipy.optimize are the dominating the computation time. Since I need to perform this optimisation for a large number of parameter sets, I wonder if there is a way to optimise the performance e.g. using numba and a C-level implementation of an optimiser, or using a vectorised optimiser that can vectorise the operations.
tagged with: mathematical-optimization
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/92307679
tagged with: numeric
has comment: http://stackoverflow.com/comment/92326346
tagged with: scipy
has title: Efficient (e.g. vectorised) numerical solution of many parameter-sets of a low-dimensional nonlinear optimisation problem
type: Question
tagged with: numpy

http://stackoverflow.com/q/52673733
has comment: http://stackoverflow.com/comment/92277502
has comment: http://stackoverflow.com/comment/92277347
type: UnansweredQuestion
type: Question
score: 3
has body: I can't figure out what it is but the ipython repl does not accept multiline statement blocks. For ex., when I try to write a for loop, I can only enter the first line after the loop statement but subsequently pressing enter simply executes the statement instead of allowing another line. In [2]: if x == 0: ...: print(x) 0 I'm unable to extend the for loop by entering more lines in that block. What is strange is that, if I use ipython v5 (which uses python 2.7), I don't have this problem. It only seems to be specific to ipython3 I'm on macOS Mojave, in iTerm2 (although I have the same problem in terminal as well) I've tried installing ipython3 via pip3 install ipython and ipython via homebrew brew install ipython, but nothing seems to work. What am I missing here?
tagged with: ipython
upvote count: 3
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
tagged with: macos
has title: Cannot create multiline statement blocks in ipython3 on macOS
has answer: http://stackoverflow.com/a/52675564
tagged with: python-3.x

http://stackoverflow.com/a/52687723
downvote count: 0
upvote count: 8
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/52687686
answers question: http://stackoverflow.com/q/52687686
has comment: http://stackoverflow.com/comment/92302570
has body: As the error suggests, getpeername returns a tuple. To get the IP you should simply take the first element: ip = socket.getpeername()[0]
type: AcceptedAnswer

http://stackoverflow.com/comment/92322680
comment on: http://stackoverflow.com/q/52691128
type: Comment
has text: I rolled back your edit as you shouldn't *change* your question in substance after you have answer(s). Instead, ask a new question with a **[mcve]** so that these problems don't occur.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92209874
score: 0
type: Comment
type: QuestionComment
has text: In Python there can be functions without classes and the names enclosed in double underscores have special meanings by convention.
comment on: http://stackoverflow.com/q/52637766

http://stackoverflow.com/a/52659255
has comment: http://stackoverflow.com/comment/92250322
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92249982
has comment: http://stackoverflow.com/comment/92251246
answers question: http://stackoverflow.com/q/52620202
has body: @blhsing has given a nice approach. But I ended up solving my issue using pprint.pprint in my function and disabling the outputs of print. This works because pprint uses more low level stream.write("...") instead of bootstrapping on print. The code: def disable_prints(f): @functools.wraps(f) def decorated(*args, **kwargs): global print # Disable all calls made to print(...) by relacing stdout with devnull print = functools.partial(print, file=open(os.devnull, 'w')) f_returns = f(*args, **kwargs) # Restore back print = functools.partial(print, file=sys.stdout) return f_returns return decorated so that: def func(): print("Inside func") @disable_prints def my_func(): pprint("Starting inside my_func") func() pprint("In my_func") func() my_func() would output: Starting inside my_func In my_func

http://stackoverflow.com/comment/92414935
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52742770
has text: @Jean-FrançoisFabre Well, there really is no reason why it's necessary to pass *3* arguments to that function. If a function like `print_exception(ex)` existed, that would be much nicer.
score: 10

http://stackoverflow.com/a/52628582
score: 0
has body: A few issues in your code. usersFileLength = len(text_file_name) That's just the length of the name of the file. Not the size of the file's contents. firstChar = usersFile[i] This is not how you read from a file. You need to use a function like read(). Also, you break a couple of the (silly) constraints. Here's my solution. It reads the entire file then goes through it char-by char. It builds the current word and when it reaches a non-letter it compares. def count_text_file(search_for, text_file_name): with open(text_file_name, 'r') as users_file: # Read entire file content = users_file.read() line_number = 1 # Build the words of the file char-by-char current_word = "" while len(content) &gt; 0: # "only use indexing to access the first character of a string" c = content[0] # If it's a letter add to string # Can't use c.isalpha() as it is a "python string method" if (c &gt;= 'A' and c &lt;= 'Z') or (c &gt;= 'a' and c &lt;= 'z'): current_word += c # Else (not a letter), check the word else: if current_word == search_for: print(f"found at line {line_number}") if c == '\n': line_number += 1 # Reset for next word current_word = "" # "only use ... slicing to get the tail of the string" content = content[1:] There are some improvements you can do. For example, words with punctuation in them won't be found (ex: "can't" or "non-existent"). Also, it only considers a "letter" to be "[A-Za-z]". Unicode characters won't be recognized. And it is case sensitive. But since this is an assignment, who knows if your teacher cares about any of that.
type: Answer
has comment: http://stackoverflow.com/comment/92224972
answers question: http://stackoverflow.com/q/52615251

http://stackoverflow.com/q/52594207
has comment: http://stackoverflow.com/comment/92126895
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92126925
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92129339
score: 1
has title: How to skip rest of arguments if specific add_argument is selected using argparse?
type: Question
tagged with: python-2.7
tagged with: argparse
downvote count: 0
has body: try: parser = argparse.ArgumentParser(description='Note: -un is not mandatory', usage='use "python %(prog)s -h" for help\nNote: *** Astericks represent mandatory fields', formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-re', '--regard', required=True, # choices=['Prod', 'Dev', 'Test'], type=str, help='* Rancher Environment Pass') parser.add_argument('-g', '--group_names', # required=False, type=str, help='* Group Name(s) - Specify the group names using comma separated values (no spaces permitted) - ex: group1, group2, group3') parser.add_argument('-un', '--user_names', type=str, help='Username(s) - Specify the group names using comma separated values (no spaces permitted) - ex: user1, user2, user3') args = parser.parse_args() sys.exit() except: parser = argparse.ArgumentParser(description='Note: -un is not mandatory', usage='use "python %(prog)s -h" for help\nNote: *** Astericks represent mandatory fields', formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-u', '--env', required=True, choices=['Prod', 'Dev', 'Test'], help='* Rancher Environment --&gt; Prod/Dev/Test') parser.add_argument('-b', '--business_unit', required=True, type=str, help='* The Business Unit you choose to use --&gt; "PFE Business Unit, ex: FBO, R&amp;D, PGS, PCH"') parser.add_argument('-p', '--project_name', required=True, type=str, help='* The Project Name you choose to use --&gt; Project Name') parser.add_argument('-e', '--app_environment_name', required=True, type=str, help='* The Application Environment Name you choose to use --&gt; Application Environment, ex Prod, Dev, DR, Test, Staging') parser.add_argument('-g', '--group_names', required=True, type=str, help='* Group Name(s) - Specify the group names using comma separated values (no spaces permitted) - ex: group1, group2, group3') parser.add_argument('-un', '--user_names', type=str, help='Username(s) - Specify the group names using comma separated values (no spaces permitted) - ex: user1, user2, user3…

http://stackoverflow.com/q/52734213
tagged with: django
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/38627393
has comment: http://stackoverflow.com/comment/92393355
type: Question
has body: I just started playing around with Django and the JavaScript in my static files don't seem to load, while other another resources like logo.png seems to load fine. Am I missing something really basic? Or what I am doing wrong? My setup Using Docker with Python 3.5 with and Django 2.1 as described here My static files are in app\static\app as described here I have a JavaScript file (d3.js) and an image (logo.png) in the above directory In my template I have In settings.py I have DEBUG = True (default) On a Windows environment Tried solutions I can find the files with python manage.py findstatic app/d3.js I tried adding STATICFILES_DIRS as suggested here, but that didn't seem to work. Directory ├───project │ └───__pycache__ └───app ├───migrations │ └───__pycache_ ├───static │ └───app ├───templates │ └───app └───__pycache__ HTML {% extends 'app/base.html' %} {% load static %} {% block content %} {% endblock %} Edit: Seems to work when I change the HTML into
has comment: http://stackoverflow.com/comment/92395629
tagged with: javascript
has comment: http://stackoverflow.com/comment/92393300
tagged with: docker
score: 0
has comment: http://stackoverflow.com/comment/92393559
accepted answer: http://stackoverflow.com/a/52737446
answer count: 1
has title: Django - JavaScript from static files not loading, but other resources are
has answer: http://stackoverflow.com/a/52737446

http://stackoverflow.com/comment/92291561
comment on: http://stackoverflow.com/q/52681511
score: 0
type: Comment
type: QuestionComment
has text: @RobinZigmond Hi Robin. Is there an alternate way to get this data that I can look into? Thanks.

http://stackoverflow.com/comment/92247236
type: Comment
type: QuestionComment
has text: Thank you for your solutions. I solved my loop problem
comment on: http://stackoverflow.com/q/52603377
score: 0

http://stackoverflow.com/comment/92343130
score: 0
has text: Maybe another dupe of [Why do backslashes appear twice?](https://stackoverflow.com/questions/24085680/why-do-backslashes-appear-twice)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52708397

http://stackoverflow.com/q/52692150
favorite count: 0
has comment: http://stackoverflow.com/comment/92311247
has answer: http://stackoverflow.com/a/78328318
type: Question
has comment: http://stackoverflow.com/comment/92311259
has title: Converting TIFF to numpy array
tagged with: python
has body: I am currently working on transforming a TIFF file to a numpy array. A simple working code is from PIL import Image photo = Image.open("filename.tif") photo.show() Although I do get as an output the picture, I am getting the error TIFFSetField: tempfile.tif: Unknown pseudo-tag 65538. Moreover, when I try data = np.array(photo) print(data) I am getting the output [[[ 0 0 0 255] [ 0 0 0 255] [ 0 0 0 255] ... [ 0 0 0 255] [ 7 7 7 255] [ 7 7 7 255]] [[ 0 0 0 255] [ 0 0 0 255] [ 0 0 0 255] ... [ 0 0 0 255] [ 0 0 0 255] [ 0 0 0 255]] [[ 5 5 5 255] [ 0 0 0 255] [ 0 0 0 255] ... [ 0 0 0 255] [ 0 0 0 255] [ 0 0 0 255]] ... [[ 0 0 0 255] [ 0 0 0 255] [ 0 0 0 255] ... [ 1 1 1 255] [ 0 0 0 255] [ 3 3 3 255]] [[ 0 0 0 255] [ 0 0 0 255] [ 0 0 0 255] ... [ 11 11 11 255] [ 0 0 0 255] [ 0 0 0 255]]] which I am pretty sure does not reflect the information of the image. Any ideas to what may cause this error? I would prefer if I didn't have to upload the image file.
has answer: http://stackoverflow.com/a/70229480
upvote count: 3
has answer: http://stackoverflow.com/a/52692982
answer count: 3
tagged with: numpy
tagged with: tiff
has comment: http://stackoverflow.com/comment/92311593
tagged with: python-imaging-library
type: UnansweredQuestion
tagged with: image
score: 3
downvote count: 0

http://stackoverflow.com/comment/92283435
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52677230
has text: *"I will never need multiple player objects"* One thing I've learned about requirements is that they change even if you don't expect them to, so never say never. Is it really unthinkable that you'll add a multiplayer mode someday?

http://stackoverflow.com/comment/92346849
type: QuestionComment
has text: what about from Django itself, like in the console that is running `python manage.py runserver`
score: 2
comment on: http://stackoverflow.com/q/52710305
type: Comment

http://stackoverflow.com/q/52615425
downvote count: 1
has answer: http://stackoverflow.com/a/52881574
favorite count: 0
has answer: http://stackoverflow.com/a/54947575
answer count: 3
type: UnansweredQuestion
has body: I have some matplotlib graphs that need to be viewed offline in a browser, I was using MPLD3 to render them before, but given the need to view the plots without an internet connection, I'm considering using plotly. Is there a way to view matplotlib plotly graphs offline?
tagged with: python
upvote count: 8
type: Question
tagged with: plotly
score: 7
has answer: http://stackoverflow.com/a/56361966
tagged with: matplotlib
has title: Matplotlib to plotly offline
tagged with: raspberry-pi

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/52690994
type: Tag
tags question: http://stackoverflow.com/q/52727032
tags question: http://stackoverflow.com/q/52608995
tags question: http://stackoverflow.com/q/52737595
tags question: http://stackoverflow.com/q/52590383
tags question: http://stackoverflow.com/q/52707238
tags question: http://stackoverflow.com/q/52651677
tags question: http://stackoverflow.com/q/52740002
tags question: http://stackoverflow.com/q/52733087
tags question: http://stackoverflow.com/q/52725076
tags question: http://stackoverflow.com/q/52591299
tags question: http://stackoverflow.com/q/52597414
tag name: csv
tags question: http://stackoverflow.com/q/52643870
tags question: http://stackoverflow.com/q/52708297
tags question: http://stackoverflow.com/q/52702669
tags question: http://stackoverflow.com/q/52667035
tags question: http://stackoverflow.com/q/52595408
tags question: http://stackoverflow.com/q/52606022
tags question: http://stackoverflow.com/q/52597437
tags question: http://stackoverflow.com/q/52714303
tags question: http://stackoverflow.com/q/52696176
tags question: http://stackoverflow.com/q/52608848
tags question: http://stackoverflow.com/q/52699385
tags question: http://stackoverflow.com/q/52729569
tags question: http://stackoverflow.com/q/52616803
tags question: http://stackoverflow.com/q/52691634
tags question: http://stackoverflow.com/q/52596332
tags question: http://stackoverflow.com/q/52677922
tags question: http://stackoverflow.com/q/52638991
tags question: http://stackoverflow.com/q/52593926
tags question: http://stackoverflow.com/q/52617427
tags question: http://stackoverflow.com/q/52640088
tags question: http://stackoverflow.com/q/52600305
tags question: http://stackoverflow.com/q/52747035
tags question: http://stackoverflow.com/q/52606526
tags question: http://stackoverflow.com/q/52707006
tags question: http://stackoverflow.com/q/52658773
tags question: http://stackoverflow.com/q/52680199
tags question: http://stackoverflow.com/q/52623218
tags question: http://stackoverflow.com/q/52671142
tags question: http://stackoverflow.com/q/52613747
tags question: http://stackoverflow.com/q/52731336
tags question: http://stackoverflow.com/q/52680031
tags question: http://stackoverflow.com/q/52671959
tags question: http://stackoverflow.com/q/52627863
tags question: http://stackoverflow.com/q/52662585
tags question: http://stackoverflow.com/q/52653144
tags question: http://stackoverflow.com/q/52665228
tags question: http://stackoverflow.com/q/52739307
tags question: http://stackoverflow.com/q/52610116
tags question: http://stackoverflow.com/q/52729483
tags question: http://stackoverflow.com/q/52594895
tags question: http://stackoverflow.com/q/52673574
tags question: http://stackoverflow.com/q/52669094
tags question: http://stackoverflow.com/q/52657522
tags question: http://stackoverflow.com/q/52639381
tags question: http://stackoverflow.com/q/52709750
tags question: http://stackoverflow.com/q/52664730
tags question: http://stackoverflow.com/q/52607862
tags question: http://stackoverflow.com/q/52604298
tags question: http://stackoverflow.com/q/52622905
tags question: http://stackoverflow.com/q/52642233
tags question: http://stackoverflow.com/q/52641121
tags question: http://stackoverflow.com/q/52628596
tags question: http://stackoverflow.com/q/52633819
tags question: http://stackoverflow.com/q/52629275
tags question: http://stackoverflow.com/q/52708397
tags question: http://stackoverflow.com/q/52668335
tags question: http://stackoverflow.com/q/52616281
tags question: http://stackoverflow.com/q/52682156
tags question: http://stackoverflow.com/q/52664136
tags question: http://stackoverflow.com/q/52602118
tags question: http://stackoverflow.com/q/52601808
tags question: http://stackoverflow.com/q/52712201
tags question: http://stackoverflow.com/q/52692345
tags question: http://stackoverflow.com/q/52597678
tags question: http://stackoverflow.com/q/52666182
tags question: http://stackoverflow.com/q/52744755

http://stackoverflow.com/comment/92165397
type: QuestionComment
comment on: http://stackoverflow.com/q/52615493
score: 0
type: Comment
has text: When you call `.shift()` without an `axis` parameter, it defaults to row-wise shifting, which means for your first calculation, you're trying to divide `2018-09-27` by `104.05` which is a meaningless operation

http://stackoverflow.com/q/52635688
tagged with: selenium
has comment: http://stackoverflow.com/comment/92333051
type: Question
tagged with: heroku
linked to: http://stackoverflow.com/q/41059144
has body: I'm running Selenium (really Splinter) in Python on a Heroku server. I need to run it through a proxy server, but most options for proxies seem to work only with Firefox, which can't run on Heroku. I've been trying to use the QuotaGuard addon by just adding an argument to chrome options, but it only results in getting blank web pages. Here's the setup (using the chromedriver/Google Chrome buildbacks, which place the bin in GOOGLE_CHROME_SHIM): chrome_bin = os.environ.get('GOOGLE_CHROME_SHIM', None) opts = ChromeOptions() opts.add_argument("proxy-server=SOME_URL") opts.binary_location = chrome_bin with Browser('chrome', executable_path="chromedriver", options=opts) as browser: # Do stuff What's the best way to basically have it run through another IP address? Is there another way to do that that's not a proxy server?
has comment: http://stackoverflow.com/comment/92298416
tagged with: proxy
score: 0
tagged with: python
tagged with: selenium-chromedriver
has title: Running Selenium+Chromedriver through a proxy?
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/92256109
comment on: http://stackoverflow.com/q/52663040
has text: Please give example inputs to your functions. It's not clear what you mean by `array`. Do you mean NumPy array? XArray? List? Something else?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52633468
has comment: http://stackoverflow.com/comment/92201349
type: Question
possible better answer: http://stackoverflow.com/a/52634204
has comment: http://stackoverflow.com/comment/92200449
has answer: http://stackoverflow.com/a/52671486
upvote count: 2
answer count: 3
has title: Print each line of json in new .json file using Python
has body: I have a json file; I need to remove the id key from the content, which I can do with my code. Now I want to print each line of the json file in a new file and use the name filed in my json for the file name. My json file ex: {"categories":["Test"],"indications":[{"@class":"=indication.BuildLogIndication","pattern":".*TypeError .*"},{"@class":"model.indication.BuildLogIndication","pattern":".*LoadError .*"}],"modifications":[{"time":{"$date":"2015-10-08T20:01:54.075Z"}},{"user":"user1","time":{"$date":"2015-03-04T18:38:58.123Z"}},{"user":"user2","time":{"$date":"2014-11-13T01:54:13.906Z"}},{"time":{"$date":"2014-09-02T18:48:05.000Z"}}],"lastOccurred":{"$date":"2017-01-25T20:05:17.180Z"}} {"pattern":".*look for this string.*"}],"modifications":[{"time":{"$date":"2014-09-02T18:52:20.000Z"}}],"lastOccurred":{"$date":"2014-11-04T00:43:32.945Z"},"_removed":{"timestamp":{"$date":"2014-11-13T01:52:44.346Z"},"by":"user3"},"active":false} Code for removing id: import json import sys import re import fileinput infile = "failure.json" outfile = "failure1.json" fin = open(infile) fout = open(outfile, "w+") for line in fin: for word in line: line = re.sub("\"_id.*?},","", line) fout.write(line) file.write("%d\n" % n) fin.close() fout.close()
has comment: http://stackoverflow.com/comment/92200713
downvote count: 1
linked to: http://stackoverflow.com/q/12451431
favorite count: 0
has answer: http://stackoverflow.com/a/52634204
linked to: http://stackoverflow.com/q/5844672
has answer: http://stackoverflow.com/a/52634345
accepted answer: http://stackoverflow.com/a/52634345
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92272734
score: 1
linked to: http://stackoverflow.com/q/1276764
tagged with: http://stackoverflow.com/tag/json
tagged with: loops

http://stackoverflow.com/q/52632601
has answer: http://stackoverflow.com/a/52632660
answer count: 2
has title: How to serve a zip file download in Django?
has answer: http://stackoverflow.com/a/52634223
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/52634223
tagged with: django
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/52632660
has body: I have a zip file stored in the Django project directory. How can I serve it to users for downloading.
type: Question

http://stackoverflow.com/q/52601383
score: 2
has comment: http://stackoverflow.com/comment/92212610
type: Question
has comment: http://stackoverflow.com/comment/92212765
downvote count: 0
favorite count: 0
tagged with: python-2.7
tagged with: pycharm
answer count: 0
has title: How to recognize google.appengine from PYTHONPATH in PyCharm
has body: When I started using PyCharm, it does not recognize only google.appengine . It says Unresolved references . I thought it automatically read my PYTHONPATH in launch. My PYTHONPATH is below. /Users/taichi/google-cloud-sdk/platform/google_appengine/:/Users/taichi/myrepo/api/ I use virtualenv to set up the environment. My project interpreter is this, but what is wrong?
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92185267
tagged with: python

http://stackoverflow.com/q/52650583
upvote count: 7
has answer: http://stackoverflow.com/a/60976630
has comment: http://stackoverflow.com/comment/92233094
has comment: http://stackoverflow.com/comment/92234026
accepted answer: http://stackoverflow.com/a/52653324
downvote count: 1
has comment: http://stackoverflow.com/comment/92233178
has comment: http://stackoverflow.com/comment/92237881
tagged with: performance
has body: I have a list, say: NUM = 100 my_list = list(range(NUM)) I would like to generate a dict where the key is equal to the value, something like: my_dict = {item: item for item in my_list} or: my_dict = dict(zip(my_list, my_list)) I have run some micro-benchmarks, and it looks like they have similar speed, but I was hoping that the second would be much faster, since the looping should be happening in C. For example, the following construct: my_dict = {key: SOMETHING for key in keys} translates into the much faster: my_dict = dict.fromkeys(k, SOMETHING) So, my question is: is there any similar such construct for {x: x for x in my_list}? EDIT I have checked dir(dict) and there seems to be nothing in this direction (I would expect it to be called something like dict.fromitems()). EDIT 2 A method like dict.fromitems() would have a broader application than this specific use-case, because: dict.fromitems(keys, values) could, in principle substitute both: {k, v for k, v in zip(keys, values)} and: dict(zip(keys, values))
has comment: http://stackoverflow.com/comment/92233243
score: 6
has title: Fastest way to generate a dict from list where key == value
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92233236
has answer: http://stackoverflow.com/a/52651292
favorite count: 0
has comment: http://stackoverflow.com/comment/92233431
linked to: http://stackoverflow.com/q/2912231
type: Question
has comment: http://stackoverflow.com/comment/92233519
has comment: http://stackoverflow.com/comment/92233597
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/92233871
has answer: http://stackoverflow.com/a/52653324
has comment: http://stackoverflow.com/comment/92233391
tagged with: list
linked to: http://stackoverflow.com/q/38987
has comment: http://stackoverflow.com/comment/92233229
has comment: http://stackoverflow.com/comment/92237834
possible better answer: http://stackoverflow.com/a/60976630
answer count: 3

http://stackoverflow.com/comment/92191740
type: Comment
comment on: http://stackoverflow.com/a/52629170
score: 0
type: AnswerComment
has text: No need for an intermediary list eating memory. Use a generator expression instead (and divide by the length of `student_data`).

http://stackoverflow.com/comment/92261584
has text: Have you had a look into Anaconda? Basically you need to install the interpreter. Anaconda handles dependencies for you (including interpreter install).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52665950

http://stackoverflow.com/comment/92145585
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52605666
has text: Oh, sorry, I input the filename plus extension: "mbox.txt".
score: 0

http://stackoverflow.com/comment/92261295
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52656013
has text: Here's a response from the Dash community forum: https://community.plot.ly/t/reference-pandas-dataframe-in-app-py-dash-file/14251/2

http://stackoverflow.com/q/52745313
tagged with: python
has body: I'm using a raspberry pi 3 and python 2.7 with requests to post data to my lamp server. All works great except for intermittent posting errors which are trapped requests.exceptions.ConnectTimeout. BTW, timeout=0.5 sec which is 2.5x the posting time (0.2 sec). See code below. When the request exception occurs, I check for internet access using CheckConnection(). BTW, this takes only 0.016 sec on pi;so fast compared to other techniques. When False, it doesn't retry posting and logs data locally. However, I can connect remotely to the Pi using TeamViewer while this is happening! I am posting data to our server with other installations so it is not a cloud server down issue. After several to many minutes, the issue resolves itself and posting resumes like nothing was wrong. Any suggestions to how I can change my code is most welcomed either to determine the root cause or fix the issue. Thank you in advance. ******** CODE ************ def PostData(payload,retry_count=3): url = 'http://xxx.xxx.xxx.xxx/api/data/push/' try: response = requests.post(url,params=payload,timeout=0.5) if response.status_code == 200: return response.text response.raise_for_status() except (requests.exceptions.RequestException, requests.exceptions.ConnectTimeout) as e: print "Post Error..." x = CheckConnection() if x==False: return "Internet for Posting: " + str(x) if retry_count &gt;0: Reason = "Post Settings Retry: " + str(retry_count) print Reason #sleeptime = 0.05*2**(3-retry_count) #time.sleep(sleeptime) return PostData(payload, retry_count-1) if retry_count==0: Reason = "Error! Post settings retry failed. Retry=0. Internet: " + str(x) return Reason return None except Exception as e: x = CheckConnection() Reason= "Error! Posting Exception: " + str(e) + "Internet: " + str(x) print Reason return None def CheckConnection(host="8.8.8.8",port=53,timeout=0.5): try: socket.setdefaulttimeout(timeout) socket.socket(socket.AF_INET,socket.SOCK_STREAM).connect((host,port)) return True except Exception: r…
answer count: 0
tagged with: python-requests
type: Question
has title: Strange Intermittent posting issue using python requests
tagged with: teamviewer
has comment: http://stackoverflow.com/comment/92418772
score: 0
has comment: http://stackoverflow.com/comment/92528577
tagged with: raspberry-pi3
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/a/52686444
has comment: http://stackoverflow.com/comment/92302059
has comment: http://stackoverflow.com/comment/92305101
has comment: http://stackoverflow.com/comment/92301783
has comment: http://stackoverflow.com/comment/92303356
score: 0
has body: In your views.py, class classname(LoginRequiredMixin, View): form_class = #addformname template_name = #addtemplatename def get(self, request): --- def post(self, request): form = self.form_class(request.POST, #add request.FILES if you are adding file) if form.is_valid(): project = form.save(commit = False) #this is missing in your views project.user = self.request.user #add all your cleaned_data project.save() return redirect(#add the path)
type: Answer
has comment: http://stackoverflow.com/comment/92301954
has comment: http://stackoverflow.com/comment/92301792
has comment: http://stackoverflow.com/comment/92305239
answers question: http://stackoverflow.com/q/52682163
has comment: http://stackoverflow.com/comment/92302850
has comment: http://stackoverflow.com/comment/92301619

http://stackoverflow.com/comment/92398823
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52736754
has text: How did you do that?
score: 0

http://stackoverflow.com/a/52658253
accepted answer of: http://stackoverflow.com/q/52658116
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52658116
type: Answer
has body: You don't necessarily need a class. You can always just hold all your tanks in a dict and update/display the state of your tanks by accessing those properties. tanks = {} tanks['tankA'] = {'name': 'Tank A', 'mode': 'clean'} tanks['tankB'] = {'name': 'Tank B', 'mode': 'dirty'} for t in tanks: print('{} is {}'.format(tanks[t]['name'], tanks[t]['mode'])) print('updating Tank A mode...') tanks['tankA']['mode'] = 'dirty' for t in tanks: print('{} is {}'.format(tanks[t]['name'], tanks[t]['mode'])) The result would look like this: Tank A is clean Tank B is dirty updating Tank A mode... Tank A is dirty Tank B is dirty The dict looks like this: {'tankA': {'name': 'Tank A', 'mode': 'dirty'}, 'tankB': {'name': 'Tank B', 'mode': 'dirty'}} You could then create methods to update your dict in certain ways based on your own logic. Hope this helps.
score: 0
has comment: http://stackoverflow.com/comment/92264753

http://stackoverflow.com/q/52742779
type: Question
answer count: 2
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92410258
tagged with: python
has title: Parsing a text file using pandas dataframe
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52742832
has body: I have the following csv file: Filesystem,Size,Used,Avail,Use,Mounted,on /dev/sda3,196G,124G,63G,67,/ tmpfs,32G,144K,32G,1,/dev/shm /dev/sda1,194M,42M,143M,23,/boot I'm reading the file using the following code: df = pandas.read_csv(tempFolder+"diskSpace.txt", sep=',',header=None) I tried to print the Use column with three different approaches: print(df[Use]) print(df['Use']) print(df["Use"]) It fails to print the Use column
has comment: http://stackoverflow.com/comment/92410468
has answer: http://stackoverflow.com/a/52742971

http://stackoverflow.com/q/52676117
favorite count: 0
tagged with: python-3.x
has body: I tried printing various integers (ie. int | int ) multiple times and I can't seem to establish a working pattern of values. How does 1|2 return 3, but 2|3 also returns 3?
type: UnansweredQuestion
downvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/3929278
answer count: 4
has title: Trying to learn how bitwise or operator | works for python, and I'm wondering why 1 | 2 == 3?
type: Question
has comment: http://stackoverflow.com/comment/92281485
score: -1
has answer: http://stackoverflow.com/a/52676183
has comment: http://stackoverflow.com/comment/92281495
has answer: http://stackoverflow.com/a/52676153
duplicate of: http://stackoverflow.com/q/3929278
has answer: http://stackoverflow.com/a/52676178
upvote count: 1
has answer: http://stackoverflow.com/a/52676166

http://stackoverflow.com/comment/92208435
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52637617
type: QuestionComment
has text: I see what you're saying. Perhaps I am asking the wrong question. I can see there are a few parts to the question. Determining if I'm on an interactive TTY is part of it, determining if there are files in the program arguments is another. I guess I the issue is between fileinput (which hides a bunch of implementation), and TTY input (which fileinput doesn't cater for out of the box).

http://stackoverflow.com/comment/92412041
comment on: http://stackoverflow.com/q/52731407
score: 0
type: QuestionComment
has text: @lagom, the CMD shell's `echo` command has nothing to do with the console echoing input. The closest the Windows command line has to stty is mode.com, but it only controls a small subset of console modes for compatibility with old batch scripts.
type: Comment

webdriverwait
tags question: http://stackoverflow.com/q/52598793
tags question: http://stackoverflow.com/q/52688693
tag name: webdriverwait
tags question: http://stackoverflow.com/q/52603847
type: Tag
tags question: http://stackoverflow.com/q/52600350
tags question: http://stackoverflow.com/q/52673842
tags question: http://stackoverflow.com/q/52668844

http://stackoverflow.com/comment/92310569
comment on: http://stackoverflow.com/a/52691477
type: Comment
has text: You can get rid of that print statement, It was just for informing and anyways It isn't for this topic.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52636899
tagged with: reinforcement-learning
has answer: http://stackoverflow.com/a/53485133
score: 7
favorite count: 0
tagged with: python-3.x
upvote count: 8
type: Question
tagged with: machine-learning
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/116176977
has body: I am implementing value iteration on the gym CartPole-v0 environment and would like to record the video of the agent's actions in a video file. I have been trying to implement this using the Monitor wrapper but it generates json files instead of a video file in the recording directory. This is my code: env = gym.make('FrozenLake-v0') env = gym.wrappers.Monitor(env, 'recording', force=True) env.seed(0) optimalValue = valueIteration(env) st = time.time() policy = cal_policy(optimalValue) policy_score = evaluate_policy(env, policy) et = time.time() env.close() print('Best score: %.2f Time: %4.4f sec' % (policy_score, et-st)) monitoring json files I have followed this tutorial but not sure what is wrong. I have Googled a lot but haven't come across anything that could be useful.
tagged with: openai-gym
has title: python OpenAI gym monitor creates json files in the recording directory
downvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/52717235
upvote count: 0
accepted answer: http://stackoverflow.com/a/52717273
score: -1
has comment: http://stackoverflow.com/comment/92360006
answer count: 1
has comment: http://stackoverflow.com/comment/92360237
has comment: http://stackoverflow.com/comment/92434002
favorite count: 0
linked to: http://stackoverflow.com/q/9979970
tagged with: python
has title: A prime number checker that fails
has answer: http://stackoverflow.com/a/52717273
tagged with: calculation
has body: It seems like a normal code and works well, but for whatever reasons when I try entering this number = 18765411123451, computer seems to freeze, any clue? num = 18765411123451 if num &gt; 1: for i in range(2,num): if num % i == 0: print(num,"is not a prime number") print("Because", i,"x",num//i, "=" ,num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") I've tried many other numbers and the code works as it should except that number. What happened here?
type: AnsweredQuestion
tagged with: numbers
has comment: http://stackoverflow.com/comment/92427042
has comment: http://stackoverflow.com/comment/92359904
downvote count: 1
has comment: http://stackoverflow.com/comment/92359967
type: Question

apache-spark
tags question: http://stackoverflow.com/q/52730907
tags question: http://stackoverflow.com/q/52622076
tags question: http://stackoverflow.com/q/52742287
tags question: http://stackoverflow.com/q/52720282
tags question: http://stackoverflow.com/q/52598878
tags question: http://stackoverflow.com/q/52699765
tags question: http://stackoverflow.com/q/52702282
tags question: http://stackoverflow.com/q/52645253
tags question: http://stackoverflow.com/q/52649030
tags question: http://stackoverflow.com/q/52675628
tags question: http://stackoverflow.com/q/52609143
tag name: apache-spark
tags question: http://stackoverflow.com/q/52702407
tags question: http://stackoverflow.com/q/52685346
tags question: http://stackoverflow.com/q/52713466
tags question: http://stackoverflow.com/q/52696414
tags question: http://stackoverflow.com/q/52734739
tags question: http://stackoverflow.com/q/52597455
tags question: http://stackoverflow.com/q/52719122
tags question: http://stackoverflow.com/q/52596370
tags question: http://stackoverflow.com/q/52606022
tags question: http://stackoverflow.com/q/52667863
tags question: http://stackoverflow.com/q/52616254
tags question: http://stackoverflow.com/q/52685609
type: Tag
tags question: http://stackoverflow.com/q/52673621
tags question: http://stackoverflow.com/q/52633549
tags question: http://stackoverflow.com/q/52695236

http://stackoverflow.com/q/52641676
type: Question
has title: How to use values from variables imported from another file python
has comment: http://stackoverflow.com/comment/92216164
score: 0
has comment: http://stackoverflow.com/comment/92215726
answer count: 3
has answer: http://stackoverflow.com/a/52641754
has comment: http://stackoverflow.com/comment/92215690
has comment: http://stackoverflow.com/comment/92217859
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52641782
has body: so I know this has been asked in several forms before, but I cannot relate to any of those, either I have something different or I just don't understand them. The problem is I have script A and script B, and in script A I calculate and have all the variables I want to use in script B. Script A has various functions, let's say for now I just want to pass a simple number from a variable in script A to script B , let's call the variable value . I used from script_A import value . Now, I have value initialized in script_A with 0 right at the top to say so, but script_A processes value, and gets a result clearly different from 0, but when I debug, I am getting in script_B value == 0, and not value == calculated_value_that_should_be_there. I did not know what to do so I tough about scope,so I put it in the return of a function, I tried making variable value a Global variable. Nothing seems to work in the way that I am not passing the calculated 'value' but I am passing to script_B that 0 initialization. P.S last thing I tried and what I saw from this topic is to import script_A as it was said with no namespaces. This has worked. When I write script_A.value it is calculated_value_that_should_be_there. But, I do not know why anything else that I described did not work. script_A from definitions import * variable_1 = 0 variable_2 = 0 variable_3 = 0 variable_4 = 0 total = 0 respected = 0 time_diff = {} seconds_all_writes = "write" class Detect(): def __init__(self, data_manager, component_name, bus_name_list=None): def __Function_A(self): """ global time_diff global seconds_all_writes process script_B: from script_A import respected from script_A import total import script_A print aln_mon_detector.total print aln_mon_detector.respected I also want a dictionary table_content.append(script_A.time_diff[file[script_A.seconds_all_writes]) I get KeyError: 'writes'
has answer: http://stackoverflow.com/a/52641809
tagged with: file
tagged with: import

http://stackoverflow.com/comment/92221386
score: 1
comment on: http://stackoverflow.com/q/52644377
type: Comment
type: QuestionComment
has text: @Paul The `+` in `a+` stands for "open a disk file for updating (reading and writing)", so it makes sense that `a+` provides `.read`

http://stackoverflow.com/comment/92304757
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52687616
has text: `1 ≤ Size(A) ≤ 32` does indicate that A will always have at least 1 element. And `1 ≤ Ai ≤ 32` means you don't have to worry about A containing zero. So at this point, I don't know what to suggest.
type: Comment

http://stackoverflow.com/a/52681051
score: 0
has body: you could probably try something like this : &gt;&gt;&gt; dftemp = pd.DataFrame({'a': [1] * 3 + [2] * 2 + [3]*1, 'b': 'a a b c d e'.split()}) &gt;&gt;&gt; dftemp a b 0 1 a 1 1 a 2 1 b 3 2 c 4 2 d 5 3 e &gt;&gt;&gt; dftemp.groupby('a')['b'].apply(lambda df: df.reset_index(drop=True)).unstack() 0 1 2 a 1 a a b 2 c d None 3 e None None
answers question: http://stackoverflow.com/q/52680963
type: Answer

http://stackoverflow.com/comment/92225976
type: QuestionComment
type: Comment
has text: From what I get, it's always 8 digits, 1 space and 1 bar, right?
comment on: http://stackoverflow.com/q/52646581
score: 0

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/52722864

http://stackoverflow.com/comment/92372187
score: 1
has text: What defines a point as being "too far off the current average"?
comment on: http://stackoverflow.com/q/52723340
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92266767
comment on: http://stackoverflow.com/a/52668230
type: AnswerComment
score: 0
has text: I tried this but using `print(items)` instead of `return items` and now I don't get the error message, but nothing is printed... do you know why?
type: Comment

http://stackoverflow.com/comment/92387470
comment on: http://stackoverflow.com/q/52731171
score: 0
type: QuestionComment
type: Comment
has text: Do I need to round it off? Like an extra function to detect 0.999~ then round it off.

http://stackoverflow.com/a/52646278
answers question: http://stackoverflow.com/q/52643973
score: 0
type: Answer
has body: The best solution is to use State and not Input and then you will have only one function callback. this State could be assigned to a submit button and then when the user choose one Input between Dropdown or textbox and click on button the update will be done.

http://stackoverflow.com/q/52687450
upvote count: 2
type: UnansweredQuestion
tagged with: sockets
tagged with: multithreading
tagged with: python
score: 2
type: Question
downvote count: 0
has body: I would like to write a very simple rock-paper-scissors game in Python. I would like to have 1 server and 2 clients. After connecting to the server, the server should send a message to each client to choose (r/p/s). After this, each client should send back their choice and the server then decides about the winner, and then it informs the clients about the winner. This is what I have so far: This is the server.py import socket from threading import Thread class ClientThread(Thread): def __init__(self, ip, port): Thread.__init__(self) self.ip = ip self.port = port print("[+] New server socket thread started for " + ip + ":" + str(port)) def run(self): while True: data = conn.recv(1024).decode() print("Server received data:", data) MESSAGE = input("Server response: ") if MESSAGE == 'exit': break conn.send(MESSAGE.encode()) TCP_IP = '0.0.0.0' TCP_PORT = 2004 BUFFER_SIZE = 1024 tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcpServer.bind((TCP_IP, TCP_PORT)) threads = [] while True: tcpServer.listen(4) print("Multithreaded Python server : Waiting for connections from TCP clients...") (conn, (ip, port)) = tcpServer.accept() newthread = ClientThread(ip, port) newthread.start() threads.append(newthread) for t in threads: t.join() This is clientA.py: import socket host = socket.gethostname() port = 2004 BUFFER_SIZE = 1024 MESSAGE = input("tcpClientA:") tcpClientA = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpClientA.connect((host, port)) while MESSAGE != 'exit': tcpClientA.send(MESSAGE.encode()) data = tcpClientA.recv(BUFFER_SIZE).decode() print(" ClientA received data:", data) MESSAGE = input("tcpClientA:") tcpClientA.close() This is clientB.py: import socket host = socket.gethostname() port = 2004 BUFFER_SIZE = 1024 MESSAGE = input("tcpClientB:") tcpClientB = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpClientB.connect((host, port)) while MESSAGE != 'exit': tcpClientB.send(MESSA…
has title: Rock-paper-scissors game using sockets in Python
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52687997

http://stackoverflow.com/comment/92369754
comment on: http://stackoverflow.com/q/52699157
type: QuestionComment
has text: Noo, but I found a solution few minutes ago. Probably keyword "interact" was a problem. I changed it to "expect eof exit" like was mentioned in this link: https://gist.github.com/nachivpn/ff2e2b8cf647af633127
score: 0
type: Comment

http://stackoverflow.com/comment/92247292
has text: It works fine for me. Did you confirm both your dataframes df and df1 has the key "DESC" ?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52658055
type: Comment

http://stackoverflow.com/comment/92128824
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52597031
has text: The similar issue: [https://stackoverflow.com/questions/51868737/python-valueerror-duplicated-level-name-reported-date-assigned-to-level-1](https://stackoverflow.com/questions/51868737/python-valueerror-duplicated-level-name-reported-date-assigned-to-level-1)

http://stackoverflow.com/comment/92226157
has text: but without this command the line is so messy!
comment on: http://stackoverflow.com/q/52646527
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52662538
answers question: http://stackoverflow.com/q/52662393
score: 0
has body: def get_queryset(self, request): return super(RegistrationOTPResource, self).get_queryset(request).select_related('country')
type: Answer

http://stackoverflow.com/comment/92289344
has text: @GeoF you also have to fix your `__getitem__`: it should read `def __getitem__(self, i): return self.val[i]`
comment on: http://stackoverflow.com/a/52674107
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52784628
accepted answer of: http://stackoverflow.com/q/52628270
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52628270
type: Answer
has comment: http://stackoverflow.com/comment/130696913
score: 34
has body: As, @dennlinger mentioned in his answer : torch.utils.model_zoo, is being internally called when you load a pre-trained model. More specifically, the method: torch.utils.model_zoo.load_url() is being called every time a pre-trained model is loaded. The documentation for the same, mentions: The default value of model_dir is $TORCH_HOME/models where $TORCH_HOME defaults to ~/.torch. The default directory can be overridden with the $TORCH_HOME environment variable. This can be done as follows: import torch import torchvision import os # Suppose you are trying to load pre-trained resnet model in directory- models\resnet os.environ['TORCH_HOME'] = 'models\\resnet' #setting the environment variable resnet = torchvision.models.resnet18(pretrained=True) I came across the above solution by raising an issue in the PyTorch's GitHub repository: https://github.com/pytorch/vision/issues/616 This led to an improvement in the documentation i.e. the solution mentioned above.
upvote count: 34
has comment: http://stackoverflow.com/comment/136688727
has comment: http://stackoverflow.com/comment/111088819

http://stackoverflow.com/a/52662115
score: -1
has comment: http://stackoverflow.com/comment/92254679
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52662063
has body: You can use this formatted_number = "{:,}".format(number)
downvote count: 1

http://stackoverflow.com/comment/92137874
score: 1
has text: Where is `cherrypy` normally installed, and what is `sys.path` from the init-script?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52601825

http://stackoverflow.com/comment/92309823
type: Comment
comment on: http://stackoverflow.com/a/52691206
type: AnswerComment
score: 0
has text: We don't know the list was created as a source code literal. It might have been calculated at execution time. In general you could have a list of values with one or more having a `float` value of `Nan`. For example: `['a', 42, 3.14, float("NaN")]` → `['a', 42, 3.14, nan]`. Not that the `nan` at the end does not have quotes around it and isn't a string.

http://stackoverflow.com/a/53135109
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52731407
type: Answer
upvote count: 1
has body: Ended up finding a solution a couple hours later. I added a function to the code that checked if it was a unix of windows computer, and then used msvcrt when needed as a replacement. I believe I used the code from here to fix the program: http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/

http://stackoverflow.com/q/52674581
favorite count: 0
type: UnansweredQuestion
tagged with: error-handling
has comment: http://stackoverflow.com/comment/92278886
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92279002
has comment: http://stackoverflow.com/comment/92279727
has body: When implementing a try/except block, VS Code does not recognize the specified exception or any exception for that matter. Ex: try: x = 1/0 except ZeroDivisionError: print("You cannot divide by zero ") throws an exception error and does not print "You cannot divide by zero" when executed through the terminal. VS Code doesn't seem to be recognizing any exceptions. I've tried using the same code in IDLE and Sublime and it prints the correct message. Does anyone have any suggestions for fixing this? Other information: I'm using the python extension from Microsoft and have no other extensions in VS Code. Thanks!
score: 1
has comment: http://stackoverflow.com/comment/92278670
type: Question
has comment: http://stackoverflow.com/comment/92279590
tagged with: visual-studio-code
downvote count: 0
has comment: http://stackoverflow.com/comment/99912345
has answer: http://stackoverflow.com/a/56681984
has comment: http://stackoverflow.com/comment/92279339
tagged with: exception
has comment: http://stackoverflow.com/comment/92279261
answer count: 1
has title: why is try except block not working in visual studio code for python 3.7?
has comment: http://stackoverflow.com/comment/92280194

http://stackoverflow.com/a/52675642
has body: thanks for resolving @KlausD. have to create a new socket to reconnect. to rerun socket.socket(...),
answers question: http://stackoverflow.com/q/52658396
accepted answer of: http://stackoverflow.com/q/52658396
type: AcceptedAnswer
type: Answer
score: 0

http://stackoverflow.com/comment/92566880
type: AnswerComment
has text: Ty exactly what i was looking for.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52637810

http://stackoverflow.com/comment/92171288
score: 0
type: Comment
type: QuestionComment
has text: @AmarthGûl https://stackoverflow.com/a/590789/8079103
comment on: http://stackoverflow.com/q/52618381

http://stackoverflow.com/q/52713261
has body: I'm trying to compute the integral of a gaussian from an arbitrary point gamma as follows: import numpy as np from scipy.stats import norm def func(mu, sigma, gamma): x = np.linspace(mu-4*sigma, mu + 4*sigma, 100) y = norm.pdf(x, mu, sigma) area = y[x&gt;=gamma].sum() print(f"Area is ~ {area:.3f}") plt.plot(x,y, label=f'μ0 = {mu}, σ={sigma}') plt.fill_between(x[x&gt;gamma],y[x&gt;gamma], alpha=.5, label=f'area={area:.3f}') plt.title("Example") plt.legend(loc='best') plt.show() # Execute the function func(0,10,-20) Output is: Area is ~ 1.211 The blue area is integrated but it adds more than one (far more), even when it's not the complete function. I found this related but didn't help. Why is it adding up more than one?
type: AnsweredQuestion
has title: scipy.stat.norm.pdf does not add up to one
score: 1
has answer: http://stackoverflow.com/a/52713435
upvote count: 1
tagged with: scipy
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52713435
has comment: http://stackoverflow.com/comment/92352246
linked to: http://stackoverflow.com/q/38141951
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92352450
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/130696913
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52784628
has text: for me it was in ~/.cache/torch/checkpoints/ For example: wget https://download.pytorch.org/models/vgg19-dcbb9e9d.pth -P ~/.cache/torch/checkpoints/
type: AnswerComment

http://stackoverflow.com/comment/92260280
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52665187
score: 0
has text: you want to do it using some external script automatically ?

http://stackoverflow.com/a/52706643
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52705722
answers question: http://stackoverflow.com/q/52705722
score: 4
type: AcceptedAnswer
has body: The first sentence (a = numpy.random.RandomState(1)) start the pseudo random seed, in your case 1. That means that, no mater how many times you run the script, always get the same "random" number. In the second case (b = numpy.random.rand()), the seed is predefined, you don't know what seed was used. So, every time you run a script, you obtain the next pseudo random of the unknown seed.
type: Answer

http://stackoverflow.com/a/52655294
has body: Try using this library here, which supports password-protected archives.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52655258
score: 1
downvote count: 0

http://stackoverflow.com/comment/92312723
type: AnswerComment
score: 0
has text: looks like `if/elif` are way to go.
type: Comment
comment on: http://stackoverflow.com/a/52692852

http://stackoverflow.com/q/52707977
tagged with: python-multiprocessing
score: 0
has comment: http://stackoverflow.com/comment/92343436
has body: I have the issue : "AttributeError: 'dict_values' object has no attribute 'update'" How could I solve it ? code : queue = Queue() liste = glob(f+'/2013/*.xml')[:30] # l1 = Manager().list # l2 # # for fic in liste : # grosse_bc = main(fic,listeIngr,listeAll,grosse_bc) # for i in range (50): # main(liste[i],listeIngr,listeAll,grosse_bc) while len(liste) &gt;= 15 : for i in range(15): p = multiprocessing.Process(target=main, args=(liste[i],listeIngr,listeAll,queue,grosse_bc)) jobs.append(p) p.start() liste = liste[14:] print("fini !") # for p in jobs : # # grosse_bc.update(p) # p.join() # print("join fini !") gros_dico = [] # queue.join() x = 0 tgd = {} while not queue.empty(): # gros_dico.append(queue.get()) for elem in queue.get(): if elem not in tgd : tgd[elem] = queue.get().values() else : tgd[elem].update(queue.get().values()) # print(gros_dico) # for elem in gros_dico : # tgd.update(elem) pprint(tgd) And I would like to concatenate all the dicts outputed by the queues. Best Leon
has comment: http://stackoverflow.com/comment/92342487
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: AttributeError: 'dict_values' object has no attribute 'update'
tagged with: dictionary
answer count: 0
type: Question

http://stackoverflow.com/comment/92299790
comment on: http://stackoverflow.com/q/52669705
has text: After discussions with @John_Sharp1318 who has answered below, my answer is incorrect! His answer below is indeed the actual issue, and you should probably accept it instead for others who have your same issue. However, you will additionally run into the problem stated in my question with 3.4.3 anyways, which is stated in [this question](https://stackoverflow.com/questions/52574336/opencv-xfeatures2d-surf-213the-function-feature-is-not-implemented/52686193#52686193).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92226578
type: AnswerComment
type: Comment
has text: Thanks @PaulPanzer!
comment on: http://stackoverflow.com/a/52636390
score: 0

http://stackoverflow.com/q/52636959
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/29785084
type: UnansweredQuestion
has title: Value in a list is being parsed incorrectly in Python3
tagged with: python
has comment: http://stackoverflow.com/comment/92207398
answer count: 0
downvote count: 0
score: 1
has body: The following function for some reason is displaying different values of q1 at two different executions of it. I use Pycharm and the value of the last element in q1 is different in both the outputs it is displaying def rotation(mat): q1 = mat[0] q2 = [mat[i][-1] for i in range(len(mat))] print('\n\n', q1, q2) ####### This is where it goes wrong print('Actual:', q1[len(q1)-1], len(q1)-1) for i in range(0, len(q1)): mat[i][-1] = q1[i] print('Obtained:', q1[i], i) ########################## # display(mat) q1 = q2 q2 = mat[-1][::-1] for i in range(len(mat[-1]), 0): mat[-1][i] = q1[len(mat)-i-1] # display(mat) q1 = q2 q2 = [mat[i][0] for i in range(len(mat)-1, 0, -1)] for i in range(len(mat)-1, 0, -1): mat[i][0] = q1[len(mat)-i-1] # display(mat) q1 = q2 for i in range(len(mat[0])-1 ): mat[0][i] = q1[i] print('\n\n') # display(mat) UPDATE: The value is printing correctly if I comment out the line where I assign the value to mat[i][-1].
type: Question
upvote count: 1

http://stackoverflow.com/comment/92395467
score: 1
comment on: http://stackoverflow.com/q/52735310
type: Comment
has text: So you want to *transpose* the input?
type: QuestionComment

intersection
tags question: http://stackoverflow.com/q/52694093
type: Tag
tag name: intersection

http://stackoverflow.com/q/52637098
has title: How do you use elasticsearch in python to search over all indices?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52641685
score: 1
tagged with: search
type: Question
answer count: 1
has body: Here is my code: def search(term): s = Search().filter('match_phrase', title=term) response = s.execute() return response Looking at the function, title is the name of one of my indices. How do I change it so instead of only searching over one index, it searches over all of my indices?
upvote count: 1
tagged with: elasticsearch
favorite count: 0
downvote count: 0

http://stackoverflow.com/comment/92380375
score: 0
has text: I just discovered something strange. Your code works if I change the encoding of my file to ANSI. If I keep the file as UTF8, it fails. Thx for your help!
type: Comment
comment on: http://stackoverflow.com/a/52727411
type: AnswerComment

http://stackoverflow.com/comment/101360521
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52677793
has text: Can we use this code to get the Z of the color frame pixel?
type: AnswerComment

http://stackoverflow.com/a/52683910
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/52683891
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52683891
has body: The problem is that you are reinitializing numbers to be an empty list inside the function. So each time you call the function, you create an empty list numbers and hence the previously appended values are lost. You need to move numbers = [] outside the function. This way you just define it once as an empty list and then the items just keep appending/adding to it during each function call. numbers = [] def addnumber(a): numbers.append(a) print(numbers) button1 = Button(bottomFrame, text="1", command=lambda: addnumber(1)) button2 = Button(bottomFrame, text="2", command=lambda: addnumber(2))

http://stackoverflow.com/q/52623323
has answer: http://stackoverflow.com/a/52628832
tagged with: parameters
has body: I have a bash script that calls a python script with parameters. In the bash script, I'm reading a file that contains one row of parameters separated by ", and then calls the python script with the line I read. My problem is that the python gets the parameters separated by the space. The line looks like this: "param_a" "Param B" "Param C" Code Example: Bash Script: LINE=`cat $tmp_file` id=`python /full_path/script.py $LINE` Python Script: print sys.argv[1] print sys.argv[2] print sys.argv[3] Received output: "param_a" "Param B" Wanted output: param_a Param B Param C How can I send the parameters to the Python script the way I need? Thanks!
has title: Send parameters to python from bash
score: 1
has comment: http://stackoverflow.com/comment/92180134
has comment: http://stackoverflow.com/comment/92180534
type: Question
has answer: http://stackoverflow.com/a/52625286
tagged with: split
answer count: 3
downvote count: 0
favorite count: 0
tagged with: bash
tagged with: python
has answer: http://stackoverflow.com/a/52623613
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/q/52631694
has comment: http://stackoverflow.com/comment/92196969
has answer: http://stackoverflow.com/a/52632553
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/92197048
possible better answer: http://stackoverflow.com/a/52632553
has comment: http://stackoverflow.com/comment/92197144
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/92197334
downvote count: 5
has answer: http://stackoverflow.com/a/52632087
has comment: http://stackoverflow.com/comment/92196811
has title: Replacing string character in python
has comment: http://stackoverflow.com/comment/92197130
answer count: 2
has comment: http://stackoverflow.com/comment/92197201
has comment: http://stackoverflow.com/comment/92196632
favorite count: 0
has body: I am making a program where the user inputs some text, and I wan't all the characters in that text that is not in the variable "alfabet" to be changed to "?". How can I do this? I also want a to do it in two functions, main and clean_text. My code looks like this now: def clean_text(): for char in text: if char in alfabeth: continue elif char not in alfabeth: #don't know what to do here #text[] = "?" def main(): userInput = input("type in text: ") text = list(userInput) if__name__ == "__main__": main() clean_text(text)
accepted answer: http://stackoverflow.com/a/52632087
tagged with: python

http://stackoverflow.com/comment/92343710
type: QuestionComment
has text: Why do you think `uploads()` should be an endpoint in the Python client? `uploads()` isn't a thing in the REST API: https://developers.google.com/photos/library/reference/rest/ . Did you mean `batchCreate` and `create`? Those are the endpoints that let you create things.
type: Comment
comment on: http://stackoverflow.com/q/52674334
score: 0

http://stackoverflow.com/comment/92199100
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52632797
has text: I added the Python encoding line, that works too if it's just an encoding issue.
type: AnswerComment

http://stackoverflow.com/a/52792125
type: Answer
accepted answer of: http://stackoverflow.com/q/52743188
answers question: http://stackoverflow.com/q/52743188
score: 0
type: AcceptedAnswer
has body: I had several problems. First, my Ajax query did not have any callback function. Thanks to Rawri for pointing that out. The code is now the following. $.getJSON("/chk_chn", { name: channel_name} ) .done(function( json ) { console.log(json.result) // Check Name Uniqueness if (json.result === false) { $("#chn_name").after('Channel name already exists'); } else { // Check Channel Length if (channel_name.length > 20) { $("#chn_name").after('Channel Name exceeds maximum length'); return false } else { // Create Channel socket.emit("create_channel", {"channel_name": channel_name}) // Close the modal return true; } } }) .fail(function(jqxhr, textStatus, error) { var err = textStatus + ", " + error; console.log("Request Failed: " + err); }); My second and even more stupid issue was that the Ajax query was being called by a button that existed in a Modal. When the button was clicked, the Modal was closed and the javascript was regenerated on the new page, thus discarding my query entirely. I fix this by returning false on my form

http://stackoverflow.com/a/52729810
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52729628
downvote count: 0
type: Answer
has body: I don't know what kinds of commands your turtle can take, so this example may not exactly fit your use case. But from what I can see, you could use regular expressions to solve this problem. Let's say a command consists of two parts: a character to indicate the operation (F, &lt;, S, etc.), and a number to indicate the magnitude (100, 30, etc.). Your string has several of these back-to-back. What we can do is build a regular expression that will recognize all instances of this operation-number pattern in your string. Using only the commands F, &lt;, and S, the following regular expression will work: regex = r'([FS&lt;]\d+)' Let's unpack this. First, r'...' designates this string as a "raw string", which is what we typically use for regular expressions. This means characters within the string that would normally be escape characters, like \, will not be treated as such. Next, the parentheses () mark whatever's inside of them as a regex match - meaning that, when we pass through the string, anything matching the pattern inside the parentheses will be saved and outputted. Inside the parentheses, the square brackets [] denote a group of characters - this will match any character contained inside the brackets. So, in this case, the regex will look for a F, S, or &lt;. After looking for that character, we look for a number. \d is a shorthand for [0123456789] - that is, it matches any digit. + is a sign we attach to \d. This tells the regex to be "greedy", which means to include as many digits as possible instead of just one. You can now use python's re library to find all matches in the string. The findall method is what we need here: it takes one regex string and one search string, and returns, in order, a list of patterns from the search string that match the regex string. &gt;&gt;&gt; import re &gt;&gt;&gt; search = 'F100&lt;30S30' &gt;&gt;&gt; regex = r'([FS&lt;]\d+)' &gt;&gt;&gt; commands = re.findall(regex, search) &gt;&gt;&gt; print(commands) ['F100', '&lt;30', 'S3…

http://stackoverflow.com/comment/92312782
type: Comment
comment on: http://stackoverflow.com/q/52692345
has text: In my understanding you are victim of a typo. It's `print(rows[1][1])` (note _rows_, not _row_). Another problem is that your code is seemingly misaligned, the `print(rows[1][1])` shouldn't be outside of the `with` blocks, when all file i/o has been completed?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92406539
type: AnswerComment
comment on: http://stackoverflow.com/a/52730909
score: 0
type: Comment
has text: What does next race mean exactly?

http://stackoverflow.com/comment/92269807
type: Comment
type: QuestionComment
score: 1
has text: Can you show your code? I don't know what you mean by "all valid try cases after that exception will see the same exception".
comment on: http://stackoverflow.com/q/52669978

http://stackoverflow.com/q/52613049
tagged with: indexing
score: 3
tagged with: dataframe
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/52613085
has title: python dataframe: return column name in apply lambda
favorite count: 0
tagged with: pandas
tagged with: python
has body: I want to use apply(applymap) and lambda functions to get the column name for every element in dfx (a dataframe). The lambda function is used for mapping another dataframe into dfx, and it will be rewritten afterwards. dfx A B C 2011-01-10 123 12 123 2011-01-10 12 32 312 2011-01-11 44 1 30.99 pseudocode output = dfx.apply(lambda r:r.column) I don't know how to write this part "r:r.column" intended output A B C 2011-01-10 A B C 2011-01-10 A B C 2011-01-11 A B C Any help is more than welcome! Thanks a lot!!
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52613674
tagged with: lambda
has comment: http://stackoverflow.com/comment/92162392
type: Question

http://stackoverflow.com/comment/92359967
type: Comment
comment on: http://stackoverflow.com/q/52717235
has text: @roganjosh it is a big number, but I've tried even larger number(twice as long), it works just fine and fast though
score: 0
type: QuestionComment

http://stackoverflow.com/q/52706659
tagged with: azure
tagged with: python
tagged with: jupyter-notebook
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: azure-data-factory
has answer: http://stackoverflow.com/a/52712294
type: Question
has body: I gather from the documentation that we can use Jupyter notebooks only with Databricks Spark cluster. Is there a way around this? Can I call Jupyter notebook as an activity from ADF without Databricks environment? I would like to have a simple way to call some python code from ADF. Thanks!
answer count: 1
downvote count: 0
favorite count: 0
has title: Use Jupyter notebook without DataBricks in Azure Data Factory?

http://stackoverflow.com/q/52691468
score: 10
has comment: http://stackoverflow.com/comment/92311020
has comment: http://stackoverflow.com/comment/92310402
linked to: http://stackoverflow.com/q/12544056
has body: Is it possible for a jupyter notebook to get the name of its own file, similarly to what we would do from a python script? os.path.basename(__file__) doesn't seem to work, at least for me on jupyterlab sys.argv[0] returns my_home/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py
has comment: http://stackoverflow.com/comment/95673905
answer count: 1
downvote count: 0
tagged with: jupyter-notebook
favorite count: 0
accepted answer: http://stackoverflow.com/a/56443793
tagged with: python
tagged with: python-os
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92310821
upvote count: 10
type: Question
has title: Can a jupyter notebook find its own filename?
tagged with: jupyter-lab
has comment: http://stackoverflow.com/comment/92311168
has answer: http://stackoverflow.com/a/56443793
has comment: http://stackoverflow.com/comment/92311283

http://stackoverflow.com/a/52648063
type: Answer
has comment: http://stackoverflow.com/comment/92227970
has comment: http://stackoverflow.com/comment/92228221
answers question: http://stackoverflow.com/q/52647395
has comment: http://stackoverflow.com/comment/92228033
has comment: http://stackoverflow.com/comment/92227947
score: 0
has body: I you insist on not using index for the key, answer = None for key in d.keys(): if "CCC" in d[key]: answer = key break *edit suggested by @Olivier

http://stackoverflow.com/q/52687860
has answer: http://stackoverflow.com/a/52688372
has comment: http://stackoverflow.com/comment/92302936
has answer: http://stackoverflow.com/a/52687958
has answer: http://stackoverflow.com/a/52688086
upvote count: 1
has comment: http://stackoverflow.com/comment/92302910
answer count: 4
downvote count: 0
has body: I'm trying to create a list with options in 30 minute intervals from 9am-5pm. e.g. times = ['09:00-09:30', '09:30-10:00', '10:00-10:30', '10:30-11:00', '11:00-11:30', '11:30-12:00', '12:00-12:30', '12:30-13:00', '13:00-13:30', '13:30-14:00', '14:00-14:30', '14:30-15:00', '15:00-15:30', '15:30-16:00', '16:00-16:30', '16:30-17:00'] How would I be able to accomplish this but using loops or a method that doesn't look this verbose?
has comment: http://stackoverflow.com/comment/92302836
type: AnsweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52687982
score: 1
has title: Creating a list of times with loops instead of manual entry
favorite count: 0
possible better answer: http://stackoverflow.com/a/52688372
type: Question
accepted answer: http://stackoverflow.com/a/52687982

http://stackoverflow.com/q/52744181
type: AnsweredQuestion
score: 0
has body: How do I use Regex (python engine) to find a certain string, match several lines above it and all text after it until another specified string? The text is coming from a log file and almost all of the values are dynamic. I have found only one constant string and it sits in the middle of the block I want to capture. For example: Here is a line of text that I DON'T want to match. Here is a line of text that I DO want to match. Here is a line of text that I DO want to match. String to match Line of text and numbers and other marks abc123:/()& that I want to capture. Line of text and numbers and other marks abc123:/()& that I want to capture. Line of text and numbers and other marks abc123:/()& that I want to capture. String to end on but NOT capture text I DON'T want text I DON'T want I should also probably note that most of these lines can contain not only text but numbers and other punctuation and I need to get all of it. If anyone can point me in the right direction, I would really appreciate the help. Thanks! EDIT Here is a real example from the log file with certain values redacted: Tue Oct 0 00:00:00 UTC 0000 A:REDACTED# REDACTED 7/1/8 ============================================================== Ethernet Interface =============================================================== Description : REDACTED Interface : 0/0/0 Oper Speed : 10 Gbps Link-level : Ethernet Config Speed : N/A Admin State : up Oper Duplex : full Oper State : up Config Duplex : N/A Physical Link : Yes MTU : 2004 Single Fiber Mode : No Min Frame Length : 64 Bytes IfIndex : REDACTED Hold time up : 90 seconds I need to capture all but the first and last line using "Ethernet Interface" as the text to match. I have attempted something like this: (?<=Ethernet Interface)(.*)(?=IfIndex) but that only captures the second half of what I need. How do I add in the first part?
answer count: 1
accepted answer: http://stackoverflow.com/a/52744532
has comment: http://stackoverflow.com/comment/92414358
favorite count: 0
has comment: http://stackoverflow.com/comment/92413401
tagged with: python
tagged with: regex
upvote count: 1
downvote count: 1
has title: How to match lines of text above and below a certain string up to another string - RegEx
type: Question
has answer: http://stackoverflow.com/a/52744532

http://stackoverflow.com/comment/92344784
comment on: http://stackoverflow.com/q/52709268
has text: Are you using this `launch.json` configuration?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92306782
type: QuestionComment
score: 1
has text: What exactly is your question?
comment on: http://stackoverflow.com/q/52689985
type: Comment

amazon-s3
tags question: http://stackoverflow.com/q/52738357
tags question: http://stackoverflow.com/q/52684987
tags question: http://stackoverflow.com/q/52594497
tags question: http://stackoverflow.com/q/52711311
tags question: http://stackoverflow.com/q/52736337
tags question: http://stackoverflow.com/q/52625812
type: Tag
tags question: http://stackoverflow.com/q/52670635
tags question: http://stackoverflow.com/q/52596370
tags question: http://stackoverflow.com/q/52645443
tags question: http://stackoverflow.com/q/52693824
tags question: http://stackoverflow.com/q/52739471
tags question: http://stackoverflow.com/q/52683685
tag name: amazon-s3
tags question: http://stackoverflow.com/q/52600363
tags question: http://stackoverflow.com/q/52614580
tags question: http://stackoverflow.com/q/52600745

http://stackoverflow.com/comment/92384817
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52729337
has text: Your first group will not meet any of the criteria you have set. The numbers passed for `Col3` in the first group will be `1` and `4`. Since `1` is less than your test value for `x` (note, your example is `x = 4`), then it cannot return `high` or `med`. It also cannot return `low` because the other value in the first group is `4`, and your check for `low` is only triggered if any of the remaining values are > or < than your `x` value, which is `4`, so they are equal! Long story short, your logic is very unclear and can be simplified. Please edit your question accordingly.

http://stackoverflow.com/a/52712911
score: 0
answers question: http://stackoverflow.com/q/52711543
has body: With text functions: c = "apple bottom cotton dog (eagle fox gut) horse" txtfilter = c[:]+"()" result = [] while "(" in txtfilter: positionInit = txtfilter.find("(") extract_first = txtfilter[:positionInit] result.extend(extract_first.split()) positionEnd = txtfilter[positionInit:].find(")")+positionInit+1 result.append(txtfilter[positionInit:positionEnd]) txtfilter = txtfilter[positionEnd:] print result[:-1] Output: ['apple', 'bottom', 'cotton', 'dog', '(eagle fox gut)', 'horse'] Description: apple bottom cotton dog &lt;-- extract_first block --> (eagle fox gut) (&lt;-- append-->) horse &lt;--repeat process-->
type: Answer

http://stackoverflow.com/a/52601284
score: 6
type: Answer
upvote count: 6
has body: Which makes me wonder why do we need to pickle the object in order to do multiprocessing? We don't need pickle, but we do need to communicate between processes, and pickle happens to be a very convenient, fast, and general serialization method for Python. Serialization is one way to communicate between processes. Memory sharing is the other. Unlike memory sharing, the processes don't even need to be on the same machine to communicate. For example, PySpark using serialization very heavily to communicate between executors (which are typically different machines). Addendum: There are also issues with the GIL (Global Interpreter Lock) when sharing memory in Python (see comments below for detail). isn't fork() enough? Not if you want your processes to communicate and share data after they've forked. fork() clones the current memory space, but changes in one process won't be reflected in another after the fork (unless we explicitly share data, of course). I kind of get why we need pickle to do interprocess communication, but that is just for the data you want to transfer right? why does the multiprocessing module also try to pickle stuff like functions etc? Sometimes complex objects (i.e. "other stuff"? not totally clear on what you meant here) contain the data you want to manipulate, so we'll definitely want to be able to send that "other stuff". Being able to send a function to another process is incredibly useful. You can create a bunch of child processes and then send them all a function to execute concurrently that you define later in your program. This is essentially the crux of PySpark (again a bit off topic, since PySpark isn't multiprocessing, but it feels strangely relevant). There are some functional purists (mostly the LISP people) that make arguments that code and data are the same thing. So it's not much of a line to draw for some.
answers question: http://stackoverflow.com/q/52600240
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52600240
has comment: http://stackoverflow.com/comment/92137599

http://stackoverflow.com/q/52740680
score: 0
has title: Odoo 10 : Security groups are not working on edit/create button
has answer: http://stackoverflow.com/a/52744130
tagged with: python
tagged with: menu
tagged with: http://stackoverflow.com/tag/xml
type: UnansweredQuestion
tagged with: odoo
has body: Aim : to make appear the Edit/create button only for user group : Manager Module name : Simcard Model Name : simcard_simcard my csv file : id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink demo_admin, Model admin access,model_simcard_simcard,simcard.group_manager,1,1,1,1 demo_user, Model user access,model_simcard_simcard,simcard.group_user,0,0,0,0 My user_groups.xml : <?xml version="1.0" encoding="utf-8"?> Simcard User access level for this module 3 User Manager My views.xml : remove.edit simcard.simcard true simcard.group_manager This Edit button still appears for normal users.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52747082
tagged with: security

http://stackoverflow.com/comment/92128308
score: 3
has text: Why not simply use `df.f.value_counts().sort_index().to_frame().plot(kind='bar')`?
type: Comment
comment on: http://stackoverflow.com/q/52596604
type: QuestionComment

http://stackoverflow.com/comment/92303003
type: Comment
type: QuestionComment
has text: The instructions say to set the name etc from a _value_. The method shouldn't call `input`. The code outside the class should first gather the name, type, and age from the user, and then use those values to create a Pet.
comment on: http://stackoverflow.com/q/52687918
score: 0

http://stackoverflow.com/comment/92369148
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52717761
has text: @GiacomoAlzetta it's the same one. One just has to read more than the question title (which, i admit, is kinda misleading with the `-e` option): _How can one manage to install extras_requires with pip when installing from a git repository?_ The answer listed there is also a working one and answers this question perfectly.

http://stackoverflow.com/a/52746900
type: Answer
has body: Since your inbox class is basically a wrapper around a list, you could make it a subclass of UserList and have access to all list methods. from collections import UserList class Inbox(UserList): """ Inbox class: add_new_arrival, message_count, get_unread_indexes, get_message, delete, clear """ def add_new_arrival(self, from_number, time_arrived, text_of_SMS): """Makes new SMS tuple, inserts it after other messages in the store. When creating this message, its has_been_viewed status is set to False""" self.append((from_number, time_arrived, text_of_SMS, False)) my_inbox = Inbox() my_inbox.add_new_arrival("from number", "time arrived", "text") print(len(my_inbox))
answers question: http://stackoverflow.com/q/52745556
score: 0

http://stackoverflow.com/comment/132530076
type: Comment
comment on: http://stackoverflow.com/a/52709150
type: AnswerComment
has text: I tried this and couldn't get it to work. I installed pareto using pip. But when I ran the code on my dataframe I got AttributeError: 'function' object has no attribute 'eps_sort'.
score: 0

http://stackoverflow.com/comment/92176466
score: 0
comment on: http://stackoverflow.com/q/52620774
type: Comment
type: QuestionComment
has text: @andree17914can you please post the whole code? Or an excerpt but that gives an idea of what you're trying to do?

http://stackoverflow.com/q/52627282
has title: Tango with Django Chapter 6 - URL won't work
type: Question
has comment: http://stackoverflow.com/comment/92225742
has comment: http://stackoverflow.com/comment/92281829
has comment: http://stackoverflow.com/comment/92188467
has comment: http://stackoverflow.com/comment/92187996
has comment: http://stackoverflow.com/comment/92188292
upvote count: 1
has answer: http://stackoverflow.com/a/52676634
accepted answer: http://stackoverflow.com/a/52676634
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92225332
has comment: http://stackoverflow.com/comment/92225125
tagged with: python
has comment: http://stackoverflow.com/comment/92225790
has comment: http://stackoverflow.com/comment/92188537
has body: I have been going through "Tango with Django" and have been unable to solve this problem myself or by looking online. Would anyone know how to approach it? The relevant page should be opened when I click on the link, but none are going through, which makes me assume something in my view.py file is wrong or even in my url.py or model.py file (index.html seems to be working correctly). Views.py # Create your views here. from django.http import HttpResponse from django.shortcuts import render from Spaces.models import Category, Page def index(request): # Query the databse for a list of ALL categories currently stored. # Order the categories by no likes in descending order . # Retrieve the top 5 only - or all if less than 5. # Place the list in context_dict dictionary # that will be passed to the template engine. category_list = Category.objects.order_by('-likes')[:5] context_dict = {'categories': category_list} # Render the response and send it back! return render(request, 'Spaces/index.html', context=context_dict) def about(request): context_dict = {'boldmessage':"Crunchy, creamy, cookie, candy, cupcake!"} return render(request, 'Spaces/about.html', context=context_dict) def show_category(request, category_name_slug): # Create a context dictionary which we can pass # to the template rendering engine. context_dict = {} try: # Can we find a category name slug with the given name? # If we can't, the .get() method raises a DoesNotExist exception. # So the .get() method returns one model instance or raises an exception. category = Category.objects.get(slug=category_name_slug) # Retrieve all of the associated pages. # Note that filter() will return a list of page objects or an empty list pages = Page.objects.filter(category=category) # Adds our results list to the template context under name pages. context_dict['pages'] = pages # We also add the category object from # the database to the context dictionary. # We'll use this in the template to verify that the category exists…
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: django

http://stackoverflow.com/comment/92400579
comment on: http://stackoverflow.com/q/52737806
has text: Also - totally unrelated but - you don't need to make your test method variables (`test_operation_type`, `chosen_date_from` etc) attributes of the `TestCase` instance (it's just useless)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92275328
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52671224
score: 0
has text: With closer approximations of the initial values that goes away.

http://stackoverflow.com/q/52614194
has title: Pandas Seaborn Data labels showing as 0.00
has comment: http://stackoverflow.com/comment/92168131
tagged with: seaborn
type: UnansweredQuestion
tagged with: python
has body: I have two questions: My data labels are showing as 0.00 and isn't matching my cross tab. I don't know why... Updating with the full code: df = pd.read_csv('2018_ms_data_impact_only.csv', low_memory=False) df.head() StartDate EndDate Status IPAddress Progress duration Finished RecordedDate ResponseId RecipientLastName ... Gender LGBTQ Mobile organizing_interest Parent Policy policy_interest reg_to_vote unique_id Veteran 0 4/6/18 10:32 4/6/18 10:39 1 NaN 100 391 1 4/6/18 10:39 R_1liSDxRmTKDLFfT Mays ... Woman 0.0 4752122624 Currently in this field 1.0 NaN NaN 0.0 0034000001VAbTAAA1 0.0 1 4/9/18 6:31 4/9/18 6:33 1 NaN 100 160 1 4/9/18 6:33 R_0ezRf2zyaLwFDa1 Mays ... Woman 0.0 4752122684 2020 0.0 A 2020 0.0 0034000001W3tGOAAZ 0.0 2 4/9/18 9:14 4/9/18 9:15 1 NaN 100 70 1 4/9/18 9:15 R_DeHh3DQ23uQZwLD Mays ... Woman 0.0 4752122684 2020 0.0 A 2020 0.0 0034000001W3tGOAAZ 0.0 3 4/9/18 9:21 4/9/18 9:22 1 NaN 100 69 1 4/9/18 9:22 R_1CC0ckmyS7E1qs3 Mays ... Woman 0.0 4752122684 2020 0.0 A 2020 0.0 0034000001W3tGOAAZ 0.0 4 4/9/18 9:28 4/9/18 9:29 1 NaN 100 54 1 4/9/18 9:29 R_01GuM5KqtHIgvEl Mays ... Woman 0.0 4752122684 2020 0.0 A 2020 0.0 0034000001W3tGOAAZ 0.0 def impact_action_yn_new(series): if series == 3: return 'No' elif series == 1: return 'Yes' df['impact_action_yn_new'] = df['impact_action_yn'].apply(impact_action_yn_new) df['impact_action_yn_new'].value_counts(sort=False) # clean up engagement - collapse nan and 0, 2s def engagement_new(series): if series == '0': return 'Null' elif series == 'NaN': return 'Null' elif series == '1': return '1' elif series == '2': return '2a' elif series == '2a': return '2a' elif series == '2b': return '2b' elif series == '3': return '3' elif series == '4': return '4' elif series == '5': return '5' df['engagement_new'] = df['Engagement'].apply(engagement_new) impact_action_table_eng = pd.crosstab(df.impact_action_yn_new,df.engagement_new) print(impact_action_table_eng) engagement_new 1 2a 2b 3 4 5 Null impact_action_yn_new No 676 508 5…
answer count: 0
linked to: http://stackoverflow.com/q/20109391
tagged with: percentage
has comment: http://stackoverflow.com/comment/92164685
has comment: http://stackoverflow.com/comment/92166059
type: Question
has comment: http://stackoverflow.com/comment/92164520
score: 0
tagged with: bar-chart

http://stackoverflow.com/a/52613513
accepted answer of: http://stackoverflow.com/q/52613369
has body: I would recommend NOT using regex to parse HTML. Your life will be much easier if you use something like beautifulsoup! It's as easy as this: from BeautifulSoup import BeautifulSoup HTML = """firstoneIhaveurls""" s = BeautifulSoup(HTML) for href in s.find_all('a', href=True): print("My URL: ", href['href'])
answers question: http://stackoverflow.com/q/52613369
has comment: http://stackoverflow.com/comment/92162412
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92190794
type: Comment
type: QuestionComment
has text: @eyllanesc because I would have to use it 12 times and i don't want my code to be that long, I'm looking for a shorter way to do it.
comment on: http://stackoverflow.com/q/52628160
score: 0

http://stackoverflow.com/a/52602777
accepted answer of: http://stackoverflow.com/q/52602703
has comment: http://stackoverflow.com/comment/92139823
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92140087
has comment: http://stackoverflow.com/comment/92140082
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92140069
answers question: http://stackoverflow.com/q/52602703
type: Answer
has body: I believe you need merge with left join and then set 0 by numpy.where with boolean mask created by DataFrame.duplicated: df3 = df1.merge(df2, on=['Date','Name','Orgz'], how='left') df3['min'] = np.where(df3.duplicated(subset=['Date','Name','Orgz']), 0, df3['min']) print (df3) Date Name Orgz min 0 2018-08-10 A Alpha 60 1 2018-08-10 A Alpha 0 2 2018-08-10 A Alpha 0 3 2018-08-10 A Alpha 0 4 2018-08-10 A Alpha 0 5 2018-08-11 B Beta 85 6 2018-08-11 B Beta 0 7 2018-08-11 B Beta 0 8 2018-08-12 C Gamma 90 9 2018-08-12 C Gamma 0 10 2018-08-13 D Theta 77 11 2018-08-13 D Theta 0 12 2018-08-12 E Theta 25 13 2018-08-12 F Theta 30 14 2018-08-12 F Theta 0

http://stackoverflow.com/comment/92150442
score: 0
type: QuestionComment
type: Comment
has text: If thats the case then this should do it? {% for x in data.pairs | sort(x) %} {{ x }} {% endfor %}
comment on: http://stackoverflow.com/q/52608052

http://stackoverflow.com/comment/92113212
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52589025
has text: By the look of it there's no easy logging in pysftp. Assuming put_d is the right method (it's not recursive - that's put_r), I think your best bet is to edit your local copy of pysftp to add print statements to walktree() and put_d() to see what it's doing. It might also be worth checking you can transfer a single file using cd and put.
score: 0

http://stackoverflow.com/q/52689682
has comment: http://stackoverflow.com/comment/92306351
tagged with: python
has body: After ran the code on spyder a lot of times, this error appeared. 'tuple' object is not callable X=float(input("¿Cual es el valor del cateto opuesto?: ")) Y=float(input("¿Cual es el valor del cateto adyacente?: ")) H=((X)**2+(Y)**2)**0.5 print(H) And this appeared on the Terminal runfile('D:/Docente Catedra Udea/Algoritmos y Programacion/2018- 2/Estudiantes/Practicas/Practica_3/Calculo de la Hipotenusa DANNA VALENTINA VILLAMIL GONZÁLEZ.py', wdir='D:/Docente Catedra Udea/Algoritmos y Programacion/2018-2/Estudiantes/Practicas/Practica_3') ¿Cual es el valor del cateto opuesto?: 1 ¿Cual es el valor del cateto adyacente?: 1 Traceback (most recent call last): File "&lt;ipython-input-19-ccf4414dc7a2&gt;", line 1, in &lt;module&gt; runfile('D:/Docente Catedra Udea/Algoritmos y Programacion/2018- 2/Estudiantes/Practicas/Practica_3/Calculo de la Hipotenusa DANNA VALENTINA VILLAMIL GONZÁLEZ.py', wdir='D:/Docente Catedra Udea/Algoritmos y Programacion/2018-2/Estudiantes/Practicas/Practica_3') File "C:\Users\USUARIO\Anaconda3\lib\site- packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\USUARIO\Anaconda3\lib\site- packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "D:/Docente Catedra Udea/Algoritmos y Programacion/2018- 2/Estudiantes/Practicas/Practica_3/Calculo de la Hipotenusa DANNA VALENTINA VILLAMIL GONZÁLEZ.py", line 11, in &lt;module&gt; print(H) TypeError: 'tuple' object is not callable Any advice on how to solve this would be welcome.
score: 0
has comment: http://stackoverflow.com/comment/92316424
has comment: http://stackoverflow.com/comment/92306299
has comment: http://stackoverflow.com/comment/92314800
has title: Problem with spyder Type error: 'tuple' object is not callable
answer count: 0
type: UnansweredQuestion
tagged with: typeerror
has comment: http://stackoverflow.com/comment/92314796
tagged with: spyder
type: Question

http://stackoverflow.com/q/52635572
has comment: http://stackoverflow.com/comment/92204676
has title: Most efficient way to combine list of lists to get groups of items <= but as close as possible to length X
tagged with: sorting
has answer: http://stackoverflow.com/a/52641720
accepted answer: http://stackoverflow.com/a/52641720
linked to: http://stackoverflow.com/q/5626520
possible better answer: http://stackoverflow.com/a/52637563
downvote count: 0
has body: Say I have a list of lists like: [ [ a1, a2, a3, a4, a5], [b1, b2, b3, b4, b5, b6, b7, b8], [c1, c2, c3, c4, c5, c6], [d1, d2, d3, d4] ] What's the easiest way to compare all the list item lengths and combine them into a list of lists with lengths as close as possible to, but less than or equal to, x? So with the above example, and x=12: [ [a1, a2, a3, a4, a5, c1, c2, c3, c4, c5, c6], [b1, b2, b3, b4, b5, b6, b7, b8, d1, d2, d3, d4] ] The ordering of the individual groups (e.g a, b, c...) in the output isn't important, but individual groups cannot be broken up. I know I could, for instance, take the length of the first group, then get the length of each subsequent group in order and if their sum = x then pop those lists and append their items to the returned list, and if not then work through each group again checking if the sum of their lengths=x-1 and if so pop and append, and on with sum of lengths=x-2 etc until the input list is empty. Which will work fine for small groups like the example given, but what about when the len of the input list gets very large? Is there a more efficient method / algorithm?
favorite count: 0
has comment: http://stackoverflow.com/comment/92336674
has comment: http://stackoverflow.com/comment/92204750
tagged with: python
has comment: http://stackoverflow.com/comment/92204876
type: AnsweredQuestion
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/52637563
upvote count: 3
linked to: http://stackoverflow.com/q/16017197
has comment: http://stackoverflow.com/comment/92208173
has comment: http://stackoverflow.com/comment/92204850
type: Question
answer count: 2
tagged with: algorithm

http://stackoverflow.com/comment/92146264
type: Comment
comment on: http://stackoverflow.com/a/52605275
score: 0
type: AnswerComment
has text: Could it be that my app needs me to add some sort of module to get self to work?

http://stackoverflow.com/q/52656417
favorite count: 0
has comment: http://stackoverflow.com/comment/110904511
has answer: http://stackoverflow.com/a/52657290
linked to: http://stackoverflow.com/q/788411
has comment: http://stackoverflow.com/comment/92247200
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92245901
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52657326
type: Question
has body: I have a python script named update.py, and I want to use another python script to check whether the script is running or not. If update.py doesn't run or error, then the script will run update.py. Can i do it? If there is an example it will be very thankful.
answer count: 2
downvote count: 0
tagged with: raspberry-pi3
tagged with: bash
accepted answer: http://stackoverflow.com/a/52657326
has title: Check a Python Script Is Running
possible better answer: http://stackoverflow.com/a/52657290

http://stackoverflow.com/comment/92278099
score: 0
type: Comment
type: QuestionComment
has text: Hi @HenryWoody, I used df.loc[891]to access the value
comment on: http://stackoverflow.com/q/52673752

http://stackoverflow.com/comment/92336829
type: Comment
type: QuestionComment
has text: Be more specific than `didn't work`. I can guess what's wrong, but can't run a test case right now.
comment on: http://stackoverflow.com/q/52703473
score: 0

http://stackoverflow.com/a/54671399
type: Answer
answers question: http://stackoverflow.com/q/52636783
score: 0
has body: Upgrading matplotlib from version 3.0.0 to 3.0.2 solved the problem. If you use pip type: pip install --upgrade matplotlib I verified the case with Jupyter version 4.4.0.

http://stackoverflow.com/a/52668758
answers question: http://stackoverflow.com/q/52668547
type: Answer
score: 0
has body: generate the product list and then shuffle it. It will contain unique values in tuple from itertools import product from random import shuffle my_list= list((i,j) for i,j in product([1,2],range(1,10)) if i!=j) shuffle(my_list) print(my_list[:14]) # just pick random 14 pairs which are not duplicate Correcting your code to check for duplicates. Although with expensive in operator import random intial_range=range(2) for i in intial_range: count=0 while count&lt;7: temp = random.randint(1,10) if(temp not in intial_range): print(i, ',', temp) count+=1

http://stackoverflow.com/a/52719393
upvote count: 1
has comment: http://stackoverflow.com/comment/92371723
has comment: http://stackoverflow.com/comment/92374322
answers question: http://stackoverflow.com/q/52719346
downvote count: 0
has body: I think the named ranges are global to the workbook, not local to each sheet. Which is hinted at by the error message you're getting: DefinedName with the same name and scope already exists So you'd have to give those different names wb = openpyxl.load_workbook(file.xlsx) sheet1 = wb['sheet1'] sheet2 = wb['sheet2'] wb.create_named_range('sales1', sheet1 , '$B$11:$B$35') wb.create_named_range('sales2', sheet2 , '$B$11:$B$35') or a more DRY solution: wb = openpyxl.load_workbook(file.xlsx) sheets = [] for sheet_no in range(1,3): sheets[sheet_no] = wb[f'sheet{sheet_no}'] # note pre python 3.6 you should change f'sheet{sheet_no}' to 'sheet{}'.format(sheet_no) wb.create_named_range(f'sales{sheet_no}', sheets[sheet_no], '$B$11:$B$35')
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/92367209

http://stackoverflow.com/q/52650413
has answer: http://stackoverflow.com/a/52650527
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52650464
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52650464
type: Question
possible better answer: http://stackoverflow.com/a/52650527
has answer: http://stackoverflow.com/a/52651589
upvote count: 2
has body: So I have this dataframe that contains a lot of columns and for an example have a look at this: id Status Name Age Job 213 Active John 39 Unavailable 415 Inactive Sara 34 Unavailable 941 Inactive Micky 11 Unavailable 993 Active Zack 45 Unavailable What I want to do is to use the pandas library to assign a value of 1 to the job column if the status of a person is active and 0 if it is inactive.So the original dataframe becomes like: id Status Name Age Job 213 Active John 39 1 415 Inactive Sara 34 0 941 Inactive Micky 11 0 993 Active Zack 45 1 And to change the values of status column to 1 and 0 based if status is active or inactive respectively. id Status Name Age Job 213 1 John 39 Unavailable 415 0 Sara 34 Unavailable 941 0 Micky 11 Unavailable 993 1 Zack 45 Unavailable I read a lot in their documentation but they haven't really explicitly declared such manipulations. Also I want to have these made separately.
answer count: 3
tagged with: pandas
has title: Changing a column's values into 1 or 0 based on a parameter in pandas

http://stackoverflow.com/comment/92360758
comment on: http://stackoverflow.com/a/52717586
type: Comment
has text: @Beginner Because `count` is initialized with the value `0`, it will always print this value... Have a look at my small change.
score: 1
type: AnswerComment

http://stackoverflow.com/a/52693162
has comment: http://stackoverflow.com/comment/92313120
upvote count: 2
downvote count: 0
type: Answer
has body: May I suggest this code skeleton? ... while True: # i.e., loop F O R E V E R reply = present_menu() if not (1 &lt;= reply &lt;= 5) : show_error_message() continue # i.e., abort this cycle and start a new loop cycle if reply == 5: recapitulation() break # i.e., exit the forever loop how_many = ask_how_many(reply) update_purchases(reply, how_many) ... What really matters are the following ideas an infinite loop if the answer is unsatisfactory, abort and start a new iteration (i.e., presenting again the menu) using the continue statement if the user chooses to stop interaction, definitively exit the loop using the break statement. You could put all your code inside the loop according to these principles, or you can follow my suggestion and abstract repetitive pieces of code into auxiliary functions.
score: 2
answers question: http://stackoverflow.com/q/52692931

http://stackoverflow.com/q/52659268
answer count: 0
has comment: http://stackoverflow.com/comment/92248922
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92248862
type: Question
has comment: http://stackoverflow.com/comment/92248940
tagged with: pause
score: 0
has comment: http://stackoverflow.com/comment/92248900
has title: how to implement pause and resume button function using tkinter python
tagged with: python
tagged with: tkinter
has body: Tkinter.Button(self, text='Pause', command=self.pause_program).grid(row=7, columnspan=2, rowspan=3) def pause_program(self): input("Press Enter to continue...") time.sleep(2) and below the other part of the program. remaining program fetches data from a source, want to implement a pause and resume button to pause the program by simply pressing the button and resume it back whenever needed.

http://stackoverflow.com/q/52728604
tagged with: python
has answer: http://stackoverflow.com/a/52729862
tagged with: pycharm
has title: PyCharm - packaging_tool.py error on Install packaging tools
type: Question
tagged with: jetbrains-ide
score: 0
has body: I'm trying to set up a Python Flask project and Project Interpreter. It showing me that "Python Packaging tools not found" When I'm trying to install it showing me Error in Line 100 of PyCharm file - Execute command: /Applications/PyCharm.app/Contents/helpers/packaging_tool.py untar /Applications/PyCharm.app/Contents/helpers/setuptools-28.8.0.tar.gz Error Occurred: nstall (pkgs) : try : try : from pip._internal import main except Exception: from pip import main except ImportError: error_no_pip() return main([ 'install' ] + pkgs) def do_uninstall (pkgs) : try : try : from pip._internal import main except Exception: from pip import main except ImportError: error_no_pip() return main([ 'uninstall' , '-y' ] + pkgs).stdout.flush() File "/Applications/PyCharm.app/Contents/helpers/packaging_tool.py", line 100 nstall (pkgs) : try : try : from pip._internal import main except Exception: from pip import main except ImportError: error_no_pip() return main([ 'install' ] + pkgs) def do_uninstall (pkgs) : try : try : from pip._internal import main except Exception: from pip import main except ImportError: error_no_pip() return main([ 'uninstall' , '-y' ] + pkgs).stdout.flush() ^ SyntaxError: invalid syntax I did everything installed pip/pip3 again. Also tried to edit nstall to install on line 100. Please help
answer count: 1
type: UnansweredQuestion
tagged with: pip

http://stackoverflow.com/q/52673360
type: UnansweredQuestion
tagged with: python
tagged with: tei
has answer: http://stackoverflow.com/a/52674075
has body: I have a .tei file of the following format. The Semantic Web T Berners-Lee J Hendler O Lassilia Scientific American <date type="published" when="2001-05" /> I want to convert the above file to .txt format which looks like this : T. Berners-Lee, J. Hendler and O. Lassilia. ‘The Semantic Web’, Scientific American,May 2001 I tried using the following piece of code: tree = ET.parse(path) root = tree.getroot() s = "" for childs in root: for child in childs: s= s+child.text The problem with the above code is that the loop executes sequentially and the string is not in the sequential format. Secondly, there might be even more inner loops. Extracting something inside inner loops without manually checking is also problematic. Please help me with this
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92276661
has title: Converting .tei file to a .txt file
has comment: http://stackoverflow.com/comment/139415197
upvote count: 2
answer count: 1
downvote count: 1
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0

http://stackoverflow.com/a/52726875
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52704962
has body: You can sort this dictionary but you have to make an exception for rotation since its values do not fit the rest of the format of being a dictionary with alphabetical keys d = {k: dict(sorted(v.items(), key=lambda x: x[0])) if k != 'rotation' else schedule[k] for k, v in schedule.items()} print(d) # {'rotation': 6, '1': {'B': '8:32', 'C': '9:34', 'D': '10:36', 'F': '12:11', 'G': '1:13', 'H': '2:15'}, '2': {'A': '8:32', 'B': '9:34', 'C,': '10:36', 'E': '12:11', 'F': '1:13', 'G,': '2:15'}, '3': {'A': '8:32', 'B': '9:34', 'D,': '10:36', 'E': '12:11', 'F': '1:13', 'H,': '2:15'}, '4': {'A': '8:32', 'C': '9:34', 'D,': '10:36', 'E': '12:11', 'G': '1:13', 'H,': '2:15'}, '5': {'B': '8:40', 'D': '11:00', 'F': '12:55', 'H': '2:15'}, '6': {'A': '8:40', 'C': '11:00', 'E': '12:55', 'G': '2:15'}}

http://stackoverflow.com/comment/132313587
has text: This crashes: ----> 2 pdb.set_trace() 3 x = 1 4 y = 2 5 z = x * y ipdb> s [... skipped 1 hidden frame] > /usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py(3436)run_code() 3434 finally: 3435 # Reset our crash handler in place -> 3436 sys.excepthook = old_excepthook 3437 except SystemExit as e: 3438 if result is not None
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/68624669

http://stackoverflow.com/q/52689140
has body: I would like to perform some tests on my optimisation routine using scipy.optimize.minimize, in particular graphing the convergence (or the rather objective function) each iteration, over multiple tests. Suppose I have the following linearly constrained quadratic optimisation problem: minimise: x_i Q_ij x_j + a|x_i| subject to: sum(x_i) = 1 I can code this as: def _fun(x, Q, a): c = np.einsum('i,ij,j-&gt;', x, Q, x) p = np.sum(a * np.abs(x)) return c + p def _constr(x): return np.sum(x) - 1 And I will implement the optimisation in scipy as: x_0 = # some initial vector x_soln = scipy.optimise.minimize(_fun, x_0, args=(Q, a), method='SLSQP', constraints={'type': 'eq', 'fun': _constr}) I see that there is a callback argument but which only accepts a single argument of the parameter values at each iteration. How can I utilise this in a more esoteric case where I might have other arguments that need to be supplied to my callback function?
favorite count: 0
tagged with: optimization
has answer: http://stackoverflow.com/a/52689141
accepted answer: http://stackoverflow.com/a/52689141
tagged with: python
score: 2
downvote count: 0
type: Question
type: AnsweredQuestion
has title: Graphing Scipy optimize.minimize convergence results each iteration?
tagged with: matplotlib
tagged with: minimize
tagged with: scipy
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/92135824
type: Comment
has text: @vash_the_stampede Those make me dizzy
comment on: http://stackoverflow.com/a/52600436
score: 1
type: AnswerComment

http://stackoverflow.com/q/52730025
tagged with: django
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/52737990
tagged with: celery
type: Question
tagged with: django-celery
has body: I'm trying to get a function to work in my django project with celerybeat that imports a class based function from a wrapper library. I've been reading that celery doesn't work with classes too easily. my function login_mb doesn't take an argument but when I try register and call this task I get an error Couldn't apply scheduled task login_mb: login_mb() takes 0 positional arguments but 1 was given Is this because of self in the wrapper function imported? What could I do to get this to work with celerybeat? settings.py CELERY_BEAT_SCHEDULE = { 'login_mb': { 'task': 'backend.tasks.login_mb', 'schedule': timedelta(minutes=30), } , tasks.py from matchbook.apiclient import APIClient import logging from celery import task log = logging.getLogger(__name__) @shared_task(bind=True) def login_mb(): mb = APIClient('abc', '123') mb.login() mb.keep_alive() apiclient.py (wrapper library) from matchbook.baseclient import BaseClient from matchbook import endpoints class APIClient(BaseClient): def __init__(self, username, password=None): super(APIClient, self).__init__(username, password) self.login = endpoints.Login(self) self.keep_alive = endpoints.KeepAlive(self) self.logout = endpoints.Logout(self) self.betting = endpoints.Betting(self) self.account = endpoints.Account(self) self.market_data = endpoints.MarketData(self) self.reference_data = endpoints.ReferenceData(self) self.reporting = endpoints.Reporting(self) def __repr__(self): return '&lt;APIClient [%s]&gt;' % self.username def __str__(self): return 'APIClient'
has title: django celery beat arguments with imported class functions from another library
answer count: 1
tagged with: celerybeat
type: UnansweredQuestion

http://stackoverflow.com/comment/92476891
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52745001
has text: Done. I tried looking for ProcessContext in python sdk, but there doesnt seem to be any
score: 0

http://stackoverflow.com/comment/92403473
type: Comment
has text: @ugabuga77 - You can use `df['TFR'] = pd.to_numeric(df['TFR'].str[:-31])`, because there is also one value `'children born/woman (2015 est.)`
type: AnswerComment
comment on: http://stackoverflow.com/a/52738127
score: 0

http://stackoverflow.com/a/52737048
type: Answer
answers question: http://stackoverflow.com/q/52736900
upvote count: 9
downvote count: 0
has body: split() is a python method which is only applicable to strings. It seems that your column "content" not only contains strings but also other values like floats to which you cannot apply the .split() mehthod. Try converting the values to a string by using str(x).split() or by converting the entire column to strings first, which would be more efficient. You do this as follows: df['column_name'].astype(str)
score: 9

http://stackoverflow.com/q/52637153
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/93289304
has title: Run .Net and Python applications on Azure Data Factory?
has body: I am trying to create a pipeline in Azure which involves running .Net applications and python applications as part of the workflow. These applications read/write to ADLS and Azure databases. I am wondering what are the best tools for the job. So far I have landed on using ADF, with Azure Batch/Custom activity for .Net; and same or Databricks notebook/Python activity for Python as per this. (preferably avoid having to spin up a Databricks cluster.) Other options I considered: use Azure Functions for .Net (and use it in ADF) but not sure if it is only suitable for small snippets of code or entier applications. Use Logic Apps to run .net/python applications in a Docker container activity step which seems like an overkill. Thanks in advance.
type: UnansweredQuestion
tagged with: python
tagged with: azure-logic-apps
score: 1
has answer: http://stackoverflow.com/a/52735219
upvote count: 1
type: Question
tagged with: azure-data-factory
tagged with: .net
tagged with: azure

http://stackoverflow.com/q/52693345
accepted answer: http://stackoverflow.com/a/52693419
tagged with: python
has title: Pandas: Accounting for Entry Discrepancies and Specific Column Values in Tabular Summaries
favorite count: 0
answer count: 1
upvote count: 3
has answer: http://stackoverflow.com/a/52693419
has body: I've just started learning how to use Pandas and I'm trying to work with a fairly large dataset (5000 rows and 15 columns). The data has a format like this (to give an example of the issues I am facing and because I want to understand how to do this - the actual data has nothing to do with termination). ID# Firing Date Age State Position Cause 1 2011-07-03 29 NY Salesman Layoff 2 2014-03-20 25 AK salesman layoff 3 2004-08-11 42 CA Receptionist Tardiness 4 07/18/12 41 CA Mechanic Unknown 5 06/30/12 24 NY Salesman Harassment 6 05/20/12 31 NY Mechanic Harassment I need to use data like this to create tabular summaries, but after poring through the pandas documentation and somewhat similar questions for hours I am still lost. I believe I have figured out how to parse the dates by simply using that feature of read_csv(), my_df = pd.read_csv('my_dataset.csv', parse_dates = ['Hiring Date']) However I can't figure out how to go about creating a summary that accounts for every row's value in a specific column. If that value is 'Salesman' or 'salesman' in that column, then I need to compare it to the hiring date (by year), with a third column for all 'Mechanic' values, and then a fourth column that totals all the remaining position types for each year. So in the example data above, I would want to have an output that looks something like this: Year Salesman Mechanic Other Total 2004 0 0 1 1 2011 1 0 0 1 2012 1 2 0 3 2014 1 0 0 1 I've been trying for hours, but the most I've been able to do is make a table that shows all the different possible position types (which in the actual data is close to 30), and I can't figure out a way to feed my needed slice of date so it only reads the year rather than the full date (and then groups by it). Any help would be appreciated.
downvote count: 0
type: Question
tagged with: pandas
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/52729922
answers question: http://stackoverflow.com/q/52729650
has comment: http://stackoverflow.com/comment/92385089
has comment: http://stackoverflow.com/comment/92385148
downvote count: 0
type: Answer
has body: Short answer: it is possible. But context-managers allow to implement some logic, which makes it "tricky" to implemented it exactly the right way. Below you see a "Proof of Concept", but I do not guarantee that it has exactly the same behavior. Therefore I really advise to work with nested withs. What is not covered here: the __init__, or __enter__ can raise exceptions as well, and these are then handled by the "outer" context managers. This makes it of course rather complicated. You basically would need to "build" a stack in the __enter__, and then "pop" the stack in case one of the __enter__s fails. This scenario is not covered here. We can make a "composite" context manager: class C: def __init__(self, *ctxs): self.ctxs = ctxs def __enter__(self): return tuple(ctx.__enter__() for ctx in self.ctxs) def __exit__(self, self, exception_type, exception_value, traceback): for ctx in reversed(self.ctxs): try: if ctx.__exit__(exception_type, exception_value, traceback): (exception_type, exception_value, traceback) = (None,) * 3 except Exception as e: exception_value = e traceback = e.__traceback__ exception_type = type(e) return exception_value is None The __exit__ part is tricky. First of all, we need to exit in reverse order. But the exception handling is even more complicated: if an __exit__ silenced an exception, by returning a "truthful" value, then we should pass (None, None, None) as (exception_type, exeption_value, traceback), but a problem that can occur is that an __exit__ on the other hand triggers an exception itself, and thus then introduces a new exception. We can then use the context processor like: with C(A(), B()) as (a,b): # ... pass The above thus allows to implement a context manager for an arbitrary number of "sub-contextmanagers". We can subclass this to generate a specific one, like: class ContextAB(C): def __init__(self): super(ContextAB, self).__init__(A(), B()) and then use this as: with ContextAB() as (a, b): # ... pass But long story short: us…
score: 3
upvote count: 3

http://stackoverflow.com/comment/92408537
type: AnswerComment
has text: Not subdags. Airflow uses a Backend database to store metadata. Check your `airflow.cfg` file and look for `executor` keyword. By default Airflow uses `SequentialExecutor` which would execute task sequentially no matter what. So to allow Airflow to run tasks in Parallel you will need to create a database in Postges or MySQL and configure it in `airflow.cfg` (`sql_alchemy_conn` param) and then change your executor to `LocalExecutor`.
type: Comment
score: 3
comment on: http://stackoverflow.com/a/52741626

http://stackoverflow.com/comment/92345578
has text: So next time, please tag the language as well. :)) However, I am not a pythonist.
score: 0
comment on: http://stackoverflow.com/q/52709667
type: Comment
type: QuestionComment

http://stackoverflow.com/a/62541798
has body: There is another efficient way to convert the Dicom image into JPEG or PNG format using OpenCV and pydicom libraries. Here below code converts all set of dicom images into jpeg/png in one run (using for loop). import pydicom as dicom import os import cv2 # make it True if you want in PNG format PNG = False # Specify the .dcm folder path folder_path = "/Image" # Specify the output .jpg/png folder path jpg_folder_path = "/JPGImage" images_path = os.listdir(folder_path) for n, image in enumerate(sorted(images_path)): print(os.path.join(folder_path, image)) ds = dicom.dcmread(os.path.join(folder_path, image), force=True) ds.file_meta.TransferSyntaxUID = dicom.uid.ImplicitVRLittleEndian pixel_array_numpy = ds.pixel_array if PNG == False: image = image.replace('.dcm', '.jpg') else: image = image.replace('.dcm', '.png') pixel_array_numpy2 = cv2.flip(pixel_array_numpy, 0) cv2.imwrite(os.path.join(jpg_folder_path, image), pixel_array_numpy2)
score: 0
answers question: http://stackoverflow.com/q/52633803
type: Answer

http://stackoverflow.com/comment/92377891
has text: @DawidFerenczy thanks for the feedback ... please check the updates.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52726049

nlp
tags question: http://stackoverflow.com/q/52686366
tags question: http://stackoverflow.com/q/52663935
tags question: http://stackoverflow.com/q/52718910
tags question: http://stackoverflow.com/q/52702431
tags question: http://stackoverflow.com/q/52725193
tags question: http://stackoverflow.com/q/52675017
tags question: http://stackoverflow.com/q/52686640
tags question: http://stackoverflow.com/q/52663908
tags question: http://stackoverflow.com/q/52704990
tags question: http://stackoverflow.com/q/52702653
tags question: http://stackoverflow.com/q/52660336
tags question: http://stackoverflow.com/q/52734146
tags question: http://stackoverflow.com/q/52729565
tags question: http://stackoverflow.com/q/52590111
tags question: http://stackoverflow.com/q/52734659
tags question: http://stackoverflow.com/q/52707075
tags question: http://stackoverflow.com/q/52693004
tags question: http://stackoverflow.com/q/52598117
tags question: http://stackoverflow.com/q/52609382
tags question: http://stackoverflow.com/q/52612455
tags question: http://stackoverflow.com/q/52677634
tags question: http://stackoverflow.com/q/52688019
tags question: http://stackoverflow.com/q/52704301
tags question: http://stackoverflow.com/q/52665291
tag name: nlp
tags question: http://stackoverflow.com/q/52703283
type: Tag
tags question: http://stackoverflow.com/q/52723687
tags question: http://stackoverflow.com/q/52645459
tags question: http://stackoverflow.com/q/52598788
tags question: http://stackoverflow.com/q/52597532
tags question: http://stackoverflow.com/q/52712731
tags question: http://stackoverflow.com/q/52724444
tags question: http://stackoverflow.com/q/52743248
tags question: http://stackoverflow.com/q/52720624

http://stackoverflow.com/comment/92363084
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52717595
has text: I have figured out a hack for this. posting it so it might help. The first offsite_conversion.* key in the response it the actual result event that the campaign is optimised for, Though this is a hack, I am pretty sure that there is some other better way to get the campaign/ adset settings. Will keep this thread posted if i get any further with this.

http://stackoverflow.com/q/52619740
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52619830
tagged with: python
tagged with: regex
has title: Python extract session id from string url
has answer: http://stackoverflow.com/a/52637972
score: 0
has body: I have a url: mywebsite.com/idp/profile/SAML2/Redirect/SSO;jsessionid=CED11D31669BEAB45B4CDA651C7EBF3B.idp03?execution=e1s1 I want to extract the jsessionid value after the semicolon but before the .idp03: CED11D31669BEAB45B4CDA651C7EBF3B How might I do this with Python?
type: Question
has answer: http://stackoverflow.com/a/52619751

http://stackoverflow.com/comment/92300866
type: QuestionComment
has text: @Sinai: Only English language need to use in your question. Please edit with correct value of "ﺱﺭﻭﺭ ﺎﺨﺘﺻﺎﺻی" in English language.
comment on: http://stackoverflow.com/q/52686547
score: 0
type: Comment

http://stackoverflow.com/q/52734146
has answer: http://stackoverflow.com/a/52746111
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/57250579
tagged with: gensim
tagged with: nlp
type: UnansweredQuestion
tagged with: word2vec
tagged with: python
upvote count: 7
has body: I'm working on a NLP application, where I have a corpus of text files. I would like to create word vectors using the Gensim word2vec algorithm. I did a 90% training and 10% testing split. I trained the model on the appropriate set, but I would like to assess the accuracy of the model on the testing set. I have surfed the internet for any documentation on accuracy assessment, but I could not find any methods that allowed me to do so. Does anyone know of a function that does accuracy analysis? The way I processed my test data was that I extracted all the sentences from the text files in the test folder, and I turned it into a giant list of sentences. After that, I used a function that I though was the right one (turns out it wasn't as it gave me this error: TypeError: don't know how to handle uri). Here is how I went about doing this: test_filenames = glob.glob('./testing/*.txt') print("Found corpus of %s safety/incident reports:" %len(test_filenames)) test_corpus_raw = u"" for text_file in test_filenames: txt_file = open(text_file, 'r') test_corpus_raw += unicode(txt_file.readlines()) print("Test Corpus is now {0} characters long".format(len(test_corpus_raw))) test_raw_sentences = tokenizer.tokenize(test_corpus_raw) def sentence_to_wordlist(raw): clean = re.sub("[^a-zA-Z]"," ", raw) words = clean.split() return words test_sentences = [] for raw_sentence in test_raw_sentences: if len(raw_sentence) &gt; 0: test_sentences.append(sentence_to_wordlist(raw_sentence)) test_token_count = sum([len(sentence) for sentence in test_sentences]) print("The test corpus contains {0:,} tokens".format(test_token_count)) ####### THIS LAST LINE PRODUCES AN ERROR: TypeError: don't know how to handle uri texts2vec.wv.accuracy(test_sentences, case_insensitive=True) I have no idea how to fix this last part. Please help. Thanks in advance!
has title: Word2vec Gensim Accuracy Analysis
score: 7
type: Question
answer count: 2

http://stackoverflow.com/q/52631631
has comment: http://stackoverflow.com/comment/92198086
favorite count: 0
has body: I am upto creating a lookup table for a Human modelling software, Makehuman I have to translate its scale into real world metric scale for that I am creating lookup tables. It has 25 parameters that needs to be varied, I am using nested for loops for that and store values finally in database SQlite . Please anyone tell me how can I modify my code or use some other technique to overcome this exception, because this has to run anyhow for the completion of my project. Thank You.
has answer: http://stackoverflow.com/a/52631687
score: -3
tagged with: python
type: AnsweredQuestion
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/92196681
accepted answer: http://stackoverflow.com/a/52631687
has title: How to use more than 20 nested for loops in python3 program without any exception of too many statically nested blocks?
tagged with: nested-loops
upvote count: 0
answer count: 1

http://stackoverflow.com/q/52716461
tagged with: anaconda
has comment: http://stackoverflow.com/comment/92375743
has comment: http://stackoverflow.com/comment/92405848
score: 0
has title: Test Anaconda build after updating packages
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92387802
tagged with: build
linked to: http://stackoverflow.com/q/52602576
answer count: 0
has body: I use conda update --all to update my packages. Recently, I encountered an error with Anaconda build, posted at Error while trying to update and use scipy module in Anaconda. It seems now the issue has been fixed. Is there any way, I can test all modules one by one by importing them and deleting them ? I am requesting this because I have noticed that if import doesn't work, I spend a lot of time figuring out the dependency and then the package that is causing this. For instance, a few minutes ago I found that PyCharm 2018.2.4 breaks with the latest version of matplotlib (3.0.0). Hence, it might be helpful to run some type of test script after running conda update --all to ensure that all packages are indeed working--i.e. importable. I did some research on this topic and found three sources. First, Anaconda offers run_test.py (Source: https://conda.io/docs/user-guide/tasks/build-packages/recipe.html). However, being new to the world of Python, I am unsure how to go about running a script in Anaconda terminal. Second, I found: https://conda.io/docs/user-guide/install/test-installation.html. However, this just tells me the version of the package. I am not interested in the version. I need to know whether all packages import properly. Finally, I found out that there is a method to run test script for all packages at https://anaconda-installer.readthedocs.io/en/latest/testing.html. However, I am unsure how I can run make in Anaconda terminal. I used to use make long time ago when I worked on gcc on Unix environment. Being new to Python, I am unsure how to go about handling this. I'd appreciate any thoughts or any test script that could help us verify two things: a) whether all packages have been installed b) packages are indeed importable; If the package import fails, the script should terminate with handsome error message highlighting the source (package) where import failed.
has comment: http://stackoverflow.com/comment/92427880
tagged with: updates
type: Question

http://stackoverflow.com/comment/92384522
has text: `C` must become a context manager, meaning it implements some special methods. Specification is in [PEP 343](https://www.python.org/dev/peps/pep-0343/#specification-the-with-statement)
comment on: http://stackoverflow.com/q/52729650
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/92348706
type: QuestionComment
type: Comment
has text: Where did I pass array of strings? my first column is Date and second is float
comment on: http://stackoverflow.com/q/52711149
score: 0

http://stackoverflow.com/q/52731407
has comment: http://stackoverflow.com/comment/92411990
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: A friend of mine wrote python code on a Mac, and now I'm trying to get it to work on a windows laptop. This line in particular is being annoying: os.system("stty echo") Anyone know a windows equivalent? I've already replaced tty with msvcrt, but I am completely stuck on this.
has comment: http://stackoverflow.com/comment/92388575
has comment: http://stackoverflow.com/comment/92390182
has answer: http://stackoverflow.com/a/53135109
type: Question
has title: Any ideas how to replace os.system("stty echo") to work in windows?
tagged with: stty
answer count: 1
score: -1
has comment: http://stackoverflow.com/comment/92412041
has comment: http://stackoverflow.com/comment/119912975
linked to: http://stackoverflow.com/q/22832933
tagged with: python-2.7
downvote count: 2
upvote count: 1
tagged with: windows
has comment: http://stackoverflow.com/comment/92388461

http://stackoverflow.com/comment/92378175
has text: Though it's worth saying that the logic goes in before the `break`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52726481

http://stackoverflow.com/comment/92405580
type: AnswerComment
has text: thanks for the suggestion, but it seems to make little difference.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52736392

http://stackoverflow.com/q/52699358
has answer: http://stackoverflow.com/a/52699532
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92325358
has comment: http://stackoverflow.com/comment/92325833
has comment: http://stackoverflow.com/comment/92326301
has comment: http://stackoverflow.com/comment/92325971
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52699532
has comment: http://stackoverflow.com/comment/92326651
has comment: http://stackoverflow.com/comment/92326187
has body: Consider the following example: test = 123 f = lambda x,test=test: print(x, test) del test f('hello') prints hello 123 By capturing the variable in the lambda definition, the original variable seems to be retained. Is the lambda ok to use when you could also use a simple object to store the same data? class Test: def __init__(self, some_data): self.some_data = some_data def f(self, x): print(x, self.some_data) t = Test('123') t.f('hello')
has comment: http://stackoverflow.com/comment/92326822
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92325392
has comment: http://stackoverflow.com/comment/92325207
has title: Python lambda capturing external variables
tagged with: python
tagged with: lambda
possible better answer: http://stackoverflow.com/a/52699502
has comment: http://stackoverflow.com/comment/92325337
has answer: http://stackoverflow.com/a/52699502
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92325944
has comment: http://stackoverflow.com/comment/92325395

collatz
tags question: http://stackoverflow.com/q/52745085
type: Tag
tags question: http://stackoverflow.com/q/52635518
tag name: collatz
tags question: http://stackoverflow.com/q/52728461

http://stackoverflow.com/comment/92145240
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52605539
has text: How did I not know this? I am used to `x or y`, I use it all the time for assignments when `x` is falsy, but I did not know it what a thing for `and` too. Can you link to the docs where they cover this matter and especially the reasoning of implementing this behavior?
type: AnswerComment

http://stackoverflow.com/q/52609848
tagged with: python-3.x
has title: Create df that holds column name and corresponding value of another dataframe
tagged with: python
has answer: http://stackoverflow.com/a/52610786
type: AnsweredQuestion
has body: I have created the following dataframe called df col1 col2 col3 0 4 5 2 1 5 2 4 2 3 10 3 3 6 2 2 4 3 2 4 What I would like now is to flip the rows so that the df looks like this: column_name value 0 col1 4 1 col2 5 2 col3 2 3 col1 5 4 col2 2 5 col3 4 ... ... ... I think I need to use stack(), but I'm not sure how. I've tried the following df = df.stack().rename_axis(['column_name']).reset_index(name = 'value') but that returns the following error raise ValueError('Length of names must match number of levels in ' ValueError: Length of names must match number of levels in MultiIndex. Question: how do I stack the values so that I get the desired dataframe?
has answer: http://stackoverflow.com/a/52609880
linked to: http://stackoverflow.com/q/28654047
possible better answer: http://stackoverflow.com/a/52610786
type: Question
downvote count: 0
tagged with: dataframe
score: 4
has comment: http://stackoverflow.com/comment/92154855
upvote count: 4
accepted answer: http://stackoverflow.com/a/52609880
answer count: 2
tagged with: pandas
favorite count: 0

http://stackoverflow.com/comment/92125644
score: 0
type: Comment
type: QuestionComment
has text: no. here it will give error if i will put indentation afetr row[field]
comment on: http://stackoverflow.com/q/52595408

http://stackoverflow.com/comment/92313501
type: Comment
has text: I never used websockets library, but I use [websocket-client](https://pypi.org/project/websocket-client/) on a daily basis and it seems to do the job very well. You can create a connection `ws = create_connection(someWsUrl)`, and then you can use `ws.send`, `ws.recv`, or `ws.close`. I can put a little exmaple. On the installation side, `pip install websocket-client`, and finally to import the module : `from websocket import create_connection`. Hope it helps.
score: 1
comment on: http://stackoverflow.com/q/52692736
type: QuestionComment

http://stackoverflow.com/comment/98221532
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52701095
has text: @SebiSebi It's hard to understand what is wrong without seeing your code. Please ask a new question, providing enough details (i.e. your code, what you expect, full error log, etc.). Then surely people can help you much better.

http://stackoverflow.com/comment/92310095
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52691503
has text: Update the question with a bit of the _outerHTML_

http://stackoverflow.com/a/73496266
score: 0
has body: Python's standard lib zipfile handles multiple files and has supported bz2 compression since 2001. import zipfile sourcefiles = ['a.txt', 'b.txt'] with zipfile.ZipFile('out.zip', 'w') as outputfile: for sourcefile in sourcefiles: outputfile.write(sourcefile, compress_type=zipfile.ZIP_BZIP2)
type: Answer
answers question: http://stackoverflow.com/q/52646982

http://stackoverflow.com/q/52673702
type: Question
has comment: http://stackoverflow.com/comment/93851094
has comment: http://stackoverflow.com/comment/121626293
tagged with: pyautogui
answer count: 2
upvote count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/56949628
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/55149178
score: 1
has title: PyAutoGUI: How do I shift select in Excel?
has body: I am trying to use PyAutoGUI (Python 3.7 64-bit) to copy a column of cells in Excel from one sheet to another. The code is: import pyautogui as gui gui.PAUSE = 1 gui.FAILSAFE = True gui.keyDown('shift') gui.typewrite(['down']*67) gui.keyUp('shift') gui.keyDown('ctrl') gui.press('c') gui.keyUp('ctrl') which should hold down shift, click the down arrow 67 times to select the cells I want, then release shift. Following this, the text will be copied to the clipboard. When run (with the top cell pre-selected), the delay of each step is noticeable, but it is as if shift is not held down. The selected cell moves to the bottom, but the previous cells are not selected. At the bottom, the last cell is copied. It seems as though 'ctrl' is working, but 'shift' is not. If I stop before running keyUp on shift, when the program ends, my computer is act as if shift is being help down until I press the key again. I have also tried using 'shiftright' in case that was the issue but it made no difference. There are a number of PyAutoGUI functions run before these, but none have to do with the state of these keys. I have also been looking at alternatives to select these cells without using shift but haven't been able to find anything. Does anyone have suggestions on this?
has answer: http://stackoverflow.com/a/68819302
linked to: http://stackoverflow.com/q/56949628
tagged with: excel

http://stackoverflow.com/comment/92792245
comment on: http://stackoverflow.com/a/52713593
type: Comment
score: 0
type: AnswerComment
has text: What do you mean? it will print all the urls

http://stackoverflow.com/q/52723721
has body: my_list=[] x=input('Random Word:') my_list.append(x) print(my_list) If i input: Hi,My,Name,Is,Jeff The output is: ['Hi,My,Name,Is,Jeff']` Question: How can i get the output like this` ['Hi','My','Name','Is','Jeff']
duplicate of: http://stackoverflow.com/q/3475251
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52723784
has comment: http://stackoverflow.com/comment/92372778
type: Question
has comment: http://stackoverflow.com/comment/92372809
score: 0
accepted answer: http://stackoverflow.com/a/52723784
linked to: http://stackoverflow.com/q/4071396
answer count: 1
has title: Splitting list in a list
duplicate of: http://stackoverflow.com/q/4071396

http://stackoverflow.com/comment/92298866
type: Comment
has text: Hi ASGM, this is exactly what I was trying to do, your solution works perfectly. Thanks a ton :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52680164

http://stackoverflow.com/comment/92210015
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52638534
has text: There are three things to know about recursion: 1. how recursion works 2. that you don't use it if there is an other way and 3. there's always an other way.

http://stackoverflow.com/comment/92177938
comment on: http://stackoverflow.com/a/52621748
type: AnswerComment
type: Comment
has text: I have tried but I cannot control the command line after startting the batch file.
score: 0

http://stackoverflow.com/comment/92184635
has text: A result should be endless
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52625580

http://stackoverflow.com/comment/92209188
comment on: http://stackoverflow.com/q/52636864
type: QuestionComment
has text: I suspect using prepared statement placeholders instead of inserting arbitrary user-provided text directly into a query string will make a difference, as well as not opening you up to [sql injection](http://bobby-tables.com/).
score: 0
type: Comment

http://stackoverflow.com/comment/92274066
type: Comment
comment on: http://stackoverflow.com/q/52671935
score: 0
type: QuestionComment
has text: `.match` will only work with input: `'$ math-mult {5|8}'` when `pos=0` but for any other `pos` value it will fail.

http://stackoverflow.com/comment/92196976
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52631840
has text: What is `for x in range(1):` doing there?
score: 0

http://stackoverflow.com/comment/92130485
comment on: http://stackoverflow.com/q/52597716
type: Comment
has text: I am open to any sources you have for learning python. And when I started I wasn't sure if I should start with Python 2.x or 3.x I was just really eager to get the ball rolling.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92288689
comment on: http://stackoverflow.com/q/52678790
has text: That would be this part I think `for react in self.buttons: await current.add_reaction(str(react))`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52658262
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52658210
type: Answer
accepted answer of: http://stackoverflow.com/q/52658210
score: 1
upvote count: 1
downvote count: 0
has body: It looks like what you are trying to do, is define a class attribute a in class Triangle. You don't need self to do that. self is used to access the object instance of a class. If you would want to define a as an object attribute rather than a class attribute, you should do something like: class Triangle(Polygon): def __init__(self): Polygon.__init__(self, 3) self.a = 1 In this case, a is only defined upon class instantiation and accessible as Triangle().a, or as self.a inside other object-scope methods. And if you want to define a as a class attribute, simply do: class Triangle(Polygon): a = 1 def __init__(self): ... In this case, a is defined upon class definition and accessible even before instantiation, as Triangle.a

http://stackoverflow.com/comment/92364859
has text: Right, because the `BaseHTTPRequestHandler.__init__(self, *args, **kwargs)` call starts handling requests. Move your two lines that assign `self.Event_dictionary_list` and `self.cached_timestamp` *up* to run before you call `BaseHTTPRequestHandler.__init__(self, *args, **kwargs)`.
score: 0
comment on: http://stackoverflow.com/q/52718687
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52592102
accepted answer of: http://stackoverflow.com/q/52591696
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52591696
type: Answer
has comment: http://stackoverflow.com/comment/92120105
has body: An OrderedDict would probably be more conventional than using a series for this. from collections import OrderedDict d = OrderedDict([("A1", df1), ("A2", df2), ("A3", df3)]) This can easily be iterated over: for label, df in d: print(label, df) That said I can't see any strong reason not to use a pandas series. A small advantage of using the series is that you can access the dataframes using dot notation s.A1, s.A2 etc. as well as using the dictionary-like notation s["A1"]. Using a series, it would also be relatively easy to sort the dataframes, insert additional ones in the middle, or associate additional metadata with them later if needed. (See this question on dictionary ordering in Python 3.6 and 3.7 - you may be able to use an ordinary dictionary instead of an OrderedDict if using Python 3.7 and you don't need to use other 'ordered' behaviours. In Python 3.6, the preservation of insertion order is an implementation detail and should not be relied upon.)
upvote count: 5
score: 5

http://stackoverflow.com/q/52612040
upvote count: 1
type: Question
has body: So I've been doing LPTHW, and you know that 'make a text-based RPG' we're supposed to do? Well, I've certainly been doing it, but every time I try to run it, this error pops up: File "DimensionSpace.py", line 826, in &lt;module&gt; a_game.play() File "DimensionSpace.py", line 22, in play next_scene_name = current_scene.enter() AttributeError: 'function' object has no attribute 'enter' I'm actually fairly confused. That part is the part I stuck with the book for. Here's what the code looks like: from sys import exit from random import randint from textwrap import dedent class Scene(object): def enter(self): print("This scene is not yet configured.") print("Subclass it and implement enter().") exit(1) class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene last_scene = self.scene_map.next_scene('credits') while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) current_scene.enter() Can someone please help me?
tagged with: attributeerror
has title: Making a simple text rpg and there's an attribute error?
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52612916
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92158999
has comment: http://stackoverflow.com/comment/92159782
tagged with: python
score: 1

http://stackoverflow.com/a/52746790
type: Answer
answers question: http://stackoverflow.com/q/52744477
downvote count: 0
score: 1
upvote count: 1
has body: Usually, I would use a dictionary for something like this but since your representation of a dice is a list (unhashable) you can convert them into a frozenset or a tuple. I prefer a tuple since it preserves order and repetition (if any). num_rounds = 100 dice_wins = {tuple(x):0 for x in dices} for dice1, dice2 in it.combinations(dices, 2): for _ in range(num_rounds): dice1_result = dice1[randint(0, 5)] dice2_result = dice2[randint(0, 5)] if dice1_result &gt; dice2_result: dice_wins[tuple(dice1)] += 1 elif dice2_result &gt; dice1_result: dice_wins[tuple(dice2)] += 1 max_win = max(list(dice_wins.values())) die_with_max_win = [dice for dice in dices if dice_wins[tuple(dice)] == max_win] if len(die_with_max_win) == 1: return die_with_max_win[0] # only dice with that many wins else: return -1 # more than one dice with max wins Hope this helps!

http://stackoverflow.com/a/52592147
score: 2
upvote count: 2
type: Answer
has body: How about... with ContextManager(**args) if some_condition else OtherContextManager(**other_args) as contex: ... # some block ...?
answers question: http://stackoverflow.com/q/52592037
downvote count: 0

http://stackoverflow.com/q/52596340
score: 1
has comment: http://stackoverflow.com/comment/92127666
tagged with: dataframe
linked to: http://stackoverflow.com/q/22086116
tagged with: boolean
tagged with: pandas
has comment: http://stackoverflow.com/comment/92127717
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52596688
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Python filtering error. Boolean Series key will be reindexed to match DataFrame index.
has comment: http://stackoverflow.com/comment/92127582
upvote count: 1
has comment: http://stackoverflow.com/comment/92206481
has body: I am struggling to get this code that I wrote to work. I know it is probably an easy fix but I can't seem to get it to work correctly. In essence, what I want is to create a boolean mask on a pandas dataframe that returns only rows where the values in "Actual Manufacturer" or "Actual Collection" exist in "PqaQuestion". It works well with one set of criteria but adding in multiple criteria messes things up a bit. I can't seem to get the "or" operator in there without triggering the userwarning: boolean series key will be reindexed to match dataframe index, which does mess up the output. If anyone could help fix this issue but also help me understand why this happens I would greatly appreciate it. I've seen other posts about the subject but none that explain it and I can't seem to tailor other posts to my own situation. names= ['PqaPrSKU', 'PrName', 'White Label Manufacturer', 'White Label Collection', 'Actual Manufacturer', 'Actual MaID', 'Actual Collection', 'PqaID', 'PqaQuestion', 'UpdatedQuestion', 'PanID', 'PanAnswer', 'UpdatedAnswer', 'DateAdded', 'PrBclgID'] def match_function(column1_value, column2_value, column3_value): return (column2_value is not None) and (column1_value is not None) and (column3_value is not None) and (str(column2_value).lower() in str(column1_value).lower()) or (str(column3_value).lower() in str(column1_value).lower()) import pandas as pd df = pd.read_csv('Bucket61(8.22).csv', names= names, skipinitialspace=True, skiprows=1) #print(df.from_records(data)) indexer = df.apply(lambda row: match_function(row["PqaQuestion"], row["Actual Collection"], row["Actual Manufacturer"]), axis=1) filtered_df = df[indexer] print(filtered_df[indexer]) #print(df[indexer]) from pandas import ExcelWriter writer = ExcelWriter('ScrubbedQATemplate.xlsx') filtered_df.to_excel(writer, 'Sheet1') writer.save()
type: Question
tagged with: filtering

http://stackoverflow.com/comment/92271666
has text: @Ralf okay this is it but how to append it in an array and not an array of dictionary for example ["name",0,0,3] and loop through the rows and append each row to the array
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52670717

http://stackoverflow.com/a/52630079
has comment: http://stackoverflow.com/comment/92193996
score: 6
answers question: http://stackoverflow.com/q/52629767
has comment: http://stackoverflow.com/comment/92194293
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52629767
has comment: http://stackoverflow.com/comment/92193604
type: Answer
has body: The documentation of sklearn.svm.SVC is right here. Parameter class_weight doesn't accept 'auto' as an input value. That is your error. You can solve this by replacing: 'class_weight': ['auto'] with: 'class_weight': ['balanced']
upvote count: 6

http://stackoverflow.com/q/52636328
has body: Hi I am trying to build a Mixture-of-experts neural network. I found a code here: http://blog.sina.com.cn/s/blog_dc3c53e90102x9xu.html. My goal is that the gate and expert come from different data, but with same dimensions. def sliced(x,expert_num): return x[:,:,:expert_num] def reduce(x, axis): return K.sum(x, axis=axis, keepdims=True) def gatExpertLayer(inputGate, inputExpert, expert_num, nb_class): #expert_num=30 #nb_class=10 input_vector1 = Input(shape=(inputGate.shape[1:])) input_vector2 = Input(shape=(inputExpert.shape[1:])) #The gate gate = Dense(expert_num*nb_class, activation='softmax')(input_vector1) gate = Reshape((1,nb_class, expert_num))(gate) gate = Lambda(sliced, output_shape=(nb_class, expert_num), arguments={'expert_num':expert_num})(gate) #The expert expert = Dense(nb_class*expert_num, activation='sigmoid')(input_vector2) expert = Reshape((nb_class, expert_num))(expert) #The output output = tf.multiply(gate, expert) #output = keras.layers.merge([gate, expert], mode='mul') output = Lambda(reduce, output_shape=(nb_class,), arguments={'axis': 2})(output) model = Model(input=[input_vector1, input_vector2], output=output) model.compile(loss='mean_squared_error', metrics=['mse'], optimizer='adam') return model However, I got "'NoneType' object has no attribute '_inbound_nodes'". I checked other similar questions here: AttributeError: 'NoneType' object has no attribute '_inbound_nodes' while trying to add multiple keras Dense layers but the problem is fixed with the Lambda function of keras to convert into a layer.
tagged with: python
tagged with: lambda
score: 2
type: AnsweredQuestion
upvote count: 2
has title: NoneType' object has no attribute '_inbound_nodes'
type: Question
tagged with: nonetype
linked to: http://stackoverflow.com/q/52448652
has answer: http://stackoverflow.com/a/52636813
downvote count: 0
answer count: 1
tagged with: neural-network
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/52636813

http://stackoverflow.com/comment/92336813
has text: can you show the full html or the url?
comment on: http://stackoverflow.com/q/52705038
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92239931
comment on: http://stackoverflow.com/q/52654160
score: 0
type: Comment
type: QuestionComment
has text: Since the threshold and size are same, yes I have verified with multiple chunks, the chunks are working

http://stackoverflow.com/comment/92379604
type: Comment
has text: For example: If you see john does not have perday data so it should be 'null ' ''.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52727148

http://stackoverflow.com/q/52596761
has comment: http://stackoverflow.com/comment/92131104
has comment: http://stackoverflow.com/comment/92130792
answer count: 0
has comment: http://stackoverflow.com/comment/92128910
has body: I'm having having difficulties integrating dotpay payment gateway in saleor. I'm not sure how am I suppose to pass Chk parameter to dotpay. Saleor is using django-payments for that: https://github.com/mirumee/django-payments/blob/master/payments/dotpay/forms.py Dotpay docs: https://ssl.dotpay.pl/s2/login/cloudfs1/magellan_media/common_file/dotpay_technical_manual_for_payments_implementation.pdf So far I've got set up: PAYMENT_VARIANTS = { 'dotpay': ('payments.dotpay.DotpayProvider', { 'seller_id': '123', 'pin': '0000', 'lock': True, 'endpoint': 'https://ssl.dotpay.pl/test_payment/'})} and CHECKOUT_PAYMENT_CHOICES = [ ('default', 'Dotpay')]
type: Question
has comment: http://stackoverflow.com/comment/92128498
tagged with: saleor
has comment: http://stackoverflow.com/comment/92128465
score: 0
has comment: http://stackoverflow.com/comment/92128279
has title: How to pass `Chk` parameter to dotpay payments gateway in Django (Saleor)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92130260
tagged with: django
tagged with: python

http://stackoverflow.com/comment/92270908
has text: The script is complete and I described the data. I can generate a sample random data in pandas and include the code. Would that help?
comment on: http://stackoverflow.com/q/52665061
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92327478
type: QuestionComment
has text: You can look into [lambda functions](https://www.programiz.com/python-programming/anonymous-function). As a super brief explanation, you are saying "I want you to sort by the first item in the tuple - the key - after you cast it to lowercase". The `key` argument will take lambda functions and apply them to allow you to change the default sorting rule
score: 1
comment on: http://stackoverflow.com/q/52700212
type: Comment

http://stackoverflow.com/comment/92340089
comment on: http://stackoverflow.com/a/52705740
type: Comment
has text: Thanks for the amazing answer. So, as I understand your script stops around the square with length 3 around all the starting points but the first one? Also do you have any recommendation for the plots around the boundary? I was thinking of masking all the values at boundary (x,y = lsize), but this would leave a gap in the plot
type: AnswerComment
score: 0

http://stackoverflow.com/q/52651255
has answer: http://stackoverflow.com/a/52660418
type: AnsweredQuestion
has body: I am following the instructions here to use the Python SDK for Apimatic's API. My folder structure looks like this: apimatic | -- apimatic | -- test | | | -- testsdk.py | -- requirements.txt testsdk.py contains the following code: from apimatic.apimatic_client import ApimaticClient When I run python3 test/testsdk.py I get this error: ModuleNotFoundError: No module named 'apimatic' I get the same error when I run PYTHONPATH=../ python3 test/testsdk.py I have run pip3 install -r requirements.txt
has title: Apimatic Python SDK returns ModuleNotFoundError
type: Question
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/52660418
tagged with: python

http://stackoverflow.com/comment/92165099
comment on: http://stackoverflow.com/q/52615251
score: 0
has text: "not use lists, the split method, python string methods, the keyword "in", and i may only use indexing to access the first character of a string, and slicing to get the tail of the string." ... When beggers become choosers hehe sounds like me picking a girlfriend
type: Comment
type: QuestionComment

smtplib
tags question: http://stackoverflow.com/q/52607070
type: Tag
tags question: http://stackoverflow.com/q/52628387
tags question: http://stackoverflow.com/q/52611868
tag name: smtplib

http://stackoverflow.com/q/52625388
accepted answer: http://stackoverflow.com/a/52625609
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/52625609
tagged with: nltk
tagged with: lemmatization
upvote count: 1
linked to: http://stackoverflow.com/q/43747659
answer count: 1
has body: I'm a newbie and struggling with what I'm sure is a simple task. I have a list of words taken from POS tagging: words = ['drink', 'drinking'] And I want to lemmatize them and then process them (using set?) to ultimately refine my list to: refined_list = ['drink'] However, I"m stuck on the next step of lemmatization - my method still returns the following: refinded_list = ['drink', 'drinking'] I tried to reference this but can't figure out what to import so 'lmtzr' works or how to get it to work. Here's my code so far: import nltk words = ['drink', 'drinking'] WNlemma = nltk.WordNetLemmatizer() refined_list = [WNlemma.lemmatize(t) for t in words] print(refined_list) Thank you for helping me.
has comment: http://stackoverflow.com/comment/92208588
favorite count: 0
tagged with: python-3.x
has title: Iterate and Lemmatize List
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/54386118
type: Answer
has comment: http://stackoverflow.com/comment/117328524
score: 24
upvote count: 25
type: AcceptedAnswer
downvote count: 1
has body: I had the same problem and I solved it by recovering my old .bashrc file then I can load the bash configuration file of Anaconda whenever I need it. To achieve this , follow these steps Rename your current .bashrc file to something like conda.bashrc by executing these commands in your terminal cd ~ mv .bashrc conda.bashrc mv .bashrc-anaconda3.bak .bashrc Now, you have to define a custom command in your .bashrc file so it can load Anaconda only when you need it, to do so first you need to open your .bashrc file in a text editor gedit .bashrc Add the following lines to end of your .bashrc so it can load the other conda.bashrc file which contain anaconda package configurations alias anaconda='source ~/.conda.bashrc' save .bashrc with the above mentioned edits and type in your terminal window source .bashrc now you can load anaconda by simply typing anaconda in your terminal window anaconda
answers question: http://stackoverflow.com/q/52706888
accepted answer of: http://stackoverflow.com/q/52706888

tweepy
tags question: http://stackoverflow.com/q/52744485
tags question: http://stackoverflow.com/q/52660820
tags question: http://stackoverflow.com/q/52591066
type: Tag
tags question: http://stackoverflow.com/q/52688864
tags question: http://stackoverflow.com/q/52609813
tags question: http://stackoverflow.com/q/52657839
tag name: tweepy

http://stackoverflow.com/q/52643763
has comment: http://stackoverflow.com/comment/92224014
has comment: http://stackoverflow.com/comment/92224149
has comment: http://stackoverflow.com/comment/92222049
has comment: http://stackoverflow.com/comment/92360661
type: Question
has comment: http://stackoverflow.com/comment/92219883
has comment: http://stackoverflow.com/comment/92222903
has body: Using askopenfilename I have opened the directory. But, I do not want to open the file, I would need it, just to see the files present in that particular path. I want to see the path folder content after clicking the button in the frame. Not only to see the content in the path but also to move back and fro too. So I would like to delete the options (Datename, open, close) at the end. Is there anyway I can solve the problem. Here is my used code: f1 = Frame(root) for frame in (f1): frame.grid(row=0, column=0) frame1 = ttk.LabelFrame(f1, text="Data") frame1.grid(row=1, column=5, padx=(30,10), pady=(10,0), columnspan=2) b01 = ttk.Button(frame1, text="New", compound = "left", width=12, command=Dir_Data) b01.grid(row=4, column=5, padx=20, pady=5, ipadx=5, ipady=5) def Dir_Data(): directory = "C:\Req_file\date_files" temp = filedialog.askopenfile(initialdir=directory)
has title: With askopenfilename delete the options (open, close) at the end
has comment: http://stackoverflow.com/comment/92222371
has comment: http://stackoverflow.com/comment/92221974
score: 0
has comment: http://stackoverflow.com/comment/92224356
has comment: http://stackoverflow.com/comment/92219790
has comment: http://stackoverflow.com/comment/92222180
has comment: http://stackoverflow.com/comment/92223775
tagged with: tkinter
has comment: http://stackoverflow.com/comment/92223269
answer count: 0
has comment: http://stackoverflow.com/comment/92222258
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92224253
tagged with: python
has comment: http://stackoverflow.com/comment/92223162

http://stackoverflow.com/comment/92316650
has text: @NisseEngström I have fixed it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52694936
score: 0

http://stackoverflow.com/q/52659057
upvote count: 0
accepted answer: http://stackoverflow.com/a/52659392
has title: How to ignore child elements in beautifulsoup4
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has answer: http://stackoverflow.com/a/52659392
downvote count: 1
type: AnsweredQuestion
has body: I'm using BeautifulSoup4 to extract data from a website about course offerings. I'm trying to extract just the course descriptions from a &lt;p&gt; element. When I run: course_descriptions = soup.findAll("p") I get: &lt;p&gt;&lt;b&gt;INFO 101 Social Networking Technologies (5) I&amp;amp;S/NW&lt;/b&gt;&lt;br/&gt;Explores today's most popular social networks, gaming applications, and messaging applications. Examines technologies, social implications, and information structure. Focuses on logic, databases, networked delivery, identity, access, privacy, ecommerce, organization, and retrieval. &lt;br/&gt;&lt;a href="https://uwstudent.washington.edu/course/#/courses/INFO101" target="_blank"&gt; View course details in MyPlan: INFO 101&lt;/a&gt;&lt;/p&gt;, &lt;p&gt;&lt;b&gt;INFO 102 Gender and Information Technology (5) I&amp;amp;S, DIV&lt;/b&gt;&lt;br/&gt;Explores the social construction of gender in relation to the history and contemporary development of information technologies. Considers the importance of diversity and difference in the design and construction of innovative information technology solutions. Challenges prevailing viewpoints about who can and does work in the information technology field. Offered: A.&lt;br/&gt;&lt;a href="https://uwstudent.washington.edu/course/#/courses/INFO102" target="_blank"&gt;View course details in MyPlan: INFO 102&lt;/a&gt;&lt;/p&gt;, I want to get these results, but without what's in the &lt;b&gt;&lt;/b&gt; tags. How can I exclude them from my results?
score: -1
tagged with: web-scraping
type: Question

http://stackoverflow.com/q/52635941
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92219587
answer count: 0
type: UnansweredQuestion
has body: Actually I'm just trying to install discord via pip and after some initial trouble achieving this. However I still get a traceback error. "ModuleNotFoundError: No module named 'aiohttp'" I tried so much now, via pip there is again an error: Microsoft Windows [Version 10.0.17134.285] (c) 2018 Microsoft Corporation. Alle Rechte vorbehalten. C:\Users\Laptop&gt;pip install aiohttp Collecting aiohttp Using cached https://files.pythonhosted.org/packages/7a/58/4476d96f35cc18a5133330f06c9ff3bc44fa64a9b6d15d2716efa6043b80/aiohttp-3.4.4-cp37-cp37m-win32.whl Requirement already satisfied: chardet&lt;4.0,&gt;=2.0 in c:\users\laptop\appdata\local\programs\python\python37-32\lib\site-packages (from aiohttp) (3.0.4) Collecting yarl&lt;2.0,&gt;=1.0 (from aiohttp) Using cached https://files.pythonhosted.org/packages/43/b8/057c3e5b546ff4b24263164ecda13f6962d85c9dc477fcc0bcdcb3adb658/yarl-1.2.6.tar.gz Requirement already satisfied: multidict&lt;5.0,&gt;=4.0 in c:\users\laptop\appdata\local\programs\python\python37-32\lib\site-packages (from aiohttp) (4.4.2) Requirement already satisfied: attrs&gt;=17.3.0 in c:\users\laptop\appdata\local\programs\python\python37-32\lib\site-packages (from aiohttp) (18.2.0) Requirement already satisfied: async-timeout&lt;4.0,&gt;=3.0 in c:\users\laptop\appdata\local\programs\python\python37-32\lib\site-packages (from aiohttp) (3.0.0) Requirement already satisfied: idna&gt;=2.0 in c:\users\laptop\appdata\local\programs\python\python37-32\lib\site-packages (from yarl&lt;2.0,&gt;=1.0-&gt;aiohttp) (2.7) Building wheels for collected packages: yarl Running setup.py bdist_wheel for yarl ... error Complete output from command c:\users\laptop\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Laptop\\AppData\\Local\\Temp\\pip-install-rak2eq35\\yarl\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\…
upvote count: 1
has comment: http://stackoverflow.com/comment/92219682
has title: Unable to pip install aiohttp python
tagged with: aiohttp
has comment: http://stackoverflow.com/comment/92216865
score: 1
type: Question
downvote count: 0

http://stackoverflow.com/comment/92238898
has text: If I understand correctly, does this factorise input values so that you don't have to call `dict.get` on each value individually? I assume that's the purpose of `sidx` + `np.searchsorted`. If that's the case, it's worth noting this is why it's faster than the generic `np.vectorize` with `dict.get`.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52653438

http://stackoverflow.com/comment/92199596
type: QuestionComment
has text: It's not impossible. The code need only illustrate the fundamental issue you're facing, not be something tied to you or actual issue
comment on: http://stackoverflow.com/q/52632791
score: 0
type: Comment

http://stackoverflow.com/q/52684364
has comment: http://stackoverflow.com/comment/92296645
answer count: 1
has answer: http://stackoverflow.com/a/52690604
has comment: http://stackoverflow.com/comment/92296637
has comment: http://stackoverflow.com/comment/92309590
has comment: http://stackoverflow.com/comment/92296638
tagged with: python
has comment: http://stackoverflow.com/comment/92296612
type: UnansweredQuestion
tagged with: django
type: Question
tagged with: file-read
has title: Internal server error with large file in django
tagged with: internal-server-error
has body: I have the following problem; I have a module that reads a 1.5Gb file and then processes it with it. If I run it in the Python console it works normally, however if I make the call from that file read in a django view it returns error 500 before it highlights the entire file load. How to proceed?
score: 0

http://stackoverflow.com/comment/92376491
comment on: http://stackoverflow.com/q/52725477
score: 0
has text: Thx for U everyone!!! I understand :)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52683942
has body: The problem here is whenever the button is hit the control goes to def addnumber(a) where you have written numbers = [] and then you are appending. The scope of numbers is in addnumbers definition only so every time it is like you are creating a new variable and then assigning to it. Try declaring it globally and then using it. numbers = [] def addnumber(a): global numbers numbers.append(a) print(numbers) button1 = Button(bottomFrame, text="1", command=lambda: addnumber(1)) button2 = Button(bottomFrame, text="2", command=lambda: addnumber(2))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52683891

http://stackoverflow.com/q/52733969
score: 4
has comment: http://stackoverflow.com/comment/92393705
has title: Is there a good way to dynamically create non-linear equations for scipy.optimize.root or scipy.optimize.fsolve?
has comment: http://stackoverflow.com/comment/92407835
has body: I need to solve a large system of non-linear equations (static truss system). The equations are derived from nodes (xyz) and their constraints (position, forces). For now we are using Mathematica for this task, but we would like to migrate to Python. But with Mathematica (or EES (engineering equation solver) or SymPy) it is pretty convenient. I throw a bunch of stuff in like node positions or forces on nodes and it does some magic and creates the equations by itself combining the input and solve them. If I want to use scipy.optimize.root I have to somehow get the equations. scipy.optimize.root and scipy.optimize.fsolve need the equations in the following format: def func(x): out = [x[0]*cos(x[1]) - 4], x[1]*x[0] - x[1] - 5) return out But in my case there will be up to 5000 equations that define the system. One thing that came to my mind would be to use eval() and fiddle the equations to a string somehow. In the end I would like to have an object-oriented approach where a node or a constraint knows how to transform itself to an equation. A very simple skeleton could be n = Node(5, 2, 6) n.to_equation() f = ForceConstraint(1, 2, 3) f.to_equation() and this would somehow transform to equations like x[0] - 5, x[1] - 2, x[2] - 6, x[2] ** 2 - x[1] * x[0] # and some non-linear stuff to describe the overall system. Basically there should be some magic part that looks at the matching parts of the equations and constraints. E.g. look through all info you have on Node1's x direction and merge that into equations, or search for all info you have on the forces in y direction on Node2. Is scipy the correct tool for the job at all? Does someone have a good idea how to do this?
has comment: http://stackoverflow.com/comment/92402497
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92405938
has comment: http://stackoverflow.com/comment/92426743
has comment: http://stackoverflow.com/comment/92393584
tagged with: python
tagged with: scipy
type: Question
upvote count: 4
tagged with: numpy
tagged with: sympy
has comment: http://stackoverflow.com/comment/92411207
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52776070

http://stackoverflow.com/a/52717690
has comment: http://stackoverflow.com/comment/92361109
has comment: http://stackoverflow.com/comment/92360841
has comment: http://stackoverflow.com/comment/92361184
downvote count: 0
has body: Or one-liner: print([sum([1 for x in i.get('test',[]) if x['testing']=='find']) for i in a if sum([1 for x in i.get('test',[]) if x['testing']=='find'])!=0]) Output: [1, 3] Or two-liner (more readable): l=[sum([1 for x in i.get('test',[]) if x['testing']=='find']) for i in a] print(list(filter(None,l))) Output: [1, 3]
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/92360885
answers question: http://stackoverflow.com/q/52717391

http://stackoverflow.com/comment/92198295
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52631705
type: AnswerComment
has text: I am very sorry, but this method doesn't work at next case: driver.get("https://www.youtube.com/watch?v=D1l_l_dP99Y") elem = driver.find_element(By.XPATH,'//*[@id="owner-name"]/a') # element is name of the channel "MrVinylObsessive" There is working video

http://stackoverflow.com/a/52685723
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92299103
has comment: http://stackoverflow.com/comment/92299023
type: Answer
has comment: http://stackoverflow.com/comment/92299052
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52685557
has comment: http://stackoverflow.com/comment/92299016
has body: You can do that in following two ways. Option one uses more traditional way of file handling, I have used with statement, using with statement you don't have to worry about closing the file Option two, which makes use of pathlib module and this is new in version 3.4 (I recommend using this) somefile.txt is the full file path in file system. I've also included documentation links and I highly recommend going through those. OPTION ONE p=subprocess.Popen(Some command which gives me output],stdout=subprocess.PIPE,stderr=subprocess.STDOUT) p.wait() content=p.stdout.readlines() for line in content: filedata=line.lstrip().rstrip() with open('somefile.txt', 'a') as file: file.write(filedata + '\n') Documentation for The with Statement OPTION TWO - For Python 3.4 or above import pathlib p=subprocess.Popen(Some command which gives me output],stdout=subprocess.PIPE,stderr=subprocess.STDOUT) p.wait() content=p.stdout.readlines() for line in content: filedata=line.lstrip().rstrip() pathlib.Path('somefile.txt').write_text(filedata + '\n') Documentation on Pathlib module
answers question: http://stackoverflow.com/q/52685557
has comment: http://stackoverflow.com/comment/92299088
score: 2
has comment: http://stackoverflow.com/comment/92299070

http://stackoverflow.com/comment/96972504
comment on: http://stackoverflow.com/a/55041277
score: 3
type: AnswerComment
has text: df.corr(method='pearson') computes the *correlation coefficient*, while df.corr(method=pearsonr_pval) computes the *p-value*, which are diffferent things. if you define: def pearson_corr(x,y): return pearsonr(x,y)[0], then df.corr(method='pearson') should give the same output than df.corr(method=pearson_corr) :)
type: Comment

http://stackoverflow.com/comment/125970799
comment on: http://stackoverflow.com/a/52605690
type: AnswerComment
has text: @Stephan It's a secret, like the rest of QT features and how to use them
type: Comment
score: 0

http://stackoverflow.com/a/52640661
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52639535
downvote count: 0
has body: There is no need for JSON here at all. You have already serialized the data so it is in form-encoded format; doing JSON.stringify just adds another pointless level of serialization. Remove that line and send data directly in your Ajax function.

http://stackoverflow.com/comment/92124298
score: 1
has text: Is there any specific name of that web server?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52594659

http://stackoverflow.com/comment/99195713
has text: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.
comment on: http://stackoverflow.com/a/56291662
score: 4
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52743949
type: Question
has comment: http://stackoverflow.com/comment/92412636
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92412616
favorite count: 0
accepted answer: http://stackoverflow.com/a/52744072
tagged with: pandas
tagged with: datetime
has title: How do I compare a date column with a date and add a text column?
tagged with: python
has body: I have the following dataframe: id date 1 2019-09-28 2 NaT 3 2017-09-28 I want to compare the date column to a date: 2018-09-28. Then add a column status that adds a string 'Greater' or 'Less' based on the comparison. So the output would be something like this: id date status 1 2019-09-28 Greater 2 NaT 3 2017-09-28 Less
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52744072
upvote count: 3

http://stackoverflow.com/q/52735682
type: UnansweredQuestion
tagged with: python
tagged with: node.js
tagged with: post
type: Question
has answer: http://stackoverflow.com/a/52736236
has title: Node JS and Python - POST image from Node JS to Python REST API
tagged with: image
score: 0
has body: I have a Node JS application. I want to send an image from the Node JS application to a REST API which is written in Python. The key and the inputs needed by the Python REST API are as follows My problem is that I am able to POST a simple 'Hello World' string with the code I have written and get a response. However, when I try to send an image something goes wrong and I get no response. var http = require('http'); var querystring = require('querystring'); // This is some dummy string data var postData = querystring.stringify({ msg: 'hello world' }); var fs = require('fs') , path = require('path') , certFile = path.resolve(__dirname, 'ssl/client.crt') , keyFile = path.resolve(__dirname, 'ssl/client.key') , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem') , request = require('request'); // I want to send an image from one server to another. What changes should I make to the options below for POSTing image data var options = { hostname: '127.0.0.1', port: 8888, path : '/predict', //image: fs.createReadStream('car.jpg'), //Should I give something like this?? method: 'POST', headers: { 'Content-Type': 'multipart/form-data', 'Content-Length': postData.length } }; var req = http.request(options, function (res) { console.log('STATUS:', res.statusCode); console.log('HEADERS:', JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY:', chunk); }); res.on('end', function () { console.log('No more data in response.'); }); }); req.on('error', function (e) { console.log('Problem with request:', e.message); }); req.write(postData); req.end(); Please let me know what changes I have to make to this code to post an image.I read about the use of multer package. However, the examples that I came across were using JS on both ends. Since for me, I have a Python REST API , I cannot use that. PLease help since I have been struggling with it for some time now. Edit 1: Based on @Jana's suggestion, I added the multipart within the options …
answer count: 1
tagged with: rest

http://stackoverflow.com/comment/92262841
type: QuestionComment
has text: Thanks! Just tried that but still getting the same error: "no module named 'docx'"
type: Comment
comment on: http://stackoverflow.com/q/52654136
score: 0

http://stackoverflow.com/comment/92300683
comment on: http://stackoverflow.com/a/52677839
score: 0
type: AnswerComment
has text: @Esketit, sure that will help
type: Comment

http://stackoverflow.com/q/52657610
type: AnsweredQuestion
tagged with: web-scraping
tagged with: python-requests
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/52657655
has answer: http://stackoverflow.com/a/69697375
has body: I am trying to write a program that downloads all the xkcd comics images and save them in a directory, with all the images name as title.png, title being the title of the comic. Here's the code for it: #Downloads all the xkcd comics import requests, bs4, os site = requests.get('https://www.xkcd.com') def downloadImage(site): soup = bs4.BeautifulSoup(site.text) img_tag = soup.select('div[id="comic"] img') img_title = img_tag[0].get('alt') img_file = open(img_title+'.png', 'wb') print("Downloading %s..." %img_title) img_res = requests.get("https:" + img_tag[0].get('src')) for chunk in img_res.iter_content(100000): img_file.write(chunk) print("Saved %s in " %img_title, os.getcwd()) def downloadPrevious(site): soup = bs4.BeautifulSoup(site.text) prev_tag_list = soup.select("ul[class='comicNav'] li &gt; a") prev_tag = None for each in prev_tag_list: if(each.get('rel')==['prev']): prev_tag = each break if(prev_tag.get('href') == '#'): return True prev_site = requests.get('https://xkcd.com' + prev_tag.get('href')) downloadImage(prev_site) return False, prev_site def download_XKCD_Comics(site): try: os.makedirs('E:\\XKCD Comics') except: os.chdir('E:\XKCD Comics') done = False downloadImage(site) while(not done): done, site = downloadPrevious(site) return download_XKCD_Comics(site) The output of the code: ==== RESTART: E:\Computer_Science_Programs\Python\Get all XKCD Comics.py ==== Downloading Data Pipeline... Saved Data Pipeline in E:\XKCD Comics Downloading Incoming Calls... Saved Incoming Calls in E:\XKCD Comics Downloading Stanislav Petrov Day... Saved Stanislav Petrov Day in E:\XKCD Comics Downloading Bad Opinions... Saved Bad Opinions in E:\XKCD Comics Traceback (most recent call last): File "E:\Computer_Science_Programs\Python\Get all XKCD Comics.py", line 45, in &lt;module&gt; download_XKCD_Comics(site) File "E:\Computer_Science_Programs\Python\Get all XKCD Comics.py", line 42, in download_XKCD_Comics done, site = downloadPrevious(site) File "E:\Computer_Science_Pro…
possible better answer: http://stackoverflow.com/a/69697375
answer count: 2
has title: FileNotFoundError in 'wb' file mode in Python?
downvote count: 0
has comment: http://stackoverflow.com/comment/92245830
has comment: http://stackoverflow.com/comment/92245794
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52657655
has comment: http://stackoverflow.com/comment/92246671
tagged with: python
has comment: http://stackoverflow.com/comment/92246111
score: 4

http://stackoverflow.com/comment/92152683
type: Comment
comment on: http://stackoverflow.com/q/52608789
type: QuestionComment
has text: what is your issue ?
score: 0

http://stackoverflow.com/comment/92126044
has text: The coordinates themselves appear as vectors [[49.2 40.58 52.52] [47.66 41.88 49.3 ] [45.08 39.96 47.27] [46.54 41.05 43.89] [49.83 40.08 42.25] [48.9 42.28 39.19] [49.8 46.03 38.82] [46.98 48.53 39.58] [44.7 48.67 36.51] [41.21 50.38 36.49] [39.55 46.95 35.96] [41.81 45.25 38.59] [41.09 48.03 41.16] [37.31 47.71 40.48] [37.53 43.9 40.93] [39.71 44.25 44.11] [37.01 46.62 45.5 ] [34.03 44.43 44.4 ] [35.49 41.23 46. ] [36.55 42.87 49.35] ....
score: 0
comment on: http://stackoverflow.com/q/52595201
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92137052
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52601252
has text: Possible duplicate of [Keypress detection](https://stackoverflow.com/questions/36554353/keypress-detection)
type: Comment

http://stackoverflow.com/comment/92623636
has text: However, one question of mine is: if you have not set any value to `numpy.random.seed` then it simply picks one in a random way by itself?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52747730
type: Comment

http://stackoverflow.com/q/52620922
upvote count: 1
has body: I am new to matplotlib, and I don't know what the name of the title bar arrowed in following image is. I googled and dug from matplotlib official documentation, but I didn't get a clue. What is the official name of this title bar from matplotlib, and how do I to hide it? I don't want to remove the interactivity; I just want to hide the bar, because when I interact with the plot, the title bar flex/Stretch rapidly, which is so boring and distracting
possible better answer: http://stackoverflow.com/a/52622312
favorite count: 0
has answer: http://stackoverflow.com/a/52622312
has comment: http://stackoverflow.com/comment/92187243
tagged with: python
has title: What is the official name of this title bar from matplotlib and how do I hide it?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92187432
downvote count: 0
has answer: http://stackoverflow.com/a/52627300
score: 1
accepted answer: http://stackoverflow.com/a/52627300
linked to: http://stackoverflow.com/q/32156248
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/92186109
answer count: 2

http://stackoverflow.com/q/52725125
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/52725516
accepted answer: http://stackoverflow.com/a/52725516
tagged with: function
downvote count: 1
tagged with: string
has body: In Codio, there is a challenge to take a file, search for the number of times a string appears in it, then print that number. I was able to get the result using some suggestions, but I am still unclear on a few things. The main question is, at what point is the loop searching for the substring S? The count() syntax that I see everywhere involves using the string to be searched, followed by the dot operator, and then the function with the substring we want to find as the parameter. It would look something like: P.count(S) What confuses me is that the function is using line in place of P. So does this mean the function is searching line for the substring? And if so, how does that work if line is simply the counter variable for the for loop? I just want to have a clearer understanding of how this function is working in this context to get me the correct count of times that substring S appears in file P. import sys P= sys.argv[1] S= sys.argv[2] # Your code goes here f = open(P, 'r') c = 0 for line in f.readlines(): c += line.count(S) print(c)
has title: using readlines() and count() in a "for" loop?
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: readlines
upvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/92375607
possible better answer: http://stackoverflow.com/a/52725305
score: -1
has answer: http://stackoverflow.com/a/52725305

http://stackoverflow.com/comment/92179739
score: 0
type: Comment
type: QuestionComment
has text: @MadPhysicist If ihave mentioned urgent keyword... that doen't mean I didn't try anything and am directly asking on stackoverflow
comment on: http://stackoverflow.com/q/52622069

http://stackoverflow.com/comment/92164619
type: Comment
score: 0
type: AnswerComment
has text: @hluk123 hard to test since I'm just playing it out in my head, but try this now
comment on: http://stackoverflow.com/a/52596527

http://stackoverflow.com/a/52697179
score: 0
has body: The synchronous interface into the IO loop is via tasks. Scheduling methods return a future that can be synchronously waited on if needed. The run an event loop section of the docs features a combo for synchronous shutdown in the bottom. When running inside an iPython shell, one option is to spawn a daemon background thread for the IO loop and register an atexit callback to synchronously shutdown the IO loop when the shell exits. Another option is to "borrow" shell's thread once in a while for the IO tasks (only works for short tasks, of cause) using the UI Event Loop integration point described here describing how to borrow the shell thread for the IO.
type: Answer
answers question: http://stackoverflow.com/q/52696994

postgresql
tags question: http://stackoverflow.com/q/52734114
tags question: http://stackoverflow.com/q/52636708
tags question: http://stackoverflow.com/q/52622905
tags question: http://stackoverflow.com/q/52635661
tags question: http://stackoverflow.com/q/52727681
tags question: http://stackoverflow.com/q/52745415
tags question: http://stackoverflow.com/q/52711728
tags question: http://stackoverflow.com/q/52686672
tags question: http://stackoverflow.com/q/52598344
tags question: http://stackoverflow.com/q/52622302
tags question: http://stackoverflow.com/q/52589948
tags question: http://stackoverflow.com/q/52611846
tags question: http://stackoverflow.com/q/52699990
tag name: postgresql
tags question: http://stackoverflow.com/q/52668110
type: Tag
tags question: http://stackoverflow.com/q/52646692
tags question: http://stackoverflow.com/q/52687605
tags question: http://stackoverflow.com/q/52669737
tags question: http://stackoverflow.com/q/52613220
tags question: http://stackoverflow.com/q/52671528
tags question: http://stackoverflow.com/q/52712726
tags question: http://stackoverflow.com/q/52711665
tags question: http://stackoverflow.com/q/52609828
tags question: http://stackoverflow.com/q/52593393

http://stackoverflow.com/comment/92266250
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52667008
has text: ...and? Do you get any error... something? Why are you posting here?
type: Comment

http://stackoverflow.com/comment/92272802
comment on: http://stackoverflow.com/q/52671422
type: Comment
type: QuestionComment
has text: Have you explored [to_dict()](https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.to_dict.html)?
score: 0

http://stackoverflow.com/a/52962541
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52721918
score: 1
upvote count: 1
has body: What I understand reading your problem description is that you want to find the total count of pairs whose multiplication is less than the maximum element in the range between these pairs i.e. ai*aj &lt;= max(ai,ai+1,…aj). The naive approach suggested by Thomas is easy to understand but it is still of time complexity of O(n^2)). We can optimize this to reduce the time complexity to O(n*log^2n). Lets discuss about it in details. At first, from each index- i, we can find out the range say {l, r} in which element at index- i will be greater than or equal to all the elements from l to i , as well as it is greater than all elements ranges from i + 1 to r. This can be easily calculated in O(n) time complexity using the idea of histogram data-structure. Now, lets for each index-i, we find out such range {l, r}, and if we want to traverse over minimum length out of two ranges i.e. min( i - l, r - i ) then overall we will traverse n*logn indices for overall array. While traversing over small length range, if we encounter some element say x, then we somehow have to find out how many elements exists in other range such that values are less than ai / x. This can be solved using offline processing with Fenwick Tree data-structure in O(logn) time complexity for each query. Hence, we can solve above problem with overall complexity of O(n log^2 n) time complexity.

http://stackoverflow.com/a/52600994
score: 0
has body: Try this, using dictionaries T = int(input()) for i in range(T): rules= { "rock": {"rock":0, "paper":-1,"scissors":1,"lizard":1,"Spock":-1}, "paper": {"rock":1, "paper":0,"scissors":-1,"lizard":-1,"Spock":1}, "scissors": {"rock":-1, "paper":1,"scissors":0,"lizard":1,"Spock":-1}, "lizard": {"rock":1, "paper":-1,"scissors":1,"lizard":0,"Spock":-1}, "Spock": {"rock":1, "paper":-1,"scissors":1,"lizard":-1,"Spock":0} } Sheldon, Raj = input().split(' ') Result = rules[Sheldon][Raj] if(Result == 1): print("Case #{0}: Bazinga!".format(i+1)) elif(Result == -1): print("Case #{0}: Raj cheated!".format(i+1)) else: print("Case #{0}: Again!".format(i+1))
type: Answer
answers question: http://stackoverflow.com/q/52600712

http://stackoverflow.com/q/52606733
tagged with: python
duplicate of: http://stackoverflow.com/q/6077675
has comment: http://stackoverflow.com/comment/92147494
has comment: http://stackoverflow.com/comment/92147508
upvote count: 2
downvote count: 1
type: Question
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/92147454
tagged with: python-2.7
has body: I have below dictionary in python &gt;&gt;&gt; dict = {"name":"myname", "class": "10", "score %": "60"} I have converted from dictionary to json format like below &gt;&gt;&gt; json_format = json.dumps(dict) &gt;&gt;&gt; print json_format {"score %": "60", "name": "myname", "class": "10"} I am trying to get value of key from json_format variable: &gt;&gt;&gt; print json_format["name"] I am getting below error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: string indices must be integers, not str Please help me where i am doing mistake.
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/32911336
has title: Json value print TypeError: string indices must be integers, not str
linked to: http://stackoverflow.com/q/6077675
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52606963
has comment: http://stackoverflow.com/comment/92147497

http://stackoverflow.com/comment/92176213
comment on: http://stackoverflow.com/a/52621185
type: Comment
score: 1
has text: @Geni-sama I added a for loop at the bottom for you. Now it will print the full list followed by each individual item
type: AnswerComment

http://stackoverflow.com/comment/92354612
score: 0
has text: Can you modify or replace the script (to make it take longer, wait for a keystroke, log its own PID and the command line, etc)?
comment on: http://stackoverflow.com/q/52714549
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92373147
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52723520
has text: Windows path related issues are discussed in https://stackoverflow.com/questions/2953834/windows-path-in-python

http://stackoverflow.com/comment/92221384
score: 0
type: Comment
has text: As said in another comment, i cant use `r` for some reason, because then it complains that the file doesnt exists, although at the point where this piece of code is executed, the file is generated by another part... Theres a way to prevent execution of code when initiating it but i dont know
comment on: http://stackoverflow.com/a/52644565
type: AnswerComment

http://stackoverflow.com/q/52714658
has answer: http://stackoverflow.com/a/52715078
answer count: 3
has title: How to do subplot for each month?
possible better answer: http://stackoverflow.com/a/52714974
has answer: http://stackoverflow.com/a/52714974
favorite count: 0
has answer: http://stackoverflow.com/a/52715417
has comment: http://stackoverflow.com/comment/92355640
has comment: http://stackoverflow.com/comment/92355860
tagged with: python
has comment: http://stackoverflow.com/comment/92355487
accepted answer: http://stackoverflow.com/a/52715078
type: AnsweredQuestion
score: 1
tagged with: matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/92354886
type: Question
has body: I have grouped the dataset by month and date and I have added third column for count the data in each day. Dataframe before month day 0 1 1 1 1 1 2 1 1 .. 3000 12 31 3001 12 31 3002 12 31 Dataframe now: month day count 0 1 1 300 1 1 2 500 2 1 3 350 .. 363 12 28 700 364 12 29 1300 365 12 30 1000 How to do subplot for each month , x will be the days and y will be the count import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df= pd.read_csv('/home/rand/Downloads/Flights.csv') by_month= df.groupby(['month','day']).day.agg('count').to_frame('count').reset_index() I'm beginner in data science field
downvote count: 0

http://stackoverflow.com/q/52719131
type: Question
has title: Python scraping go to next page using BeautifulSoup
has comment: http://stackoverflow.com/comment/93115402
score: 0
has answer: http://stackoverflow.com/a/52720600
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
tagged with: attributeerror
accepted answer: http://stackoverflow.com/a/52720600
has body: This is my scraping code: import requests from bs4 import BeautifulSoup as soup def get_emails(_links:list): for i in range(len(_links)): new_d = soup(requests.get(_links[i]).text, 'html.parser').find_all('a', {'class':'my_modal_open'}) if new_d: yield new_d[-1]['title'] start=20 while True: d = soup(requests.get('http://www.schulliste.eu/type/gymnasien/?bundesland=&amp;start=20').text, 'html.parser') results = [i['href'] for i in d.find_all('a')][52:-9] results = [link for link in results if link.startswith('http://')] print(list(get_emails(results))) next_page=soup.find('div', {'class': 'paging'}, 'weiter') if next_page: d=next_page.get('href') start+=20 else: break And thats the error I get: AttributeError: 'str' object has no attribute 'find_all' When you press the button "weiter" (next page) the urlending changes from "...start=20" to "start=40". It is in 20s steps because there are 20 results per site. Does anyone know the reason for the error?
linked to: http://stackoverflow.com/q/43075872
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/92431518
score: 0
comment on: http://stackoverflow.com/a/52743711
type: AnswerComment
type: Comment
has text: ajoseps: I had the subclasses hardcoded in an earlier version, but decided the code would be more re-usable if it wasn't tied to some specific class hierarchy, and the cost of making it more generic was very low—although to be honest I don't see this pattern as getting reused very often.

http://stackoverflow.com/comment/92388916
comment on: http://stackoverflow.com/q/52731801
type: Comment
type: QuestionComment
has text: @MadPhysicist the code is a minimal working example and will fail in and of itself. But, FWIW, my real code doesn't call `super()`.
score: 0

http://stackoverflow.com/q/52666845
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52670272
accepted answer: http://stackoverflow.com/a/52670272
type: Question
has comment: http://stackoverflow.com/comment/92264339
answer count: 2
has answer: http://stackoverflow.com/a/52833749
upvote count: 1
score: 0
downvote count: 1
tagged with: python
favorite count: 0
has title: Is it possible to apply a single regression technique to data that has different patterns?
has body: I want to estimate the amount of sales for multiple different products depending on the temperature, which some products have a relationship between. For one of the products, the relationship between sales and temperature looks like this when plotted out: This is just one product, but here there is a general trend that from after 10 degrees the amount of sales increases. For other products the relationship might be more linear, and others might have a polynomial kind of relationship, while other products might not have a relationship at all. An example of another product, which has no correlation between sales and temperature could be this product: First of all i wanted to predict something just from one product, so I used the product from the first plot to try and model something. What I ended up doing was splitting the data so I had a dataframe with all the values from -5 degrees to 10 degrees and performed linear regression, and similar i splitted from 10 degrees to 30 degrees to perform linear regression, like so: The one problem here is that I'm doing all sorts of things to fit my data to only ONE product. I have a dataset of 1000 products where I'd want to be able to estimate sales for SOME of the products based of a temperature. I want to somehow loop through all of my datasets, figure out which ones has some kind of relationship between sales and temperature and then automatically apply the best regression model for that particular product to estimate amount of sales for that product given some temperature, X. I have looked at a bunch of different regression tutorials for neural networks, but I simply have no idea how to start or what to search for, or if what I'm trying to do is even possible?
possible better answer: http://stackoverflow.com/a/52833749
tagged with: regression
tagged with: machine-learning

http://stackoverflow.com/a/52737541
has body: another way around using with df.iteritems : &gt;&gt;&gt; df = pd.DataFrame({'a': [0, 0, 2], 'b': [ 0, 2, 1]}) &gt;&gt;&gt; df a b 0 0 0 1 0 2 2 2 1 &gt;&gt;&gt; for key, val in df.iteritems(): ... val[val == 0] = 3 ... &gt;&gt;&gt; df a b 0 3 3 1 3 2 2 2 1
score: 0
has comment: http://stackoverflow.com/comment/92400037
answers question: http://stackoverflow.com/q/52737336
has comment: http://stackoverflow.com/comment/92399829
type: Answer
has comment: http://stackoverflow.com/comment/92399772
has comment: http://stackoverflow.com/comment/92400275

http://stackoverflow.com/a/52610981
type: Answer
has comment: http://stackoverflow.com/comment/92177489
has body: pd.DataFrame.rename Avoid explicit for loops with Pandas. You can use pd.DataFrame.rename with a series input: df_input = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) df_tags = pd.DataFrame({'in_col': ['A', 'C', 'D'], 'out_col': ['X', 'Y', 'Z']}) df_input = df_input.rename(columns=df_tags.set_index('in_col')['out_col']) print(df_input) X B Y 0 1 4 7 1 2 5 8 2 3 6 9 The rename method is versatile and lenient. As described in the docs: Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error.
answers question: http://stackoverflow.com/q/52610672
has comment: http://stackoverflow.com/comment/92178856
accepted answer of: http://stackoverflow.com/q/52610672
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/52684987
tagged with: python-2.7
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/92308733
has comment: http://stackoverflow.com/comment/92308510
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52730426
has answer: http://stackoverflow.com/a/52864930
tagged with: python
has comment: http://stackoverflow.com/comment/92307762
possible better answer: http://stackoverflow.com/a/52730426
tagged with: amazon-s3
upvote count: 3
has answer: http://stackoverflow.com/a/52692772
has answer: http://stackoverflow.com/a/52692814
has body: I am attempting to run the example code for Amazon Sagemaker on a local GPU. I have copied the code from the Jupyter notebook to the following Python script: import boto3 import subprocess import sagemaker from sagemaker.mxnet import MXNet from mxnet import gluon from sagemaker import get_execution_role import os sagemaker_session = sagemaker.Session() instance_type = 'local' if subprocess.call('nvidia-smi') == 0: # Set type to GPU if one is present instance_type = 'local_gpu' # role = get_execution_role() gluon.data.vision.MNIST('./data/train', train=True) gluon.data.vision.MNIST('./data/test', train=False) # successfully connects and uploads data inputs = sagemaker_session.upload_data(path='data', key_prefix='data/mnist') hyperparameters = { 'batch_size': 100, 'epochs': 20, 'learning_rate': 0.1, 'momentum': 0.9, 'log_interval': 100 } m = MXNet("mnist.py", role=role, train_instance_count=1, train_instance_type=instance_type, framework_version="1.1.0", hyperparameters=hyperparameters) # fails in Docker container m.fit(inputs) predictor = m.deploy(initial_instance_count=1, instance_type=instance_type) m.delete_endpoint() where the referenced mnist.py file is exactly as specified on Github. The script fails on m.fit in Docker container with the following error: algo-1-1DUU4_1 | Downloading s3://&lt;S3-BUCKET&gt;/sagemaker-mxnet-2018-10-07-00-47-10-435/source/sourcedir.tar.gz to /tmp/script.tar.gz algo-1-1DUU4_1 | 2018-10-07 00:47:29,219 ERROR - container_support.training - uncaught exception during training: Unable to locate credentials algo-1-1DUU4_1 | Traceback (most recent call last): algo-1-1DUU4_1 | File "/usr/local/lib/python2.7/dist-packages/container_support/training.py", line 36, in start algo-1-1DUU4_1 | fw.train() algo-1-1DUU4_1 | File "/usr/local/lib/python2.7/dist-packages/mxnet_container/train.py", line 169, in train algo-1-1DUU4_1 | mxnet_env.download_user_module() algo-1-1DUU4_1 | File "/usr/local/lib/python2.7/dist-packages/container_support/environme…
has title: AWS NoCredentials in training
answer count: 4
accepted answer: http://stackoverflow.com/a/52864930
downvote count: 0
tagged with: amazon-web-services
tagged with: amazon-sagemaker

http://stackoverflow.com/a/52644034
has comment: http://stackoverflow.com/comment/92222054
has body: That is not how you should read the csv file. Take a look at the csv module documentation. One example : import csv with open('C:/Marine/lookup/distinct_lookup_scales.csv', 'r') as csvfile: csvreader = csv.reader(csvfile) csvreader.next() #skip header for row in csvreader: minzoom = int(row[0]) maxzoom = int(row[1]) print('minzoom : {}'.format(minzoom)) print('maxzoom : {}'.format(maxzoom)) You can also use a DictReader which will use your header line to yield dictionaries. import csv with open('C:/Marine/lookup/distinct_lookup_scales.csv', 'r') as csvfile: csvreader = csv.DictReader(csvfile) for row in csvreader: minzoom = int(row['minzoom']) maxzoom = int(row['maxzoom']) print('minzoom : {}'.format(minzoom)) print('maxzoom : {}'.format(maxzoom))
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52643870
answers question: http://stackoverflow.com/q/52643870
type: Answer
has comment: http://stackoverflow.com/comment/92222149

http://stackoverflow.com/comment/92160862
comment on: http://stackoverflow.com/q/52612761
score: 0
type: Comment
type: QuestionComment
has text: So filter_horizontal can be used in group admin, a model with a manytomany field, not with person.

http://stackoverflow.com/q/52627863
has comment: http://stackoverflow.com/comment/92190572
type: AnsweredQuestion
tagged with: screen-scraping
possible better answer: http://stackoverflow.com/a/52628209
has answer: http://stackoverflow.com/a/52627958
type: Question
accepted answer: http://stackoverflow.com/a/52627958
has answer: http://stackoverflow.com/a/52628209
has answer: http://stackoverflow.com/a/52628451
has comment: http://stackoverflow.com/comment/92189597
has title: Import Data from scraping into CSV
score: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/92189478
has comment: http://stackoverflow.com/comment/92190393
tagged with: python
has body: I'm using pycharm and Python 3.7. I would like to write data in a csv, but my code writes in the File just the first line of my data... someone knows why? This is my code: from pytrends.request import TrendReq import csv pytrend = TrendReq() pytrend.build_payload(kw_list=['auto model A', 'auto model C']) # Interest Over Time interest_over_time_df = pytrend.interest_over_time() print(interest_over_time_df.head(100)) writer=csv.writer(open("C:\\Users\\ Desktop\\Data\\c.csv", 'w', encoding='utf-8')) writer.writerow(interest_over_time_df)

http://stackoverflow.com/comment/92370635
score: 0
type: Comment
has text: Sadly ironic that this is a duplicate
type: QuestionComment
comment on: http://stackoverflow.com/q/52722001

http://stackoverflow.com/comment/92287186
type: QuestionComment
type: Comment
has text: Since 3.4, `pip` is bundled with the standard distribution, so `python3.7 -m pip` will work just fine.
comment on: http://stackoverflow.com/q/52677089
score: 0

http://stackoverflow.com/comment/92269058
comment on: http://stackoverflow.com/a/52668722
score: 0
type: AnswerComment
type: Comment
has text: @Idle_92, You could pre-create your dictionary with empty lists like `d = {k: [] for k in list_of_keys}` and it would work just fine. But the whole point of `defaultdict` is this initialization is not necessary.

http://stackoverflow.com/q/52601623
upvote count: 2
has comment: http://stackoverflow.com/comment/92137476
has answer: http://stackoverflow.com/a/52601671
tagged with: python
has comment: http://stackoverflow.com/comment/92137519
type: AnsweredQuestion
score: 2
has title: Estimating in Python
has body: I am trying to write a python function which will give me back the first value of a number k which will function 2 &gt;= function 1 function 1(p) =&gt; 1 + 1/1! + 1/2! + 1/p! function 2(k) =&gt; (1 + 1/k)^k So I input use 2 for example in function 1. It would take estimate e at 2.5 but it would take k being 6 for it to get close which is 2.522. I want to return the 6. I get this far but I am not sure where to go from there. for x in range(p): factorial(x): if x == 0: return 0 else: return x * factorial(x-1) result = 1 + 1/factorial(p)
type: Question
has comment: http://stackoverflow.com/comment/92137532
accepted answer: http://stackoverflow.com/a/52601671
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92137498
tagged with: tail-recursion
has comment: http://stackoverflow.com/comment/92137534
favorite count: 0

http://stackoverflow.com/q/52619754
has comment: http://stackoverflow.com/comment/107580926
tagged with: imdb
tagged with: python
has title: ResultSet object has no attribute 'text'. You're probably treating a list of items like a single item.
type: AnsweredQuestion
has body: from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time from bs4 import BeautifulSoup #browser = webdriver.Firefox()#Chrome('./chromedriver.exe') YOUTUBER_HOME_PAGE_URL = "https://www.imdb.com/title/tt6452574/reviews?ref_=tt_ov_rt" PATIENCE_TIME = 60 LOAD_MORE_BUTTON_XPATH = '//*[@id="load-more-trigger"]' driver = webdriver.Chrome(r"C:\Users\Panu\Dropbox\Dr.Gokhan Sir\chromedriver.exe") driver.get(YOUTUBER_HOME_PAGE_URL) while True: try: loadMoreButton = driver.find_element_by_xpath('//*[@id="load-more-trigger"]') time.sleep(2) loadMoreButton.click() time.sleep(5) except Exception as e: print e break print "Complete" time.sleep(10) #Selenium hands the page source to Beautiful Soup soup_level1=BeautifulSoup(driver.page_source, 'html.parser') movie_containers = soup_level1.find_all('div', class_ = 'review-container') print(type(movie_containers)) print(len(movie_containers)) sample_data = movie_containers #div = sample_data.find_all('div', class_ = 'text show-more__control') #sample_data.text for user review and titile reviews = [] user_titles = [] for div in sample_data: title = div.div.a.text user_titles.append(title) #print(div.text) review = div.find_all('div', class_ = 'text show-more__control').text reviews.append(review) i got error while runing above code. AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
tagged with: web-scraping
has answer: http://stackoverflow.com/a/52619812
type: Question
linked to: http://stackoverflow.com/q/24108507
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/52619812
tagged with: beautifulsoup

http://stackoverflow.com/comment/92377040
comment on: http://stackoverflow.com/q/52725870
score: 0
type: Comment
type: QuestionComment
has text: To install it run `pip install nltk`

http://stackoverflow.com/q/52673842
downvote count: 1
type: Question
score: 1
tagged with: webdriver
tagged with: css-selectors
has title: How to to input a date within the Gas Day input box through Selenium and Python
answer count: 1
has comment: http://stackoverflow.com/comment/92296367
favorite count: 0
has body: I am using Python and Selenium to read this URL: http://ips.alliance-pipeline.com/Ips/MainPage.aspx?siteId=4 I use selenium to open it up, click on the plus sign (left hand side) and click "Daily Throughput". A page opens up with "Gas Day" input box, in which I want to input a date. If these steps are done manually in regular chrome browser, it works fine, I can input the date and click "Retrieve" and get the data table. But for some reason selenium makes the input box read-only. I have tried removing the "read-only" attribute (see commented out lines), in which case the attribute seems to get removed, but the date is still not entered in the box and data is not retrieved. Why does selenium make this element read-only and how can I prevent this from happening? Here is the code: url = 'http://ips.alliance-pipeline.com/Ips/MainPage.aspx?siteId=4' browser = webdriver.Chrome() browser.get(url) browser.find_element_by_id('treeviewn0').click() # click on "Capacity" heading browser.find_element_by_id('treeviewt1').click() # click on "Daily Throughput" heading time.sleep(2) # browser.execute_script('document.getElementsByClassName("igte_EditInContainer")[0].removeAttribute("readonly")') d = datetime.date.today() - datetime.timedelta(days=5) d_str = d.strftime('%m/%d/%Y') date_box = browser.find_element_by_xpath('//*[@id="MainContent_dtJobSchedForGrid"]/tbody/tr/td[1]/input') # print(date_box.get_attribute('readonly')) date_box.send_keys(d_str + '\n') time.sleep(5) browser.find_element_by_id('MainContent_btnRetrieveJobSchedForGrid').click() # click the Retrieve button time.sleep(5)
has comment: http://stackoverflow.com/comment/92277492
tagged with: python
has comment: http://stackoverflow.com/comment/92277403
has answer: http://stackoverflow.com/a/52674091
tagged with: webdriverwait
upvote count: 2
type: UnansweredQuestion
tagged with: selenium

http://stackoverflow.com/comment/92194804
type: QuestionComment
has text: @vealkind the line "linreg.fit(X_train,y_train)"
comment on: http://stackoverflow.com/q/52629035
score: 0
type: Comment

http://stackoverflow.com/comment/92207069
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52636904
has text: JSON5 is a superset which means the string generated from JSON5 may be incompatible with JSON. Anyway, it depends on your situation. If you just need to parse, I think it is OK.
score: 0

http://stackoverflow.com/q/52672130
has answer: http://stackoverflow.com/a/52672362
type: Question
has comment: http://stackoverflow.com/comment/92274279
has title: Dictionary call into a variable during for loop
linked to: http://stackoverflow.com/q/209513
has comment: http://stackoverflow.com/comment/92274073
has answer: http://stackoverflow.com/a/52672383
accepted answer: http://stackoverflow.com/a/52672383
answer count: 3
has answer: http://stackoverflow.com/a/52672304
downvote count: 0
possible better answer: http://stackoverflow.com/a/52672362
has comment: http://stackoverflow.com/comment/92274564
favorite count: 0
has comment: http://stackoverflow.com/comment/92274158
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92274380
upvote count: 2
has comment: http://stackoverflow.com/comment/92274280
has body: I need to create a function that takes a 13 digit sequence and uses the last number as a check using modulo 10. ie BAF189D234EA2 entry check = 2. Using the values of A-F (see weight dict below) instead of ord(char). So as my loop iterates I need char to pull the corresponding weight dict if it is a string value. I simply cannot figure out how to make it call from that dictionary based on the value of char. Thanks in advance for any help. weight={ 'A' : '10', 'B' : '11', 'C' : '12', 'D' : '13', 'E' : '14', 'F' : '15', } def validater(value): global userEntry valSum = 0 i = 0 for char in userEntry: if i == 12: break try: if char &gt;=0 and char &lt;= 9: valSum += char * i i +=1 except TypeError: valSum += weight[char] * i i += 1 Error: Traceback (most recent call last): line 93, in &lt;module&gt; if validater(userEntry) ==True: line 74, in validater valSum += weight[char] * i TypeError: unsupported operand type(s) for +=: 'int' and 'str' Edit: Thanks, I changed the dictionary by dropping the quotes around my ints. Now I get a Key Error 1
tagged with: python
has comment: http://stackoverflow.com/comment/92274199
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52713097
has answer: http://stackoverflow.com/a/52716097
type: AnsweredQuestion
score: 1
has title: Stop Scrapy Spider Running in a Cron Job
tagged with: web-crawler
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/52716097
tagged with: cron
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 1
tagged with: python
has body: I have a Scrapy Spider which I have scheduled as a Cron Job. I am using the -o option in order to write my data to a csv file. scrapy crawl my_spider -o my_csv.csv I am utilizing Crawlera, but I am out of requests. I seek to shutdown my spider and have the output written to csv. Scrapy has not yet written the output to csv and I am worried that if I kill the process, the data will be lost. Is there a way to gracefully shutdown a spider, running as a cron job, without having to wait for the crawl to 'finish'?

http://stackoverflow.com/comment/92420742
type: Comment
has text: I do not have an option to change the delimiter. I'm presented with the file. And I'll try your solution.
comment on: http://stackoverflow.com/a/52733187
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92170411
type: QuestionComment
has text: Yes, this just sample code, and runs without syntax errors...
comment on: http://stackoverflow.com/q/52609069
score: 0
type: Comment

http://stackoverflow.com/q/52635232
type: UnansweredQuestion
tagged with: openid-connect
tagged with: python
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/56804856
has body: I have successfully integrated a Django test application with our Okta IAM service, using the mozilla_django_oidc package. Now I can log in using Okta, which is just cool. But now I want to log out of the session again - which I cannot do it seems. mozilla_django_oidc provides three URLs basically: name=oidc_authentication_callback name=oidc_authentication_init (the one used for the "Login" link) name=oidc_logout Naively I just added that code to my application, and expected a working logout: {% if user.is_authenticated %} {{ user.email }} - Logout {% else %} # etc. {% end %} The problem is: The logout endpoint only takes POST requests. Now, how can I log out of the session?
downvote count: 0
answer count: 1
has title: Django and mozilla_django_oidc - how to log out of session?
favorite count: 0
tagged with: openid

http://stackoverflow.com/q/52682634
possible better answer: http://stackoverflow.com/a/52683149
favorite count: 0
has comment: http://stackoverflow.com/comment/92294866
has comment: http://stackoverflow.com/comment/92293633
has comment: http://stackoverflow.com/comment/92293894
tagged with: python
accepted answer: http://stackoverflow.com/a/52682732
has answer: http://stackoverflow.com/a/52683149
linked to: http://stackoverflow.com/q/52225721
has title: TypeError: can only concatenate str (not "int") to str SUM
has comment: http://stackoverflow.com/comment/92293416
has comment: http://stackoverflow.com/comment/92293398
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52682732
has comment: http://stackoverflow.com/comment/92293424
downvote count: 0
score: 1
has body: I am trying to make a program that will sum the cube of a number up to an upper boundary. The mathematical formula is (n*(n+1)/2)^2 My code in Python: def cube_numbers(): upper_boundary = 0 cube_sum = 0 upper_boundary = input("Please enter the upper boundary:") cube_sum = ((upper_boundary * (upper_boundary + 1) / 2)**2) print("The sum of the cube of numbers up to" &amp; upper_boundary &amp; "is" &amp; cube_sum) #main cube_numbers() But I get the following error: Traceback (most recent call last): File "C:/Users/barki/Desktop/sum of cubes.py", line 10, in &lt;module&gt; cube_numbers() File "C:/Users/barki/Desktop/sum of cubes.py", line 5, in cube_numbers cube_sum = ((upper_boundary * (upper_boundary + 1) / 2)**2) TypeError: can only concatenate str (not "int") to str
has comment: http://stackoverflow.com/comment/92293666
type: Question
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/92220079
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52635539
score: 0
has text: Hello again Dan, i didn't know this was python 2, i'll try it out in python 2 and will see if it works, if it does, i'll just save it as a txt file and continue the modeling phase with python 3, so i don't have to bother you again. I'll let you know as soon as i try it! Thanks again :)

http://stackoverflow.com/comment/92228462
has text: :<25 justify text left so its nice formatted as your requirements, remove it and you will se the difference
score: 1
comment on: http://stackoverflow.com/a/52636757
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92154777
has text: In this example - [Day 1: $10; Day 2: $12; Day 3: $10]. The $10 on day 3 will not get saved
type: Comment
comment on: http://stackoverflow.com/a/52606270
score: 0
type: AnswerComment

http://stackoverflow.com/a/52632111
has comment: http://stackoverflow.com/comment/92473873
has comment: http://stackoverflow.com/comment/93015346
has comment: http://stackoverflow.com/comment/92557833
has comment: http://stackoverflow.com/comment/92506461
has comment: http://stackoverflow.com/comment/92572903
has body: You could use Jep. I actually never tested the pickle module in Jep, but for your case it would be something like this: try(Jep jep = new Jep()) { // Load model jep.eval("import pickle"); jep.eval("with open('Randomforestclassifier.pkl', 'rb'): as f: clf = pickle.load(f)"); Object randomForest = jep.getValue("clf"); ... // Then in another context you can pass your model to your function jep.eval("import predictionModule"); jep.set("arg", randomForest); jep.eval("result = predictionModule.use(arg)"); Object result = jep.getValue("result"); } Assuming you have a module named predictionModule.py which should be something like this: import pickle def use(model_as_bytes): model = pickle.loads(model_as_bytes) print(model) # do other stuff ... return prediction Hope this helps.
score: 0
answers question: http://stackoverflow.com/q/52592107
has comment: http://stackoverflow.com/comment/92431144
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92760366
has comment: http://stackoverflow.com/comment/92428972
has comment: http://stackoverflow.com/comment/92431458
has comment: http://stackoverflow.com/comment/92474240
accepted answer of: http://stackoverflow.com/q/52592107
type: Answer

http://stackoverflow.com/a/52668052
answers question: http://stackoverflow.com/q/52667926
has body: You have a few options if this is just to print the contents at the once your code is completed. lista = [1, 2, 3] print(' '.join([str(i) for i in lista])) print(*lista) for i in lista: print(i, end = ' ') 1 2 3
score: 0
type: Answer

http://stackoverflow.com/q/52744116
type: Question
has title: How to calculate with previous row value of a column if it can be declared only after it should be used in pandas dataframe?
has answer: http://stackoverflow.com/a/52747194
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has body: The following is the dataframe I have: import datetime import pandas as pd import numpy as np todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D') data = pd.DataFrame(index=index) data['Open'] = np.random.randint(20,40, size=len(data)) data['High'] = np.random.randint(40,50, size=len(data)) data['Low'] = np.random.randint(10,20, size=len(data)) data['Close'] = np.random.randint(10,20, size=len(data)) The calculations I would like to perform are the following: capital = 30000 data['Shares'] = (capital * 0.05 / data['Close'].shift(1) - data['Low'].shift(1)).round(0) data['Open_price'] = data['Open'] + 0.5 * (data['High'] - data['Open']) data['Floating_P/L'] = data['Shares'] * data['Close'] data['Close_price'] = data['Close'] - 0.5 * (data['Close'] - data['Low']) data['Closed_P/L'] = data['Shares'].shift(1) * data['Close_price'] data['Closed_Balance'] = capital + data['Closed_P/L'].cumsum() data['Equity'] = data['Closed_Balance'] + data['Floating_P/L'] capital = data['Equity'].shift(1) As you can see Equity is calculated from today's Shares number which is calculated from yesterday's Equity. I want to set capital to be the initial value of Equity at the first index and calculate Shares based on this number at the first index. From the second index, Shares should be calculated from the Equity shifted one row up. How can I do this?
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1

http://stackoverflow.com/comment/92391855
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52733545
has text: Welcome to TeX.SX! Python questions are off-topic here, you might have more luck at StackOverflow.
score: 0

http://stackoverflow.com/comment/92268652
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52669097
has text: @HT121 That's a new addition to NumPy library. Can you update your NumPy?
type: Comment

http://stackoverflow.com/comment/136336207
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52739504
has text: `ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (3,) + inhomogeneous part.` when running your code with pandas 2.0.3.
score: 0

http://stackoverflow.com/q/52656487
score: -2
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52657036
favorite count: 0
tagged with: hex
tagged with: binary
type: UnansweredQuestion
has title: I want to convert 1fd93d1cf1f13d0d to 00011111 11011001 00111101 00011100 11110001 11110001 00111101 00001101
downvote count: 3
upvote count: 1
tagged with: python
has body: I used the following function: bin(int('1fd93d1cf1f13d0d', 16)) but I keep getting 0b1111111011001001111010001110011110001111100010011110100001101 as output. When I use .zfill(64) it becomes 00b1111111011001001111010001110011110001111100010011110100001101 Can someone please tell me where i'm doing wrong. Thanks
has answer: http://stackoverflow.com/a/52657234

http://stackoverflow.com/comment/92287409
score: 1
has text: This works. Thanks for taking the time to explain your answer and for the demo.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52673459

http://stackoverflow.com/a/52592842
has comment: http://stackoverflow.com/comment/92281474
has body: Server A (Server receiving file from Server B) models.py class TestModel(models.Model): # Other fields you are interested in saving file_data = models.FileField() serializers.py class TestModelSerializer(serializers.ModelSerializer): class Meta: model = TestModel fields = '__all__' view.py class TestModelViewSet(viewsets.ModelViewSet): queryset = TestModel.objects.all() parser_classes = (MultiPartParser, FormParser,) serializer_class = TestModelSerializer urls.py router = routers.DefaultRouter() router.register(r'test', views.TestModelViewSet) urlpatters = [ url(r'^api/', include(router.urls)) ] Server B (192.168.5.5) (Send file to Server A) file_generator.py with open('file.txt', 'rb') as f: r = requests.post('http://192.168.5.5/api/test', files={'file.txt': f})
answers question: http://stackoverflow.com/q/52592298
accepted answer of: http://stackoverflow.com/q/52592298
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/92238297
type: Comment
has text: @MartijnPieters Well, despite your assertions, the interpreter disagrees with you. I'm going to go with the interpreter.
comment on: http://stackoverflow.com/a/52651292
type: AnswerComment
score: 0

http://stackoverflow.com/q/52622094
has title: How to solve the Error related to Python Libraries on no module?
accepted answer: http://stackoverflow.com/a/52622536
tagged with: python-deepdiff
type: Question
has answer: http://stackoverflow.com/a/52622536
score: -1
tagged with: batch-file
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92177932
has comment: http://stackoverflow.com/comment/92179947
has comment: http://stackoverflow.com/comment/92178220
has comment: http://stackoverflow.com/comment/92178135
favorite count: 0
has comment: http://stackoverflow.com/comment/92178343
has body: I am using Python lib deepdiff. I Installed using cmd -> python -m pip install --trusted-host https://pypi.python.org deepdiff as I got an error with SSL I used above to cmd. When I worked in pycharm using python version35 and executed my file. C:\Python35\python.exe C:/Users/mytry.py {'values_changed': {"r"}} It works in Pycharm Tools But when I try to run the file mytry.py in cmd prompt I get => from deepdiff import DeepDiff ImportError: No module named deepdiff I m using 3.5.4 in local as well I don't know how to solve this please help!!
tagged with: python
has comment: http://stackoverflow.com/comment/92177811
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/92309779
comment on: http://stackoverflow.com/q/52691083
score: 0
type: QuestionComment
has text: I have a list of dictionaries, with one of the values of each dictionary being a list of tuples. I think it's too many layers for me to make sense of as a beginner. @artomason I added the list of dictionaries I made as a test to work with things. Is that what you wanted?
type: Comment

http://stackoverflow.com/a/52670634
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52670383
has body: You can do this using list-comprehensions and only built-ins, some monstrosity like: &gt;&gt;&gt; result = [ ... random.randint(a,b) ... for args in (((0,50) for _ in range(5)), ((0, 12) for _ in range(2))) ... for a, b in args ... ] &gt;&gt;&gt; result [33, 38, 19, 9, 47, 0, 8] Perhaps, if you want to use itertools, you can do something like: &gt;&gt;&gt; from itertools import chain, repeat, starmap &gt;&gt;&gt; list(starmap(random.randint, chain(repeat((0,50),5), repeat((0,12),2)))) [16, 47, 40, 21, 15, 12, 4] Both of these approaches are hardly readable and simple. Instead, I would personally go with two for-loops, the naive approach. It would be efficient, simple, and readable. Other than showboating, I see no advantage to the above approaches in production code.

http://stackoverflow.com/a/52681223
has body: You can use np.repeat(..) [numpy-doc] for this: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.repeat(a, 2, axis=1) array([[1, 1, 2, 2, 3, 3], [4, 4, 5, 5, 6, 6], [7, 7, 8, 8, 9, 9]]) We thus repeat, for the second axis (axis=1) the elements two times. We can also use list-comprehension, but given that the data has the same time, using numpy is faster, and more declarative: times2 = [[xi for x in row for xi in [x, x]] for row in a] This the produces: &gt;&gt;&gt; [[xi for x in row for xi in [x, x]] for row in a] [[1, 1, 2, 2, 3, 3], [4, 4, 5, 5, 6, 6], [7, 7, 8, 8, 9, 9]]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52681191
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/52681191
score: 6
has comment: http://stackoverflow.com/comment/92291507
type: AcceptedAnswer

http://stackoverflow.com/comment/92167307
comment on: http://stackoverflow.com/a/52600577
score: 0
type: Comment
has text: I am sorry I have little idea about windows OS as I'm a linux developer. I've tried to figure it out and found there are some problems specified on Windows. Basically the problem is how to use `readline` module on Windows correctly as there is a built in module named GNU readline on linux. I believe if this problem can be solved, the correct inputrc file can let `ipython` work even without qtconsole. And btw, `ipython` is just a backend, `notebook`'s python backend is exactly `ipython`.
type: AnswerComment

http://stackoverflow.com/a/52630953
accepted answer of: http://stackoverflow.com/q/52629375
answers question: http://stackoverflow.com/q/52629375
has body: One option is to use the function cityblock from scipy.spatial.distance: from scipy.spatial import distance df.set_index('category', inplace = True) &gt;&gt; df.apply(lambda x: distance.cityblock(x, df.loc['apple',:]), axis=1 ).drop('apple', axis=1).nsmallest(4).index.values.tolist() ['strawberry', 'berry', 'kiwi', 'orange'] Basically, you get the distance from each row to the one selected. Then you drop the row containing the selected label and pick the index of the smallest distances.
type: AcceptedAnswer
type: Answer
score: 0

http://stackoverflow.com/comment/92404813
type: QuestionComment
has text: I use it to write to the file, in another function i used it like that "fobj_out.write(str(i) + ": " + line)"
comment on: http://stackoverflow.com/q/52740014
score: 0
type: Comment

http://stackoverflow.com/comment/92201814
type: Comment
comment on: http://stackoverflow.com/a/52621441
has text: Will this work if my function run with a infinite loop fo example? I mean: Time_start=time.time() || Infinite Loop // I need to break this loop after 10 seconds || Time_Stop=time.time()
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92237791
score: 0
type: Comment
has text: Why does the database send SIGTERM? To itself or to your Python program?
type: QuestionComment
comment on: http://stackoverflow.com/q/52642700

http://stackoverflow.com/a/54563085
type: Answer
has body: In my case, the image was incorrectly named. Check if the image exists and try import numpy as np import cv2 img = cv2.imread('image.png', 0) cv2.imshow('image', img)
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52676020
upvote count: 1

http://stackoverflow.com/comment/92153806
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52595858
has text: @user123: sorry, no, your job.

http://stackoverflow.com/q/52653976
has title: How to access global variable from first python file into second when second file is imported in first file
tagged with: python
has body: I have 2 python scripts. I am trying to access value of global variable from one.py into two.py. Here is my code. one.py import two myvar = False def fun(): global myvar myvar = True two.use_me() two.py import one print "from two: ", one.myvar def use_me(): print "This is used in one.py" I am getting this error: $ python two.py from two: Traceback (most recent call last): File "two.py", line 1, in &lt;module&gt; import one File "one.py", line 1, in &lt;module&gt; import two File "two.py", line 2, in &lt;module&gt; print "from two: ", one.myvar AttributeError: 'module' object has no attribute 'myvar' Not sure what I am missing here. Can someone please help?
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52654050
duplicate of: http://stackoverflow.com/q/744373
linked to: http://stackoverflow.com/q/744373
score: 0
has answer: http://stackoverflow.com/a/52654050
answer count: 1
has comment: http://stackoverflow.com/comment/92239750

http://stackoverflow.com/q/52657097
has answer: http://stackoverflow.com/a/52658030
type: Question
has answer: http://stackoverflow.com/a/52657425
has body: Python scripting : I want to multiply an entire matrix except for one row/column with a scalar. The row/column number is a variable. For example, [[2 2 2 2 2] [2 2 2 2 2]] num = 2 scalar = 3 I want the result to look like this [[6 6 2 6 6] [6 6 2 6 6]] I don't want any loops. I can use either numpy or pandas. What is the best way to achieve this?
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52657425
tagged with: pandas
tagged with: arrays
downvote count: 0
has title: multiply entire matrix except one row/column in python
has answer: http://stackoverflow.com/a/52657205
has answer: http://stackoverflow.com/a/52657170
favorite count: 0
answer count: 5
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/52659489
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/52657170

http://stackoverflow.com/comment/92301808
type: QuestionComment
comment on: http://stackoverflow.com/q/52687199
score: 0
has text: posting it as an answer, just mark it accepted so the issue is set as resolved :)
type: Comment

http://stackoverflow.com/comment/92295270
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52683554
has text: CPython _can't_ use all cores because of the Global Interpreter Lock (GIL) that was built in. This is why things like `numpy` exist (among other reasons).

http://stackoverflow.com/q/52589682
accepted answer: http://stackoverflow.com/a/52592177
type: Question
upvote count: 4
downvote count: 0
score: 4
has title: What is the difference between conda 'base' and 'root' enviroments?
tagged with: conda
answer count: 1
has answer: http://stackoverflow.com/a/52592177
has comment: http://stackoverflow.com/comment/92118940
favorite count: 0
tagged with: jupyter-notebook
has body: I have recently been pulling my hair out trying to organize my conda environments. I ended up reinstalling miniconda and I'm in a good spot. When I run conda env list I get: # conda environments: # base * /Users/rheft/miniconda3 sonny36 /Users/rheft/miniconda3/envs/sonny36 I would expect "root" to be included here. Furthermore when I look at my conda environments from inside jupyter notebooks there are 3 environments listed. root -- /Users/rheft/miniconda3 miniconda3 -- /Users/rheft/miniconda3 sonny36 -- /Users/rheft/miniconda3/envs/sonny36 Why doesn't root show when I run conda env list? Although everything works correctly, I would like to remove the duplicated environment if possible.
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/92308141
has text: Glad you solved it! No problem, I've been there too. Someone has already answered correctly, give him/her the credit so future readers will know how to solve it. Cheers!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52690093
score: 2

http://stackoverflow.com/comment/92229599
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52647785
has text: @Yuca now my assertion passed. I will post the answer in a minute ! Thanks a lot my deer StackOverflow friends

http://stackoverflow.com/comment/92428467
comment on: http://stackoverflow.com/q/52739471
score: 1
has text: If you can answer my questions, then we can tell you how to access S3.
type: QuestionComment
type: Comment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/52689682
tags question: http://stackoverflow.com/q/52742125
tags question: http://stackoverflow.com/q/52676843
tags question: http://stackoverflow.com/q/52705496
tags question: http://stackoverflow.com/q/52610492
tags question: http://stackoverflow.com/q/52726459
tags question: http://stackoverflow.com/q/52707190
tags question: http://stackoverflow.com/q/52667378
tags question: http://stackoverflow.com/q/52691611
tags question: http://stackoverflow.com/q/52694261
type: Tag
tags question: http://stackoverflow.com/q/52725511
tags question: http://stackoverflow.com/q/52742370
tags question: http://stackoverflow.com/q/52677254
tags question: http://stackoverflow.com/q/52661392
tags question: http://stackoverflow.com/q/52629377
tags question: http://stackoverflow.com/q/52746410
tags question: http://stackoverflow.com/q/52735012
tags question: http://stackoverflow.com/q/52646089

http://stackoverflow.com/comment/92668022
type: Comment
has text: @nicoco thats great! I hope a bug report in keras can help in figuring out how to approach debugging this problem at the very least! You can also try tensorflow bug report!
type: QuestionComment
comment on: http://stackoverflow.com/q/52724022
score: 0

http://stackoverflow.com/comment/92415323
type: QuestionComment
comment on: http://stackoverflow.com/q/52730802
score: 0
has text: As a relation, yes... could that help?
type: Comment

http://stackoverflow.com/q/52741824
linked to: http://stackoverflow.com/q/17778372
has comment: http://stackoverflow.com/comment/92409002
upvote count: 1
has body: For the code below: su = 0 def sod(N): global su su += N%10 if N != 0: N = int(N/10) sod(N) return su print(sod(int(input()))) The result is correct. For example., for input 16 its printing 7. But for the code below su = 0 def sod(N): global su su += N%10 if N != 0: N = int(N/10) sod(N) else: return su print(sod(int(input()))) The result is unexpected. Its printing None.
has title: return statement inside conditional statement is giving unexpected results in Python
favorite count: 0
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/17778372
tagged with: recursion
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92408662
type: Question

http://stackoverflow.com/q/52700894
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question
tagged with: numpy
has title: pandas optimizing bootstrapping
downvote count: 0
has body: I am trying to get the standard error of the weighted mean of some columns in a DF. I have the code down to the below, however for a DF of about 800k rows, this takes about 9 seconds, so I am wondering if there are any improvements I am missing that can shave of a significant amount of time, still def bootstrap_se_mean(df: pd.DataFrame, cols:list, w, k=1000): res = np.zeros(shape=(k, len(cols))) for i in range(k): s = df.sample(frac=1, replace=True)[cols +[w]] for j, c in enumerate(cols): res[i, j] = np.average(s[c], weights=s[w], axis=0) return np.apply_along_axis(np.std, 0, res) EDIT example: test=pd.DataFrame({'w': [100, 500, 200, 1000, 300], 'x1': [1.15, 33, -18.2, 3.6, -3.3], 'x2': [22.9, -61.2, -11.2, 33.4, 13.8]}) bootstrap_se_mean(test, ['x1', 'x2'], 'w') I also will have to run the function on slices of the data. It appears that df.sample has quite some overhead, so running it on 5000 rows takes about 1/6 of the time to run over 700k rows. Is there a way to improve this?
favorite count: 0
tagged with: pandas

http://stackoverflow.com/a/52654497
accepted answer of: http://stackoverflow.com/q/52637147
downvote count: 0
answers question: http://stackoverflow.com/q/52637147
has comment: http://stackoverflow.com/comment/92290544
upvote count: 2
has body: Try it: import sys from PyQt5.QtWidgets import QWidget, QHBoxLayout, QPushButton, QApplication from PyQt5.QtGui import QIcon from PyQt5.QtCore import pyqtSlot, QSize class Window(QWidget): def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) self.setGeometry(800, 65, 500, 200) layout = QHBoxLayout(self) layout.addWidget(QPushButton("red button", self, objectName="RedButton", minimumHeight=48)) # ---------------------------------------------------------------------- button = QPushButton(' \n PyQt5\n button\n ', self, objectName="GreenButton", minimumHeight=48) button.setIcon(QIcon("E:/_Qt/img/qt-logo.png")) button.setIconSize(QSize(48, 48)) layout.addWidget(button) # ---------------------------------------------------------------------- layout.addWidget(QPushButton("blue button", self, objectName="BlueButton", minimumHeight=48)) layout.addWidget(QPushButton("orange button", self, objectName="OrangeButton", minimumHeight=48)) layout.addWidget(QPushButton("purple button", self, objectName="PurpleButton", minimumHeight=48)) StyleSheet = ''' QPushButton { border: none; } QPushButton#RedButton { background-color: #f44336; } #RedButton:hover { background-color: #e57373; color: #fff; } #RedButton:pressed { background-color: #ffcdd2; } #GreenButton { background-color: #4caf50; border-radius: 5px; } #GreenButton:hover { background-color: #81c784; color: #fff; } #GreenButton:pressed { background-color: #c8e6c9; } #BlueButton { background-color: #2196f3; min-width: 96px; max-width: 96px; min-height: 96px; max-height: 96px; border-radius: 48px; } #BlueButton:hover { background-color: #64b5f6; } #BlueButton:pressed { background-color: #bbdefb; } #OrangeButton { max-height: 48px; border-top-right-radius: 20px; border-bottom-left-radius: 20px; background-color: #ff9800; } #OrangeButton:hover { background-color: #ffb74d; } #OrangeButton:pressed { background-color: #ffe0b2; } QPushButton[text="purple button"] { color: white; background-color: #9c27b0; } …
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/q/52728538
has comment: http://stackoverflow.com/comment/92383199
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92382643
has answer: http://stackoverflow.com/a/52728837
accepted answer: http://stackoverflow.com/a/52728837
type: Question
has comment: http://stackoverflow.com/comment/92383372
has comment: http://stackoverflow.com/comment/92382301
has comment: http://stackoverflow.com/comment/92382468
has comment: http://stackoverflow.com/comment/92383666
score: 0
has body: Lets say I have two dataframes in pandas. One df1 contains airports with other informations and I have another dataframe df2 which contains the location of these airports (latitutde,longitude). I would like to assign to each row in df1 the appropriate data from df2, how can I do that more elegantly and faster than looping over all the possibilities? Two example image is shown below: Example of df1 Example of df2 ORIGIN DEST DIVERTED 0 ANC SEA 0 1 LAX PBI 0 2 SFO CLT 1 IATA LATITUDE LONGITUDE 17 ANC 61.17432 -149.99619 277 SEA 47.44898 -122.30931 176 LAX 33.94254 -118.40807 235 PBI 26.68316 -80.09559 278 SFO 37.619 -122.37484 66 CLT 35.21401 -80.94313
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/92383311
has title: Get appropriate data for each row in pandas dataframe from another dataframe

http://stackoverflow.com/q/52668290
tagged with: importerror
tagged with: python-module
favorite count: 0
has answer: http://stackoverflow.com/a/52668465
tagged with: pycharm
type: UnansweredQuestion
has body: I want to make a module that is in the same directory as the file that imports the module. For example, if I have a directory "test", the module file is in the directory "test" and another file that is going to import the module is in the directory "test", too. If the module name is "module_name" and the function in it is "function_name", how can I create that module with that function and import it in another file? I tried this: from module_name import function_name But it told me that it is an "Unresolved reference" How can I fix that? What am I doing wrong? I'm using - PyCharm Edu 2018.2 - Python 3.7 (I tried researching and I didn't get the answer)
tagged with: python
has title: How to create module and import it in PyCharm?
downvote count: 1
type: Question
upvote count: 0
answer count: 1
score: -1

http://stackoverflow.com/a/52617941
answers question: http://stackoverflow.com/q/52617814
has body: First you need to get the answer for each function from your user using input() Then, you need to use a boolean for each function to allow or block the use of that function: I think you are looking for smthg like: def function1(): return 2 def function2(): return 4 def function3(): return 6 use_1 = input("Type T to use 1 ") use_2 = input("Type T to use 2 ") use_3 = input("Type T to use 3 ") x=(use_1=='T')*function1()+(use_2=='T')*function2()+(use_3=='T')*function3() print(x)
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92170344
has comment: http://stackoverflow.com/comment/92169983
upvote count: 1
has comment: http://stackoverflow.com/comment/92170321
has comment: http://stackoverflow.com/comment/92170015
has comment: http://stackoverflow.com/comment/92170035
has comment: http://stackoverflow.com/comment/92170072
type: Answer

http://stackoverflow.com/q/52679582
has title: How to get iframe source from page_source when the id isn't on the iframe
tagged with: python
has answer: http://stackoverflow.com/a/52679621
tagged with: selenium-webdriver
type: AnsweredQuestion
tagged with: selenium-chromedriver
tagged with: selenium
upvote count: 1
tagged with: web-scraping
downvote count: 1
has body: Hello today i wanna ask how to get the link inside the page source but without id, i asked before how to get the link with id ok now i understand, but i've tried the same method with another link and i was not successful about that so here is my code: from selenium import webdriver # Create a new instance of the Firefox driver driver_path = r"C:\Users\666\Desktop\New folder (8)\chromedriver.exe" driver = webdriver.Chrome(driver_path) # go to the google home page driver.get("https://www.gledalica.com/sa-prevodom/iron-fist-s02e01-video_02cb355f8.html") # find the element that's name attribute is q (the google search box) element = driver.find_element_by_id("Playerholder") frame = driver.find_element_by_tag_name("iframe") driver.switch_to.frame("iframe") link = frame.get_attribute("src") driver.quit() Like this here: enter image description here
type: Question
accepted answer: http://stackoverflow.com/a/52679621
score: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/52615918
upvote count: 1
has body: First with the given key on which sorting is done, you can get the indices order. You that sequence to rearrange the remaining lists in the dictionary. unsorted_my_dict = { 'key_one': [1, 6, 2, 3], 'key_two': [4, 1, 9, 7], 'key_three': [1, 2, 4, 3], } def sort_parallel_by_key(my_dict, key): def sort_by_indices(idx_seq): return {k: [v[i] for i in idx_seq] for k, v in my_dict.items()} indexes = [idx for idx, _ in sorted(enumerate(my_dict[key]), key=lambda foo: foo[1])] return sort_by_indices(indexes) print(sort_parallel_by_key(unsorted_my_dict, 'key_three'))
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52614943
type: Answer

http://stackoverflow.com/comment/92276929
comment on: http://stackoverflow.com/q/52673285
score: 0
type: Comment
type: QuestionComment
has text: "If np.vectorize() is in general always faster than df.apply(), then why is np.vectorize() not mentioned more?" Because you shouldn't be using `apply` on a row-by-row basis unless you have to, and obviously a vectorized function will out-perform a non-vectorized one.

cpu-word
tags question: http://stackoverflow.com/q/52726395
tag name: cpu-word
type: Tag

http://stackoverflow.com/q/52719830
tagged with: python
upvote count: 11
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52720991
linked to: http://stackoverflow.com/q/52719472
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/92365032
has title: Why does the UnboundLocalError occur on the second variable of the flat comprehension?
tagged with: list-comprehension
tagged with: scope
answer count: 1
has answer: http://stackoverflow.com/a/52720991
has comment: http://stackoverflow.com/comment/92365635
has body: I answered a question here: comprehension list in python2 works fine but i get an error in python3 OP's error was using the same variables for max range and indices: x = 12 y = 10 z = 12 n = 100 ret_list = [ (x,y,z) for x in range(x+1) for y in range(y+1) for z in range(z+1) if x+y+z!=n ] This is a Python-3 error only, and related to the scopes that were added to the comprehension to avoid the variables defined here "leaking". Changing the variable names fixes that. The error is: UnboundLocalError: local variable 'y' referenced before assignment because outer, global y is shadowed by the local scope. My question is: why do I get the error on y and not on z or x ? EDIT: If I remove the loop on x, the error moves to z: &gt;&gt; ret_list = [ (x,y,z) for y in range(y+1) for z in range(z+1) if x+y+z!=n ] UnboundLocalError: local variable 'z' referenced before assignment If I just do one loop: ret_list = [ (x,y,z) for y in range(y+1) if x+y+z!=n ] it works. So I'm suspecting that the first range function is evaluated before all the other expressions, which leaves the value of x intact. But the exact reason is still to be found. Using Python 3.4.3.
favorite count: 0
score: 8
has comment: http://stackoverflow.com/comment/92365140
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92365455

http://stackoverflow.com/a/52652650
type: AcceptedAnswer
type: Answer
score: 16
has body: The labels parameter accepts a callable that takes the list of break points as input. All you have to do is to convert each item in the list manually: scale_y_continuous(labels=lambda l: ["%d%%" % (v * 100) for v in l])
upvote count: 16
accepted answer of: http://stackoverflow.com/q/52625307
answers question: http://stackoverflow.com/q/52625307
downvote count: 0

http://stackoverflow.com/comment/92269646
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52669848
has text: Also take a look at your testing statements. Four of them are true in the case that your entered grade is greater than or equal to 65. Your order eliminates the false positives, but you should be a little more direct.
type: QuestionComment

string
tags question: http://stackoverflow.com/q/52652336
tags question: http://stackoverflow.com/q/52636255
tags question: http://stackoverflow.com/q/52717742
tags question: http://stackoverflow.com/q/52638661
tags question: http://stackoverflow.com/q/52689747
tags question: http://stackoverflow.com/q/52725435
tags question: http://stackoverflow.com/q/52724557
tags question: http://stackoverflow.com/q/52659009
tags question: http://stackoverflow.com/q/52678387
tags question: http://stackoverflow.com/q/52680148
tags question: http://stackoverflow.com/q/52633758
tags question: http://stackoverflow.com/q/52647667
tags question: http://stackoverflow.com/q/52669198
tags question: http://stackoverflow.com/q/52690468
tags question: http://stackoverflow.com/q/52683906
tags question: http://stackoverflow.com/q/52689226
tags question: http://stackoverflow.com/q/52706982
tags question: http://stackoverflow.com/q/52708048
tags question: http://stackoverflow.com/q/52596921
tags question: http://stackoverflow.com/q/52615130
tags question: http://stackoverflow.com/q/52670906
tags question: http://stackoverflow.com/q/52727251
tags question: http://stackoverflow.com/q/52612435
tags question: http://stackoverflow.com/q/52717176
tags question: http://stackoverflow.com/q/52736900
tags question: http://stackoverflow.com/q/52668124
tags question: http://stackoverflow.com/q/52612487
tags question: http://stackoverflow.com/q/52606331
tags question: http://stackoverflow.com/q/52598830
tags question: http://stackoverflow.com/q/52708315
tags question: http://stackoverflow.com/q/52711122
tag name: string
tags question: http://stackoverflow.com/q/52743248
tags question: http://stackoverflow.com/q/52598901
tags question: http://stackoverflow.com/q/52725125
tags question: http://stackoverflow.com/q/52742114
tags question: http://stackoverflow.com/q/52698072
tags question: http://stackoverflow.com/q/52674292
tags question: http://stackoverflow.com/q/52657106
tags question: http://stackoverflow.com/q/52603503
tags question: http://stackoverflow.com/q/52706853
tags question: http://stackoverflow.com/q/52598619
type: Tag
tags question: http://stackoverflow.com/q/52648076
tags question: http://stackoverflow.com/q/52639573
tags question: http://stackoverflow.com/q/52595584
tags question: http://stackoverflow.com/q/52713421
tags question: http://stackoverflow.com/q/52658634
tags question: http://stackoverflow.com/q/52596040
tags question: http://stackoverflow.com/q/52729693
tags question: http://stackoverflow.com/q/52723513
tags question: http://stackoverflow.com/q/52690401
tags question: http://stackoverflow.com/q/52663130
tags question: http://stackoverflow.com/q/52606703
tags question: http://stackoverflow.com/q/52662735
tags question: http://stackoverflow.com/q/52671631
tags question: http://stackoverflow.com/q/52644521
tags question: http://stackoverflow.com/q/52675869
tags question: http://stackoverflow.com/q/52640007
tags question: http://stackoverflow.com/q/52671142
tags question: http://stackoverflow.com/q/52639563
tags question: http://stackoverflow.com/q/52614184
tags question: http://stackoverflow.com/q/52733653
tags question: http://stackoverflow.com/q/52597760
tags question: http://stackoverflow.com/q/52697909
tags question: http://stackoverflow.com/q/52607943
tags question: http://stackoverflow.com/q/52657360
tags question: http://stackoverflow.com/q/52744692
tags question: http://stackoverflow.com/q/52671829
tags question: http://stackoverflow.com/q/52705416
tags question: http://stackoverflow.com/q/52594959
tags question: http://stackoverflow.com/q/52655738
tags question: http://stackoverflow.com/q/52661564
tags question: http://stackoverflow.com/q/52655415
tags question: http://stackoverflow.com/q/52705809
tags question: http://stackoverflow.com/q/52679952
tags question: http://stackoverflow.com/q/52744166
tags question: http://stackoverflow.com/q/52684122
tags question: http://stackoverflow.com/q/52643774
tags question: http://stackoverflow.com/q/52631632

http://stackoverflow.com/a/52697237
accepted answer of: http://stackoverflow.com/q/52697135
has comment: http://stackoverflow.com/comment/92329061
type: Answer
score: 16
has comment: http://stackoverflow.com/comment/92329309
has body: for url in urls: await fetch(session, url) await here means that you don't start downloading next url before previous done. To make all downloadings concurrent you should use something like asyncio.gather. Modify your code like this: async with aiohttp.ClientSession() as session: await asyncio.gather(*[ fetch(session, url) for url in urls ]) You'll see huge speedup.
upvote count: 16
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52697135
downvote count: 0

http://stackoverflow.com/comment/92204945
comment on: http://stackoverflow.com/q/52635168
has text: Can you please post some sample data and the expected result?
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/52628624
has answer: http://stackoverflow.com/a/52665700
type: UnansweredQuestion
tagged with: pyqt5
has body: I'm making custom forms for qgis 3 using qt designer and some python code behind to make verification. However, I have a problem for mapping button action OK and Cancel. I first disconnect the button then I connect them to an other function to validate data in the form. However when I try to call the close function (to close the window's form) it only make the form disappear but the window is still there Here is my code : from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import QLineEdit, QDialogButtonBox, QComboBox, QLabel, QPushButton import psycopg2 myDialog = None cbb_implant = None Validat = 0 def formOpen(dialog,layerid,featureid): bdd = psycopg2.connect("host=localhost") cursor = bdd.cursor() global myDialog myDialog = dialog dialog.hideButtonBox() global cbb_implant cbb_implant = dialog.findChild(QComboBox, "cbb_implantation") cursor.execute('SELECT * FROM l_implantation_type') fetch = cursor.fetchall() if len(fetch)&gt;0: for i in range(0,len(fetch)) : cbb_implant.addItem(fetch[i][1]) cbb_implant.setCurrentIndex(7) ok_chem = dialog.findChild(QPushButton, "ok_chem") ok_chem.clicked.connect(validate) def validate(): global Validat if Validat == 0 : print("HELLO") Validat = 1 else : myDialog.save() myDialog.close() Thank you for your help
type: Question
tagged with: forms
has answer: http://stackoverflow.com/a/55524103
score: 0
has title: close window's form qgis
answer count: 3
tagged with: qgis
tagged with: python
has answer: http://stackoverflow.com/a/55444233

http://stackoverflow.com/comment/92238737
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52653339
has text: I was not aware that python compiled code, are you trying to set breakpoints in your own code or third party code? I would also right click on the eclipse project you have your breakpoints in and see what is on the source path.

http://stackoverflow.com/q/52703577
has body: I am making a random forest multi-classifier model. Basically there are hundred of households which have 200+ features, and based on these features I have to classify them in one of the classes {1,2,3,4,5,6}. The problem I am facing is I cannot improve the accuracy of the model how much ever I can try. I have used RandomSearchCV and also GridSearchCV but I can only achieve accuracy of around 68%. Some points to note The sample points are unbalanced. This is the order of classes in decreasing order {1,4,2,7,6,3}. I have used class_weight = "balanced" but it does improve the accuracy. I have tried number of estimators ranging from 50-450 I have also calculated the f1 score and not only going by accuracy to compare the models What else do you guys suggest to improve the accuracy/f1-score?
score: 0
has comment: http://stackoverflow.com/comment/92334682
has comment: http://stackoverflow.com/comment/92336553
tagged with: multiclass-classification
has answer: http://stackoverflow.com/a/70800413
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has title: Random Forest Multi Class does not improve accuracy
has comment: http://stackoverflow.com/comment/92337184
has comment: http://stackoverflow.com/comment/92337216
type: Question
has comment: http://stackoverflow.com/comment/92334554
tagged with: random-forest
answer count: 1

http://stackoverflow.com/q/52593689
type: Question
has answer: http://stackoverflow.com/a/52593768
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: Contemplating a few options to understand which one would be the best for the below scenario: I have a dataframe in pandas that looks something like CODE NAME COL1 COL2 COL3 IN INDIA x x z US USA r s s IND INDIA f d d RU RUSSIA g f d USA USA d s s IN INDIA d d a I would like to create a new column, say POSSIBLE_CODES such that it is a list of all the CODES the corresponding NAME column has see. So my target df should look like: CODE NAME COL1 COL2 COL3 POSSIBLE_CODES IN INDIA x x z [IN, IND] US USA r s s [US, USA] IND INDIA f d d [IN, IND] RU RUSSIA g f d [RU] USA USA d s s [US, USA] IN INDIA d d a [IN, IND]
has comment: http://stackoverflow.com/comment/92122332
linked to: http://stackoverflow.com/q/47542980
tagged with: python
has title: Using a combination of isin/transform/merge/groupby/map for conditional populating of dataframe column
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/92122405

http://stackoverflow.com/q/52602654
accepted answer: http://stackoverflow.com/a/52602911
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52602690
type: Question
has answer: http://stackoverflow.com/a/52602866
tagged with: dataframe
has answer: http://stackoverflow.com/a/52602911
score: 0
possible better answer: http://stackoverflow.com/a/52602866
answer count: 3
tagged with: pandas
tagged with: header
has body: I'm using a large climate file where there's a YYYY, MM, DD columns. I want to merge these to create a date column, while keep all the original data in the dataset. I have managed to do this so far which gets me almost what I want but I can't seem to get a header in the date column. climate = pd.read_csv(r'R:\Climate\SILO\PatchedPoint\Current_csv\86090.csv') climate.apply(pd.to_numeric, errors = 'ignore') climate_nozero = climate.drop([0]) climate2 = climate_nozero.rename(columns = {'YYYY':'Year','MM':'Month','DD':'Day'}) index = climate2.apply(lambda x: pd.datetime.strptime("{0} {1} {2}".format(x['Year'],x['Month'], x['Day']), "%Y %m %d"),axis=1) climate3 = pd.concat([index, climate2], axis=1) I tried climate4 = climate3.rename(columns = {'0':'Date'}) to change the header but it does nothing I've added the output table that I get
has title: Merging columns to create a date with a header

http://stackoverflow.com/a/52602908
accepted answer of: http://stackoverflow.com/q/52602775
has body: What you're looking for is a way to turn the DataFrame into a structured array, you can find the instructions to do this in the question here Converting pandas dataframe to structured arrays
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52602775
type: Answer

http://stackoverflow.com/q/52623799
accepted answer: http://stackoverflow.com/a/52639291
answer count: 2
tagged with: pyqt
upvote count: 1
downvote count: 0
has body: How I can use callback function from QThread? Callback function on_message does not print any data. In run() I connect to mqtt-broker and subscribe on topic. on_message must work when I get new message. Example simple QT app. Change value event connected with simple QLCD. Subscription topic took from dashboard #!/usr/bin/python3 # -*- coding: utf-8 -*- import sys from PyQt5.QtCore import Qt, QThread, pyqtSignal from PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider, QVBoxLayout, QApplication) from random import uniform, normalvariate, randint import time import paho.mqtt.client as mqtt import paho.mqtt.subscribe as subscribe class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): lcd = QLCDNumber(self) self.data=DataThread() vbox = QVBoxLayout() vbox.addWidget(lcd) self.setLayout(vbox) self.data.valueChanged.connect(lcd.display) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Callback') self.data.start() self.show() class DataThread(QThread): valueChanged = pyqtSignal(object) val=0 def on_message(mqttc, obj, msg): mstr=msg.payload.decode("ascii") val=mstr self.valueChanged.emit(val) def on_subscribe(mqttc, obj, mid, granted_qos): print("Subscribed: "+str(mid)+" "+str(granted_qos)) def run(self): msg = subscribe.simple("shok2", hostname="broker.hivemq.com") print("%s %s" % (msg.topic, msg.payload)) mqttc = mqtt.Client() mqttc.on_subscribe = self.on_subscribe mqttc.on_message = self.on_message mqttc.connect("broker.hivemq.com") print("subsrcibe") mqttc.subscribe("shok2") mqttc.loop_forever() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
favorite count: 0
has answer: http://stackoverflow.com/a/52639291
has answer: http://stackoverflow.com/a/57897169
tagged with: mqtt
has title: Use paho-mqtt with PyQt
tagged with: python
type: AnsweredQuestion
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/92210599
possible better answer: http://stackoverflow.com/a/57897169
score: 1

http://stackoverflow.com/a/52724309
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52692681
type: Answer
answers question: http://stackoverflow.com/q/52692681
has body: You are mistaking string contents with string representation, and making a mess out of it. Strings, as data in Python, be then unicode strings or byte-strings in Python 2 are viewed with surrounding ' quotes whenever you look at their representation. The methods and functions meant to present the string content to the final user (which includes recording then on a file), do show that content without the surrounding quotes. In Python 2, to see the string content in the console you use the print statement. The code that is putting the quotes on your output ".dat" file is not presented here - that code is what puts the string there. If you were recording a raw file yourself, just calling myfile.write(messageid) would write it without the quotes. I tend to think you are using some 3rd party code to write your dat file, passing in your data as a dictionary - that code is including the quotes on the output. The only way you'd get these quotes if you were calling file.write directly is either if you write the repr of your data, like in: myfile.write(repr(messageid)), or if this messageid is inside a list or Python dictionay, and you write the string representation of that data structure to your file - like in file.write(str(my_dict_with_data)) And moreover, it might have reasons for that. .dat is a generic extension for data, and have no real specifications - in many cases, the qutes around data like that, (for example in JSON files), is a desirable thing.
score: 0

http://stackoverflow.com/comment/92131330
type: QuestionComment
comment on: http://stackoverflow.com/q/52598298
has text: Is the provided example the entire dataset? It doesn't contain any rows where the `class` is `1`
score: 0
type: Comment

http://stackoverflow.com/q/52726555
tagged with: python
tagged with: regex
has title: Python, Regex: Extract string after matching string
has body: I want to use regular expressions to match a pattern and extract a section of the pattern. I have scraped HTML data, an illustrative snippet looks like: 1 <a href="/projects/quickfixj/" itemprop="url" title="Find out more DESMO-J DESMO-J is a framework for 29 This Week More representative subset highlighting issue with find_all('a'): Connect The HTML is currently stored as a BeautifulSoup object, i.e. it has been passed through: html_soup= BeautifulSoup(response.text, 'html.parser') I would like to search this entire object for all instances of /projects/ and extract the string between the subsequent slashes. For example: from "/projects/quickfixj/" I would like to store "quickfixj". My initial idea is to use re.findall() and try to match (/projects/./)* but this does not work. Any help is greatly appreciated.
tagged with: web-scraping
upvote count: 1
downvote count: 1
type: Question
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52726737
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52726707
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52726706

http://stackoverflow.com/a/52714689
answers question: http://stackoverflow.com/q/52714605
type: Answer
has body: This is answered on Python - Convert epoch time with nanoseconds to human-readable? &gt;&gt;&gt; datetime.utcfromtimestamp(1539065539013987670/1000000000).strftime('%Y-%m-%d %H:%M:%S.%f') '2018-10-09 06:12:19.013988'
score: 1
has comment: http://stackoverflow.com/comment/92354905
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/92406132
comment on: http://stackoverflow.com/q/52740724
score: 0
has text: Are you sure your program takes a long time because of unoptimized loops as opposed to the unavoidable function calls themself?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92412983
has text: I'm also not sure what you mean by "an analytical way". There's an obvious pattern, and it's trivial to write efficient code to generate those coordinates. What would an "analytical" solution look like?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52744125
type: QuestionComment

http://stackoverflow.com/comment/92170832
type: Comment
comment on: http://stackoverflow.com/a/52618267
score: 1
has text: You're welcome @Gloom. I added one more note to my answer, about the order of nested list comprehensions. Hope that helps. Good luck on your PhD!
type: AnswerComment

http://stackoverflow.com/a/52753568
score: 0
answers question: http://stackoverflow.com/q/52735895
type: Answer
has body: Until now I didn't found a solution, but I'm using a workaround. Converting the Keras model to a tf Graph using a SaveBuilder to store the tf Graph and finally using TocoConverter.from_saved_model(...). import os import tensorflow as tf from keras import backend as K from keras.models import load_model K.set_learning_phase(False) def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True): graph = session.graph with graph.as_default(): freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or [])) output_names = output_names or [] output_names += [v.op.name for v in tf.global_variables()] input_graph_def = graph.as_graph_def() if clear_devices: for node in input_graph_def.node: node.device = "" frozen_graph = tf.graph_util.convert_variables_to_constants(session, input_graph_def, output_names, freeze_var_names) return frozen_graph def create_lite_model_from_saved_model(saved_model_dir, tf_lite_path): converter = tf.contrib.lite.TocoConverter.from_saved_model(saved_model_dir) tf_lite_model = converter.convert() open(tf_lite_path, "wb").write(tf_lite_model) def save_model(keras_model, session, pb_model_path): x = keras_model.input y = keras_model.output prediction_signature = tf.saved_model.signature_def_utils.predict_signature_def({"inputs": x}, {"prediction": y}) builder = tf.saved_model.builder.SavedModelBuilder(pb_model_path) legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op') signature = {tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: prediction_signature, } builder.add_meta_graph_and_variables(session, [tf.saved_model.tag_constants.SERVING], signature_def_map=signature, legacy_init_op=legacy_init_op) builder.save() def run(): sess = K.get_session() keras_model_name = 'keras_model.h5' lite_model_name = 'lite_model_file.tflite' keras_model_file_path = os.path.join('./weights', keras_model_name) lite_model_file_path = os.path.join('./weights', lite_model…

http://stackoverflow.com/q/52591572
favorite count: 0
has comment: http://stackoverflow.com/comment/92118300
tagged with: word-embedding
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: text-classification
has comment: http://stackoverflow.com/comment/92117935
type: Question
has title: How to classify text documents in legal domain
has body: I've been working on a project which is about classifying text documents in the legal domain (Legal Judgment Prediction class of problems). The given data set consists of 700 legal documents (well balanced in two classes). After the preprocessing, which consists in applying all the best practices (such as deleting stopwords,etc.), there are 3 paragraphs for each document, which I could consider all together or separately. On average, the text documents size is 2285 words. I aim to use something different from the classical n-grams model (which doesn't take into account any words order or semantic) : Using a Neural Network (Doc2Vec) for transforming the text of each document into a vector in a continuous domain; in order to create a dataset with the vectors, representing the documents, and the corresponding labels (as I said there are 2 possible labels: 0 or 1); Training a SVM for classifying the samples, I've been using a 10-fold cross-validation. I was wondering if there's someone who has some experience in this particular domain, who can suggest me other ways or how to improve the model since I'm not getting particularly good results: 74% accuracy. Is it correct using Doc2Vec for transforming text into vectors and using them for feeding a classifier? My model represantation:
tagged with: doc2vec
has comment: http://stackoverflow.com/comment/92117936
has answer: http://stackoverflow.com/a/52671494
tagged with: svm
accepted answer: http://stackoverflow.com/a/52671494
upvote count: 3
has comment: http://stackoverflow.com/comment/92118442
answer count: 1
downvote count: 1

http://stackoverflow.com/a/52699940
has comment: http://stackoverflow.com/comment/92436855
has comment: http://stackoverflow.com/comment/92431252
has comment: http://stackoverflow.com/comment/92438717
has comment: http://stackoverflow.com/comment/92398185
has comment: http://stackoverflow.com/comment/92437278
has comment: http://stackoverflow.com/comment/92398409
accepted answer of: http://stackoverflow.com/q/52679018
answers question: http://stackoverflow.com/q/52679018
score: 0
has comment: http://stackoverflow.com/comment/92436093
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92476434
has body: Quite complex one : (EDIT : solution for delete all in the bottom) if you go to this python file (i found this module by turning on echo all, while removing item) : print(mash_repro_aetemplate.__file__) You will find the mash script and the pieces where they call the UI. import maya.OpenMayaUI as mui from shiboken2 import wrapInstance usingPyside2 = False try: import PySide2 usingPyside2 = True except: pass from flux.imports import * from flux.core import pix import flux.core as fx import mash_repro_utils from mash_repro_icons import MASH_REPRO_ICONS from functools import partial import MASH.undo as undo def get_maya_window(): ptr = mui.MQtUtil.mainWindow() if ptr is not None: return wrapInstance(long(ptr), qt.QMainWindow) def refresh_all_aetemplates(force=False): """ Refresh all the repro aetemplates""" widgets = get_maya_window().findChildren(AEMASH_ReproTemplate) or [] for widget in widgets: global SCENE_OPENED SCENE_OPENED = True widget.update_data(widget.node, force=force) SCENE_OPENED = False here is a way to find the repro node : widgets = get_maya_window().findChildren(qt.QWidget, 'AEMASH_ReproTemplate') or [] myRepro = widgets[0] 'myRepro' is now the class of the mash repro node. The Qtreewidget representing your nodes is : myRepro.objs_widget you can use from this other class derived from qtree : # work only on selection, if you want to modify this command, maybe create your own add_sel_bjects(self, objs=[]) myRepro.objs_widget.add_objects() # work only on the selection in the qtree widget myRepro.objs_widget.delete_item() # you can use qtree functions instead : # myRepro.objs_widget.clear() items_count = myRepro.objs_widget.topLevelItemCount() In the delete_item methods, there is this mash_repro_utils.remove_mesh_group(myRepro.objs_widget.node, id) mash_repro_utils.remove_proxy_group(self.node, self.instance_index, id) I didn't had time to investigate but from there, you find : print(mash_repro_utils.__file__) # Result: 'maya_path/plug-ins/MASH/scripts/ma…
type: Answer
has comment: http://stackoverflow.com/comment/92395729
has comment: http://stackoverflow.com/comment/92434916
has comment: http://stackoverflow.com/comment/92475840

http://stackoverflow.com/comment/92277361
comment on: http://stackoverflow.com/q/52673774
has text: this also may help: https://stackoverflow.com/questions/5895588/django-multivaluedictkeyerror-error-how-do-i-deal-with-it
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52747036
has comment: http://stackoverflow.com/comment/92422394
downvote count: 2
has comment: http://stackoverflow.com/comment/92420053
type: Question
has answer: http://stackoverflow.com/a/52747096
possible better answer: http://stackoverflow.com/a/52747375
tagged with: function
upvote count: 0
score: -2
tagged with: variables
answer count: 2
has answer: http://stackoverflow.com/a/52747375
favorite count: 0
has title: Python 2.7 line 5 i am having invalid syntax
has body: Been looking at this for a while and cant seem to figure out why I'm receiving invalid syntax on the if statement. number = 6 if number &gt; 5 and &lt; 9: print “Yes” else: print “No”
tagged with: python
has comment: http://stackoverflow.com/comment/92418851
tagged with: parameters
accepted answer: http://stackoverflow.com/a/52747096
type: AnsweredQuestion

http://stackoverflow.com/q/52685876
tagged with: python-3.x
tagged with: diamond-problem
tagged with: python
score: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52685957
accepted answer: http://stackoverflow.com/a/52685957
tagged with: super
downvote count: 0
linked to: http://stackoverflow.com/q/607186
type: Question
has title: Why is an __init__ skipped when doing Base.__init__(self) in multiple inheritance instead of super().__init__()?
upvote count: 11
has body: Why exactly is A.__init__() B.__init__() D.__init__() printed by the following code? In particular: Why is C.__init__() not printed? Why is C.__init__() printed if I put super().__init__() instead of A.__init__(self)? #!/usr/bin/env python3 class A(object): def __init__(self): super(A, self).__init__() print("A.__init__()") class B(A): def __init__(self): A.__init__(self) print("B.__init__()") class C(A): def __init__(self): A.__init__(self) print("C.__init__()") class D(B, C): def __init__(self): super(D, self).__init__() print("D.__init__()") D()
answer count: 1
tagged with: multiple-inheritance
linked to: http://stackoverflow.com/q/3277367
favorite count: 0

http://stackoverflow.com/comment/92143566
type: AnswerComment
type: Comment
has text: Do you mean that DPI information is not relevant to EPS images?
comment on: http://stackoverflow.com/a/52604689
score: 0

http://stackoverflow.com/q/52671192
tagged with: python
has answer: http://stackoverflow.com/a/52672079
tagged with: google-oauth
type: Question
has title: How to access a user's contact with Google Auth
score: 0
answer count: 1
has body: I have access to a user's contacts, but am having trouble defining the correct "scope" for the requests. Here is an example of doing a valid call to get a user's info: requests.get( "https://www.googleapis.com/oauth2/v2/userinfo", headers={"Authorization": "OAuth %s" % token['access_token']} ).json() {'id': '123454', 'email': 'hello@hello.com', 'verified_email': True, 'name': 'David', 'given_name': 'David', 'family_name': 'K', 'link': 'https://plus.google.com/113517799811778999421', 'picture': 'https://lh3.googleusercontent.com/-AWzSenGDgCs/AAAAAAAAAAI/AAAAAAAAAAA/AAN311234572il0r4-RMKl1VC2234AmqQ/mo/photo.jpg', 'locale': 'en', 'hd': 'hello.com'} How would I do the same for the "contacts" scope (which I reference in another call with: https://www.googleapis.com/auth/contacts.readonly)?
type: UnansweredQuestion

http://stackoverflow.com/comment/102462800
type: Comment
type: QuestionComment
has text: Similar to this question [How do I get my Python program to sleep for 50 milliseconds?](https://stackoverflow.com/q/377454/6075112)
comment on: http://stackoverflow.com/q/52603847
score: 0

http://stackoverflow.com/comment/92305490
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52688884
has text: @smontanaro In the example `df` with numeric values stored as strings and `skipna=False` only `NaN`s are returned. Maybe you can try to adapt your example so that your problem is reproducible?
type: AnswerComment

http://stackoverflow.com/q/52610400
has body: I have created a dictionary containing keys and values. After reading a text file like this: test1 House: True Car: False Money: False Case: 1 test2 House: True Car: False Money: False Case: 2 test3 House: True Car: False Money: False Case: 3 the dictionary is created. The problem is that the values are read as strings. I need to have them as bools so that later I can parse them to a JSON file and use them there as bools. The dictionary created is called answer. I tried the following but it is only giving me True as boolean: to_json = {} block_cnt = 1 header = re.compile('[a-zA-Z0-9]') inner = re.compile("[\t]") empty = re.compile("[\n]",)` with open(rDEMO_parameters.txt', 'r') as document: for line in document: #print line if empty.match(line[0]): continue elif header.match(line[0]): if answer: to_json[block_cnt] = answer #print answer block_cnt += 1 answer = {} elif inner.match(line[0]): _key, value = line.split(": ") tab, key = _key.split("\t") answer[key] = value.split() for key in answer.keys(): if key == "House": answer[key] = map(bool, answer[key]) if key == "Car": answer[key] = map(bool, answer[key]) if key == "Money": answer[key] = map(bool, answer[key]) if key == "Case": answer[key] = map(int, answer[key]) f = open(r"parameters.json", "w") json.dump(to_json, f) f.close() Then after converting I only get something like this but everything in only one line: {1 { House: True Car: True Money: True Case: [1] } } {2 { House: True Car: True Money: True Case: [2] } } {3 { House: True Car: True Money: True Case: [3] }} So the strings are all converted to True booleans, which is not the case. The other problem is that the values are read inside lists. Is there any method to avoid that? Thank you.
has comment: http://stackoverflow.com/comment/92155344
has comment: http://stackoverflow.com/comment/92157635
tagged with: key-value-store
has answer: http://stackoverflow.com/a/52610620
possible better answer: http://stackoverflow.com/a/52610495
has comment: http://stackoverflow.com/comment/92224421
has comment: http://stackoverflow.com/comment/92155293
tagged with: boolean
downvote count: 0
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52612346
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52610530
has answer: http://stackoverflow.com/a/52610495
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/52610530
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92155116
score: 1
has title: How to convert the string value of a dictionary into boolean values?
type: Question

http://stackoverflow.com/q/52655708
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52655880
has title: Configparser.py KeyError (Python/Flask)
has comment: http://stackoverflow.com/comment/92285087
type: Question
score: 0
answer count: 1
tagged with: flask
has body: I am working on an app and I am getting this configparser.py error on my pythonanywhere deployment, however the app runs fine locally. I am not sure why this error is coming up. Traceback (most recent call last): File "/usr/lib/python3.7/configparser.py", line 845, in items d.update(self._sections[section]) KeyError: 'cassBot'

http://stackoverflow.com/comment/92146127
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52605915
has text: Thank´s i added a question ;)
score: 0

http://stackoverflow.com/q/52634992
answer count: 3
possible better answer: http://stackoverflow.com/a/52635182
has comment: http://stackoverflow.com/comment/92204105
has answer: http://stackoverflow.com/a/52635550
score: 0
tagged with: python
has title: How to reverse the process of np.flatten() and mapping?
tagged with: dictionary
has answer: http://stackoverflow.com/a/52635245
has comment: http://stackoverflow.com/comment/92203734
type: AnsweredQuestion
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52635550
has body: I have a target value numpy array with this format, lets say 10 dimensions (24,10) Target = [[ 2, 0, 2, 0, 0, 3, 0, 0, 1, 0, 0, -2, 4, -2, 0, 0, -3, -3, -5, 1, 0, 0, 0, 2],...] So I applied this map checker_presence = { 5: np.array([1,1,1,1,1], dtype=int), 4: np.array([1,1,1,1,0], dtype=int), 3: np.array([1,1,1,0,0], dtype=int), 2: np.array([1,1,0,0,0], dtype=int), 1: np.array([1,0,0,0,0], dtype=int), 0: np.array([0,0,0,0,0], dtype=int), -1: np.array([-1,0,0,0,0], dtype=int), -2: np.array([-1,-1,0,0,0], dtype=int), -3: np.array([-1,-1,-1,0,0], dtype=int), -4: np.array([-1,-1,-1,-1,0], dtype=int), -5: np.array([-1,-1,-1,-1,-1], dtype=int)} labels_ = np.array([list(map(checker_presence.__getitem__, row)) for row in target]) And the target value is now (10,24,5): [[ 1, 1, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 1, 1, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 1, 1, 1, 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], [-1, -1, 0, 0, 0], [ 1, 1, 1, 1, 0], [-1, -1, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [-1, -1, -1, 0, 0], [-1, -1, -1, 0, 0], [-1, -1, -1, -1, -1], [ 1, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 1, 1, 0, 0, 0]],...] After this I applied a flatten function to be only one single array (10,120): labels = np.array([i.flatten() for i in labels_]) [ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 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, -1, -1, 0, 0, 0, 1, 1, 1, 1, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, 0, 0, -1, -1, -1, 0, 0, -1, -1, -1, -1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],...] My question is how I can reverse this process to my target value be the original [ 2, 0, 2, 0, 0, 3, 0, 0, 1, 0, 0, -2, 4, -2, 0, 0, -3, -3, -5, 1, 0, 0, 0, 2] In this example I only use one row to better understanding. The problem is that I needed do this transformation…
has answer: http://stackoverflow.com/a/52635182
has comment: http://stackoverflow.com/comment/92203957

http://stackoverflow.com/q/52593742
downvote count: 0
has comment: http://stackoverflow.com/comment/92157463
has comment: http://stackoverflow.com/comment/92158408
favorite count: 0
tagged with: python-3.x
has body: I've written a script in python using Thread to handl multiple requests at the same time and do the scraping process faster. The script is doing it's job accordingly. In short what the scraper does: It parses all the links from the landing page leading to its main page (where information are stored) and scrape happy hours and featured special from there. The scrapers keeps going on until all the 29 pages are crawled. As there may be numerous links to play with, I would like to limit the number of requests. However, as I don't have much idea on this I can't find any ideal way to modify my existing script to serve the purpose. Any help will be vastly appreciated. This is my attempt so far: import requests from bs4 import BeautifulSoup from urllib.parse import urljoin import threading url = "https://www.totalhappyhour.com/washington-dc-happy-hour/?page={}" def get_info(link): for mlink in [link.format(page) for page in range(1,30)]: response = requests.get(mlink) soup = BeautifulSoup(response.text,"lxml") itemlinks = [urljoin(link,container.select_one("h2.name a").get("href")) for container in soup.select(".profile")] threads = [] for ilink in itemlinks: thread = threading.Thread(target=fetch_info,args=(ilink,)) thread.start() threads+=[thread] for thread in threads: thread.join() def fetch_info(nlink): response = requests.get(nlink) soup = BeautifulSoup(response.text,"lxml") for container in soup.select(".specials"): try: hours = container.select_one("h3").text except Exception: hours = "" try: fspecial = ' '.join([item.text for item in container.select(".special")]) except Exception: fspecial = "" print(f'{hours}---{fspecial}') if __name__ == '__main__': get_info(url)
tagged with: multithreading
has comment: http://stackoverflow.com/comment/92144479
has answer: http://stackoverflow.com/a/52593877
tagged with: python
accepted answer: http://stackoverflow.com/a/52611876
type: AnsweredQuestion
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/52593877
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/92157569
type: Question
has title: Can't modify my script to delimit the number of requests while scraping
has answer: http://stackoverflow.com/a/52614963
has comment: http://stackoverflow.com/comment/92122551
linked to: http://stackoverflow.com/q/3033952
has answer: http://stackoverflow.com/a/52611876
has comment: http://stackoverflow.com/comment/92157200
answer count: 3
has comment: http://stackoverflow.com/comment/92124093

http://stackoverflow.com/q/52667008
score: 0
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/52667470
possible better answer: http://stackoverflow.com/a/52667469
has answer: http://stackoverflow.com/a/52667469
type: AnsweredQuestion
tagged with: html5lib
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52667470
type: Question
answer count: 2
tagged with: python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/92266250
has body: Hello I try to extract the link from page_source and my code is: from bs4 import BeautifulSoup from selenium import webdriver import time import html5lib driver_path = r"C:\Users\666\Desktop\New folder (8)\chromedriver.exe" driver = webdriver.Chrome(driver_path) driver.implicitly_wait(10) driver.get("https://www.milversite.club/milver/outsiders-1x01-video_060893d7a.html") try: time.sleep(4) iframe = driver.find_elements_by_tag_name('iframe') for i in range(0, len(iframe)): f = driver.find_elements_by_tag_name('iframe')[i] driver.switch_to.frame(i) # your work to extract link text = driver.find_element_by_tag_name('body').text print(text) driver.switch_to.default_content() output = driver.page_source print (output) finally: driver.quit(); And now I want to scrape just this link
has title: How to get iframe source from page_source

http://stackoverflow.com/comment/92163784
has text: either use while loop or add line_skip variable, set it to 2 on VOLUME
score: 0
comment on: http://stackoverflow.com/q/52614648
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52760760
answers question: http://stackoverflow.com/q/52727838
score: 0
has body: In the end I've settled on another work-around. I copy the data contents of my subclass-dataframe to a standard dataframe like so: temp_df = pd.DataFrame(sdf) which I then open in the PyCharm dataframe viewer.
type: Answer

http://stackoverflow.com/q/52652789
possible better answer: http://stackoverflow.com/a/52653329
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52653329
tagged with: holoviews
tagged with: python
upvote count: 4
type: AnsweredQuestion
has body: I've been trying to embed bokeh charts in custom templates following this release updates here, examples zip Now I'm trying out holoview as well and was wondering how I can embed holoview with bokeh renderer to custom templates. I'm not able to give name in holowview charts to achieve this {{ embed(roots.mychart) }} Appreciate any help if someone has already tried this out.
downvote count: 0
tagged with: bokeh
type: Question
has title: embed holoview chart with bokeh renderer in custom templates
accepted answer: http://stackoverflow.com/a/52653102
score: 4
answer count: 2
tagged with: dashboard
has answer: http://stackoverflow.com/a/52653102

http://stackoverflow.com/q/52666877
has body: I am attempting to make a game with two surfaces. However when I try and add an image to the game layer it doesn't show up. I have tried using pygame.display.flip() which, from what I understand, should update everything on the screen. If I try to use either Game_Layer.update() or Game_Layer.flip() as seen in the code below... (I think Game_Layer.flip() doesn't work because .flip is used to update the entire screen and thus can't be called for specific layers but correct me if I am wrong). #game play def Dragon(): DragonIMG=pygame.image.load("Green Dragon.gif") DragonIMG.convert() global Game_Layer x=0 y=0 Game_Layer.blit(DragonIMG,(x,y)) Game_Layer.update() Dragon() I get the following error message: RESTART: C:\Users\Alex\OneDrive\A- Levels\1 COMPUTER SCIENCE\Course work\Coding\CSCW Pre Alfa 1.9.5.py Traceback (most recent call last): File "C:\Users\Alex\OneDrive\A- Levels\1 COMPUTER SCIENCE\Course work\Coding\CSCW Pre Alfa 1.9.5.py", line 133, in &lt;module&gt; Dragon() File "C:\Users\Alex\OneDrive\A- Levels\1 COMPUTER SCIENCE\Course work\Coding\CSCW Pre Alfa 1.9.5.py", line 131, in Dragon Game_Layer.update() AttributeError: 'pygame.Surface' object has no attribute 'update' &gt;&gt;&gt; However when I try to display an image on the root layer using the code below it works. #game play def Dragon(): DragonIMG=pygame.image.load("Green Dragon.gif") DragonIMG.convert() global Base_Layer x=0 y=0 Base_Layer.blit(DragonIMG,(x,y)) pygame.display.flip() Dragon() Below is the code I am using to set up the layers: #libraries import time, random, pygame, sqlite3, GIFimage2 pygame.init() #screen setup #variables clock=pygame.time.Clock() #for use in .tick black=pygame.color.Color("black") #set black white=pygame.color.Color("white") #set white #set up the base layer Base_Layer=pygame.display.set_mode((1000,600)) #desplay setup pygame.display.set_caption("Dragon King: Legacy") #set caption black=(0,0,0) #colour set Base_Layer.fill(black) #colour set Base_Layer.convert() #conver…
upvote count: 1
has answer: http://stackoverflow.com/a/52668776
accepted answer: http://stackoverflow.com/a/52668776
favorite count: 0
possible better answer: http://stackoverflow.com/a/52667067
tagged with: python
tagged with: pygame
tagged with: blit
has answer: http://stackoverflow.com/a/52667067
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Images not showing on surface in pygame
type: Question
tagged with: surface
answer count: 2

http://stackoverflow.com/comment/92381875
type: QuestionComment
has text: @WillemVanOnsem Sorry, but I did not understand
score: 0
comment on: http://stackoverflow.com/q/52727538
type: Comment

http://stackoverflow.com/comment/92194600
type: Comment
comment on: http://stackoverflow.com/q/52629410
type: QuestionComment
has text: What I mean is, you cannot discard any of the tensor at the moment of creation, because all of them _could_ be useful. Let's say you somehow figure out you should skip the fourth output in the list; but then you can always feed some `partitions` with a `4` in it, and you would lose some numbers. You can apply operations that do different things depending on the size, but the actual size can only be known when you feed the data. Maybe knowing what kind of operations you intend to create with this tensors (and why you need them to be non-empty) would help to find a workaround.
score: 0

http://stackoverflow.com/comment/92371544
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52721616
has text: Made an edit, does it make things clearer?
score: 0

http://stackoverflow.com/comment/92292810
has text: `pass` is not an object. It is a statement. It's like asking what is the type of `continue` or `break`
score: 4
type: Comment
comment on: http://stackoverflow.com/q/52682332
type: QuestionComment

word2vec
tags question: http://stackoverflow.com/q/52662133
tags question: http://stackoverflow.com/q/52734472
tags question: http://stackoverflow.com/q/52645459
tags question: http://stackoverflow.com/q/52645618
tags question: http://stackoverflow.com/q/52744467
tags question: http://stackoverflow.com/q/52724444
tags question: http://stackoverflow.com/q/52686366
tags question: http://stackoverflow.com/q/52618479
tags question: http://stackoverflow.com/q/52725193
tags question: http://stackoverflow.com/q/52663908
type: Tag
tags question: http://stackoverflow.com/q/52734146
tag name: word2vec
tags question: http://stackoverflow.com/q/52693004

http://stackoverflow.com/q/52655841
has answer: http://stackoverflow.com/a/71778233
has comment: http://stackoverflow.com/comment/92242952
tagged with: python
upvote count: 13
has title: OpenCV & Python Multithreading - Seeking within a VideoCapture Object
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92284946
has answer: http://stackoverflow.com/a/52679667
tagged with: multithreading
score: 13
has comment: http://stackoverflow.com/comment/92243145
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/92245856
has body: I've been working on a python application which uses OpenCV to read frames from a video and create a composite of the "activity", i.e. the things that have changed from one frame to the next. To do that, I only really want to check one frame per second or so. For a long time I've been using the following code (simplified, with some error checking, classes, etc removed for brevity) to get the video object and the first frame: video_capture = cv2.VideoCapture(video_fullpath) this_frame = get_frame(0) def get_frame(time): video_capture.set(cv2.CAP_PROP_POS_MSEC, time) capture_success, this_frame = video_capture.read() return this_frame The process of getting subsequent frames, using the latter two lines of code above, is really slow. On a 2015 MacBook Pro it takes 0.3-0.4s to get each frame (at 1sec intervals in the video, which is a ~100MB .mp4 video file). By comparison, the rest of my operations, which are comparing each frame to its predecessor, are very quick - typically less than 0.01s. I've therefore been looking at multi-threading, but I'm struggling. I can get multi-threading working on a "lookahead" basis, i.e. whilst I'm processing one frame I can be getting the next one. And once I'm done processing the previous frame, I'll wait for the "lookahead" operation to finish before continuing. I do that with the following code: while True: this_frame, next_frame_thread = get_frame_async(prev_frame.time + time_increment) &lt;&lt; do processing of this_frame ... &gt;&gt; next_frame_thread.join() def get_frame_async(time): if time not in frames: frames[time] = get_frame(time) next_frame_thread = Thread(target=get_frame, args=(time,)) next_frame_thread.start() return frames[time], next_frame_thread The above seems to be working, but because the seeking operation is so slow compared to everything else it doesn't actually save much time - in fact it's difficult to see any benefit at all. I then wondered whether I could be getting multiple frames in parallel. However, wh…
accepted answer: http://stackoverflow.com/a/52679667
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/52911236
has answer: http://stackoverflow.com/a/52911236
favorite count: 0

http://stackoverflow.com/comment/92380688
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52727746
type: Comment
has text: I installed python 3 directly. Given that python3 doesn't work I assume that python stands for python3 specifically.

http://stackoverflow.com/comment/92255025
type: Comment
has text: Better to use `BeautifulSoup` to parse html
comment on: http://stackoverflow.com/q/52662494
score: 4
type: QuestionComment

http://stackoverflow.com/comment/92304697
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52688786
has text: Have you read the docs for `ThreadPool.map`? You should be able to fix this quickly once you read it.
score: 0

http://stackoverflow.com/q/52636101
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/99380250
has body: I have a large snakemake file that looks like this (after simplifying a lot). rule a: input: '{path}.csv' output: '{path}.a.csv' shell: 'cp {input} {output}' rule b: input: '{path}.csv' output: '{path}.b.csv' shell: 'cp {input} {output}' rule c: input: '{path}.csv' output: '{path}.c.csv' shell: 'cp {input} {output}' rule d: input: '{path}.csv' output: '{path}.d.csv' shell: 'cp {input} {output}' rule all: input: 'raw1.a.b.c.a.d.csv', 'raw2.a.b.c.d.a.csv' (This setup lets me use rules like functions, by chaining their filename suffixes in the all rule.) Starting state: $ ls -tr1 Snakefile raw1.csv raw2.csv $ snakemake all ... After: $ ls -tr1 Snakefile raw1.csv raw2.csv raw2.a.csv raw2.a.b.csv raw2.a.b.c.csv raw2.a.b.c.d.csv raw1.a.csv raw1.a.b.csv raw1.a.b.c.csv raw1.a.b.c.a.csv raw1.a.b.c.a.d.csv raw2.a.b.c.d.a.csv Now, I'd like to add a rule that deletes specific intermediate files (for example raw1.a.csv and raw2.a.b.csv) because I don't need them and they take up a lot of disk space. I can't mark the outputs with temp() because of the wildcard {path}. Any tips? Thanks.
type: UnansweredQuestion
tagged with: snakemake
has answer: http://stackoverflow.com/a/52636147
has title: snakemake rule to delete file
type: Question
has answer: http://stackoverflow.com/a/52636580
answer count: 2

http://stackoverflow.com/q/52625106
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has title: How to pivot a dataframe so each column becomes a list in a cell?
type: Question
has answer: http://stackoverflow.com/a/52625146
has body: I'm trying to pivot this dataframe: pd.DataFrame([[1, 4], [2, 5], [3, 6]], columns=['a', 'b']) to this one: pd.DataFrame([['a', [1, 2, 3]], ['b', [4, 5, 6]]], columns=['key', 'list']) Ignoring the column renaming, is there a way to do it without iterating over the rows and converting them to a list and then a new column?
has comment: http://stackoverflow.com/comment/92188029
has comment: http://stackoverflow.com/comment/92207605
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52625146
linked to: http://stackoverflow.com/q/993984
tagged with: python

http://stackoverflow.com/q/52621830
has answer: http://stackoverflow.com/a/52622081
score: -2
answer count: 2
has comment: http://stackoverflow.com/comment/92177282
upvote count: 0
has title: urllib.request 'Request' object has no attribute 'getcode' and read
favorite count: 0
tagged with: python-3.x
tagged with: urllib3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92177269
tagged with: python
has comment: http://stackoverflow.com/comment/92177889
has body: I am getting error for print statement 'Request' object has no attribute 'getcode' and read sample = '[{{ "t": "{0}", "to": "{1}", "evs": "{2}", "fds": {3} }}]' response = urllib.request.Request(REST_API_URL, sample.encode('utf-8')) print("Response: HTTP {0} {1}\n".format(response.getcode(), response.read()))
downvote count: 2
has comment: http://stackoverflow.com/comment/92177869
tagged with: urllib
type: Question
has answer: http://stackoverflow.com/a/52621930

http://stackoverflow.com/comment/92426173
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52746014
has text: It *may* be the shell initialization for `oracle` that’s running `stty`; try without the `-` argument to `su`?
score: 0

http://stackoverflow.com/a/52599682
answers question: http://stackoverflow.com/q/52599582
has comment: http://stackoverflow.com/comment/92134056
has body: Using the hour attribute is not enough if you want to find entries corresponding to noon at 12:00PM. Instead, compare your index/date-range with a datetime object: dt = pd.date_range('2018-02-13', '2018-02-19', freq='1h') dt[dt.time == datetime.time(12)] DatetimeIndex(['2018-02-13 12:00:00', '2018-02-14 12:00:00', '2018-02-15 12:00:00', '2018-02-16 12:00:00', '2018-02-17 12:00:00', '2018-02-18 12:00:00'], dtype='datetime64[ns]', freq=None) If you want to introduce a minutes or seconds component, simply change datetime.time(12) to datetime.time(12, 5) for 12:05:00PM, or datetime.time(12, 5, 30) for 12:05:30PM, and so on.
has comment: http://stackoverflow.com/comment/92134006
score: 6
accepted answer of: http://stackoverflow.com/q/52599582
upvote count: 6
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92133973
has comment: http://stackoverflow.com/comment/92133957
type: Answer
has comment: http://stackoverflow.com/comment/92134027

http://stackoverflow.com/comment/92196434
comment on: http://stackoverflow.com/q/52619874
type: Comment
type: QuestionComment
has text: More on doing math with object dtype arrays: https://stackoverflow.com/questions/51447460/location-of-documentation-on-special-methods-recognized-by-numpy/51447793#51447793. It helps explain why multiplication works, but `sin` does not.
score: 1

http://stackoverflow.com/a/52608152
type: Answer
downvote count: 0
score: 2
has body: What is happening is this: when you select a range of text and then press a key, tkinter must do two things: it must delete the selected text and then it must insert the new text. The handler is first called for the delete. Because the delete causes the entry widget to be completely empty, and you can't convert an empty string to a float, your handler returns False. This prevents the delete from happening. Next, your handler is called for the insert. The old text is still there. You allow the insert, so you end up with the result that the selected text is not removed and the new text is inserted right before it. The simplest solution is to allow for an empty string. You can then simply validate that a non-empty string can be converted to a float. Example: import tkinter as tk # python 3.x import tkinter.ttk as ttk # python 3.x class Example(ttk.Frame): def __init__(self, parent): super().__init__(parent) # %P = value of the entry if the edit is allowed vcmd = (self.register(self.onValidate),'%P') self.entry = ttk.Entry(self, validate="key", validatecommand=vcmd) self.entry.pack(side="top", fill="x") def onValidate(self, P): if P.strip() == "": # allow blank string return True try: float(P) return True except: return False if __name__ == "__main__": root = tk.Tk() Example(root).pack(fill="both", expand=True) root.mainloop()
has comment: http://stackoverflow.com/comment/92210903
upvote count: 2
answers question: http://stackoverflow.com/q/52595293

http://stackoverflow.com/comment/92359082
score: 0
has text: btw, if you're unsure you're using the same interpreter, running tests via `pytest -v` will output the path to the used interpreter along some other info, so you may check that easily.
type: QuestionComment
comment on: http://stackoverflow.com/q/52713154
type: Comment

http://stackoverflow.com/comment/92223075
score: 0
has text: @Vailbhav Vishal I have added 2 screen grabs to my question to demonstrate my structure. Let me know if you need any further code
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52643357

http://stackoverflow.com/comment/92214928
has text: i'm using REST framework can you help with serializer
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52640886
type: AnswerComment

http://stackoverflow.com/comment/92134831
type: Comment
score: 0
type: AnswerComment
has text: I see! Are you updating your display? If not, add "pygame.display.update()"
comment on: http://stackoverflow.com/a/52600093

http://stackoverflow.com/comment/92238631
has text: @questionable_code A class attribute is shared by all instances, it isn't copied into the instances. So it uses the same amount of RAM as making it a global. And yes, defining a class attribute before the `__init__` is the usual practice. You just use the bare name `expected_keys` for the definition, but inside the methods you can read from it with `Spam.expected_keys` or `self.expected_keys`.
type: Comment
comment on: http://stackoverflow.com/a/52653014
score: 1
type: AnswerComment

http://stackoverflow.com/q/52663724
score: 1
has comment: http://stackoverflow.com/comment/95028684
favorite count: 0
linked to: http://stackoverflow.com/q/49947694
has body: My code is: from selenium import webdriver driver = webdriver.Firefox() driver.get('https://python.org') driver.close() The error is: Traceback (most recent call last): File "C:\Users\Aleksandra\PycharmProjects\YoutubeRG\venv\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start stdin=PIPE) File "C:\Users\Aleksandra\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 769, in __init__ restore_signals, start_new_session) File "C:\Users\Aleksandra\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1172, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Aleksandra/PycharmProjects/YoutubeRG/youtubemain.py", line 3, in &lt;module&gt; driver = webdriver.Firefox() File "C:\Users\Aleksandra\PycharmProjects\YoutubeRG\venv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 164, in __init__ self.service.start() File "C:\Users\Aleksandra\PycharmProjects\YoutubeRG\venv\lib\site-packages\selenium\webdriver\common\service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. I put the path to geckodriver in the systemvariable's path: https://i.sstatic.net/DiuGv.png What else can I do? I am lost.
type: Question
linked to: http://stackoverflow.com/q/40208051
tagged with: python
duplicate of: http://stackoverflow.com/q/49947694
tagged with: selenium-webdriver
duplicate of: http://stackoverflow.com/q/40208051
tagged with: selenium-chromedriver
tagged with: selenium
has title: "geckodriver" executable needs to be in PATH Pycharm
upvote count: 1
duplicate of: http://stackoverflow.com/q/44631020
type: UnansweredQuestion
answer count: 0
downvote count: 0

http://stackoverflow.com/q/52615715
accepted answer: http://stackoverflow.com/a/52655272
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: tensorboard
tagged with: python
type: AnsweredQuestion
score: 1
has body: I am confused about the graph I am getting in Tensborboad for my Keras LSTM network. I have defined my Keras LSTM network like this: model = Sequential() model.add(LSTM(neurons, return_sequences=True,input_shape=(look_back,2))) #model.add(Bidirectional(LSTM(neurons, return_sequences=True),input_shape=(look_back,2))) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kernel_regularizer=l2(weight_decay),bias_regularizer=l2(weight_decay),dropout=dropout,recurrent_dropout=dropout)) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kernel_regularizer=l2(weight_decay),bias_regularizer=l2(weight_decay),dropout=dropout,recurrent_dropout=dropout)) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kernel_regularizer=l2(weight_decay),bias_regularizer=l2(weight_decay),dropout=dropout,recurrent_dropout=dropout)) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kernel_regularizer=l2(weight_decay),bias_regularizer=l2(weight_decay),dropout=dropout,recurrent_dropout=dropout)) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kernel_regularizer=l2(weight_decay),bias_regularizer=l2(weight_decay),dropout=dropout,recurrent_dropout=dropout)) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kernel_regularizer=l2(weight_decay),bias_regularizer=l2(weight_decay),dropout=dropout,recurrent_dropout=dropout)) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kernel_regularizer=l2(weight_decay),bias_regularizer=l2(weight_decay),dropout=dropout,recurrent_dropout=dropout)) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kernel_regularizer=l2(weight_decay),bias_regularizer=l2(weight_decay),dropout=dropout,recurrent_dropout=dropout)) model.add(LSTM(neurons,return_sequences=True,recurrent_regularizer=l2(weight_decay), kerne…
upvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52655272
has title: Understanding Keras LSTM Tensorboard Graph
tagged with: lstm
linked to: http://stackoverflow.com/q/46259467

http://stackoverflow.com/a/52595089
score: 0
type: AcceptedAnswer
type: Answer
has body: First, Python won't allow you to modify a string (they are 'immutable'), but you can turn them into lists, modify them and then turn them back into strings. Looks difficult or slow, but not at all. Second, 'continue' in Python is used scarcely. A good code shouldn't have it. That's why you have elif's and else's after all. Third, Don't use an 'if' if you are not doing anything within it. Fourth, learn pythonic tricks (like the == or the = lines below), that's the real difference from other languages. Makes code clearer in most of the cases. Cheers def constructPalin(string, length): i = 0 j = length - 1 string = list(string) # turn it to list, as strings can't be modified while (i &lt;= j): # '&lt;=' to consider a '.' in the middle # if (string[i] == string[j] and string[i] != '.'): # only use 'if' when you need to if (string[i] == string[j] == '.'): # both equal to '.' string[i] = string[j] = 'a' # turn them to 'a' elif string[i] != string[j]: # not equal, can still be fixed filling the '.'s? if (string[i] == '.'): string[i] = string[j] elif (string[j] == '.'): string[j] = string[i] else: # hopeless string = "-1" return string i = i + 1 # if you use "continue", you'll never reach these lines j = j - 1 # ... and the program loops forever return "".join(string) # turn it back to string
answers question: http://stackoverflow.com/q/52593916
accepted answer of: http://stackoverflow.com/q/52593916

http://stackoverflow.com/a/52669097
upvote count: 2
has comment: http://stackoverflow.com/comment/92268652
has comment: http://stackoverflow.com/comment/92306443
answers question: http://stackoverflow.com/q/52668862
has comment: http://stackoverflow.com/comment/92306327
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92306384
type: Answer
score: 2
downvote count: 0
has body: Here's one that scales well for generic ndarrays - def maxindex(a, b, fillna=-1): sidx = a.argsort(-1) m = np.isin(sidx,b) idx = m.shape[-1] - m[...,::-1].argmax(-1) - 1 out = np.take_along_axis(sidx,idx[...,None],axis=-1).squeeze() return np.where(m.any(-1), out, fillna) Sample runs - In [83]: a Out[83]: array([[ 1, 4, 6, 2, 5], [ 3, 2, 7, 12, 1], [ 8, 5, 3, 1, 4], [ 6, 10, 2, 4, 9]]) In [84]: b Out[84]: array([0, 1, 4]) In [85]: maxindex(a, b) # all rows Out[85]: array([4, 0, 0, 1]) In [86]: maxindex(a[1], b) # second row Out[86]: array([0]) 3D case - In [105]: a Out[105]: array([[[ 1, 4, 6, 2, 5], [ 3, 2, 7, 12, 1], [ 8, 5, 3, 1, 4], [ 6, 10, 2, 4, 9]], [[ 1, 4, 6, 2, 5], [ 3, 2, 7, 12, 1], [ 8, 5, 3, 1, 4], [ 6, 10, 2, 4, 9]]]) In [106]: maxindex(a, b) Out[106]: array([[4, 0, 0, 1], [4, 0, 0, 1]])
has comment: http://stackoverflow.com/comment/92268628
has comment: http://stackoverflow.com/comment/92306369
has comment: http://stackoverflow.com/comment/92306345
has comment: http://stackoverflow.com/comment/92269070
accepted answer of: http://stackoverflow.com/q/52668862

http://stackoverflow.com/comment/92115859
has text: have you looked at `pandas.DataFrame.apply` ?
score: 1
comment on: http://stackoverflow.com/q/52590546
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92145564
has text: This is going to be difficult to answer without a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Can you provide the minimal amount of code that one can copy&paste that reproduces the problem?
comment on: http://stackoverflow.com/q/52603247
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/52744633
has body: Setting plt.autoscale(False) prevents autoscaling from happening. import numpy as np; np.random.seed(42) import matplotlib.pyplot as plt xy = np.random.randn(100, 2) # By default plots are autoscaled. plt.scatter(xy[:,0], xy[:,1]) #Turn autoscaling off plt.autoscale(False) xlim = plt.gca().get_xlim() plt.plot(xlim, xlim, 'k--') plt.show()
has comment: http://stackoverflow.com/comment/92414373
has comment: http://stackoverflow.com/comment/92415772
has comment: http://stackoverflow.com/comment/92415690
upvote count: 12
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92415283
type: Answer
has comment: http://stackoverflow.com/comment/92414882
has comment: http://stackoverflow.com/comment/92417765
has comment: http://stackoverflow.com/comment/92414127
answers question: http://stackoverflow.com/q/52743065
score: 12
has comment: http://stackoverflow.com/comment/92415109
has comment: http://stackoverflow.com/comment/92416730
has comment: http://stackoverflow.com/comment/92415414
accepted answer of: http://stackoverflow.com/q/52743065

http://stackoverflow.com/comment/92180875
has text: Hi can you share some more details please ?
comment on: http://stackoverflow.com/q/52623568
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53395548
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I think you need to use Custom Routers. Just an example: class Resource: def on_get(self, req, resp): resp.body = req.method resp.status = falcon.HTTP_200 def on_example(self, req, resp): resp.body = req.method resp.status = falcon.HTTP_200 class MyRouter(routing.DefaultRouter): # this is just demonstration that my solution works # I added request method into method_map def add_route(self, uri_template, method_map, resource): super().add_route(uri_template, method_map, resource) method_map['EXAMPLE'] = resource.on_example def find(self, uri, req=None): return super().find(uri, req) api = falcon.API(router=MyRouter()) # just set your router test = Resource() api.add_route('/test', test) Let's check: curl -X EXAMPLE http://127.0.0.1:8000/test EXAMPLE⏎ curl http://127.0.0.1:8000/test GET⏎ So, all what you need is just create Router and implement add_route() / find() methods. Hope you understand what I mean.
answers question: http://stackoverflow.com/q/52688122
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52688122
score: 3
has comment: http://stackoverflow.com/comment/93696221

http://stackoverflow.com/comment/92183967
comment on: http://stackoverflow.com/a/52624740
type: Comment
has text: take that back, all columns are there as they should be. Thanks again for the help.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92175310
comment on: http://stackoverflow.com/q/52620752
type: Comment
type: QuestionComment
score: 3
has text: for current example will work `re.sub(r'(\d\d+)(\w\w)(\d\d\d\d)', r'\1-\2-\3', data)`

http://stackoverflow.com/comment/92204235
type: AnswerComment
has text: what if want color1 and color2 in ('blue', 'red')
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52635417

http://stackoverflow.com/comment/92419721
type: Comment
has text: It still not clear what is your issue, but this will just return *all* the text nodes.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52747339

http://stackoverflow.com/comment/92122494
type: AnswerComment
comment on: http://stackoverflow.com/a/52590820
type: Comment
has text: Yes of course, but this is purely synthetical data: a perfect parabola with some random noise added, and it does _not_ go through [1000, 0]... So if your picture is the same, I'd guess that the requirement " must go through [1000, 0]" perhaps is wrong... It's a matter of decision what fits better: the 2nd order characteristic or the point at [1000, 0]
score: 0

http://stackoverflow.com/q/52653052
favorite count: 0
has answer: http://stackoverflow.com/a/52667399
tagged with: apache-beam
tagged with: python
type: UnansweredQuestion
upvote count: 1
has title: Google Cloud Platform Dataflow integration
has body: Is it possible to leverage command line tools within GCP Dataflow? Essentially, I have files that I currently pass as arguments into a command line tool, and that tool outputs a different file based on the input. I'm not exactly sure what the tool does so recreating the logic within Dataflow is out of question. Is there any way to call this tool using the os or subprocess modules while still taking advantage of Dataflow's benefits?
tagged with: google-cloud-dataflow
type: Question
tagged with: google-cloud-platform
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/52635968
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52636260
type: Question
answer count: 2
downvote count: 2
tagged with: animation
tagged with: python
score: -2
tagged with: module
accepted answer: http://stackoverflow.com/a/52636094
has body: I'm new to this forum :) I'm learning python, so far I can make programs without much effort, I'm planning to make a program where it shows a window with some animations when it detects an event, for example, if I press a key the window shows a nice "icon" with some nice transitions and disappears. which module should fit perfect for this task? I want to work with nice icons made on Illustrator. Something like this page but the fact is I don't want to make it on a web browser. https://www.jqueryscript.net/demo/Animated-Interactive-Donut-Chart-with-jQuery-Snap-svg/
tagged with: transition
upvote count: 0
has title: How to make animations with python
has answer: http://stackoverflow.com/a/52636094
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52636260

http://stackoverflow.com/comment/92208280
comment on: http://stackoverflow.com/q/52616670
has text: @KevinFang This is the entire error message: `tensorflow.python.framework.errors_impl.InvalidArgumentError: transpose expects a vector of size 4. But input(1) is a vector of size 3 [[Node: bidirectional_1/transpose = Transpose[T=DT_FLOAT, Tperm=DT_INT32, _class=["loc:@gradients/AddN_19"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_1/embedding_lookup, gradients/bidirectional_1/transpose_grad/InvertPermutation)]]`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52652585
tagged with: python
has answer: http://stackoverflow.com/a/52652697
type: Question
has body: For example : i have midpoints of intervals : midpoints=[1,2,4] and want to convert that to intervals : intervals=[0.,1.5,3.,+infinity] is that possible ?
has title: With pandas, How to generate bins from midpoints?
score: 0
tagged with: pandas
tagged with: intervals
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/92368791
type: QuestionComment
has text: Just a follow up on this one, it appeared the excel sheet contained very annoying comments like this: : which crashed openpyxl.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52623085

http://stackoverflow.com/comment/92379656
score: 1
comment on: http://stackoverflow.com/a/52725453
type: AnswerComment
type: Comment
has text: A regex would work, alternatively: `t1.replace('-MIN-','')`

http://stackoverflow.com/q/52737112
has title: Numpy histogram parameters
has body: I want to get histogram of an image but I have an error that I don't know how to solve it. It's due to I don't know what are right values for numpy histogram parameters: My code is: rojo = np.histogram(imagen[:,:,0], range(0,256), bins = 256) verde = np.histogram(imagen[:,:,1], range(0,256), bins = 256) azul = np.histogram(imagen[:,:,2], range(0,256), bins = 256) The error is: 9 rojo = np.histogram(imagen[:,:,0], range(0,256), bins = 256) 10 verde = np.histogram(imagen[:,:,1], range(0,256), bins = 256) 11 azul = np.histogram(imagen[:,:,2], range(0,256), bins = 256) TypeError: string indices must be integers What's wrong? Thanks
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92408826
has comment: http://stackoverflow.com/comment/92417865
has comment: http://stackoverflow.com/comment/92398988
has comment: http://stackoverflow.com/comment/92401190
has comment: http://stackoverflow.com/comment/92402297
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92398957
tagged with: histogram
has comment: http://stackoverflow.com/comment/92403272
score: 0

http://stackoverflow.com/q/52658094
downvote count: 0
accepted answer: http://stackoverflow.com/a/52658312
favorite count: 0
has comment: http://stackoverflow.com/comment/92246738
tagged with: extract
has comment: http://stackoverflow.com/comment/92246736
has comment: http://stackoverflow.com/comment/92246756
type: Question
tagged with: python
tagged with: filenames
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/92246899
has title: Extract details in multiple image filenames in Python and add them as labels for a dataset
has comment: http://stackoverflow.com/comment/92246953
has answer: http://stackoverflow.com/a/52658312
has body: I have a folder containing 1300 .JPEG files all of which have filenames in a specific order. The order of each file name is category_count_randomString.JPEG. To give an example, below is one image from the folder: 13_2_5jdf.JPEG where 13 is the category, 2 is the count of that category in the image, followed by the random string. I'd like to be able to: extract both the category from each filename and assign them as labels (to then build a CNN model) and extract the count of the category from each filename and also assign them to a vector/array. For now, I've just loaded the images (not yet as an array) using the glob function. import glob data = '/Users/Data' images = glob.glob(data+'/*.JPEG') I'm new to coding and so I'm looking for someone to be able to provide 'idiot-proof' lines of coding that I can just incorporate into my notebook to make this work.
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/92246922

http://stackoverflow.com/q/52596204
has comment: http://stackoverflow.com/comment/94562208
tagged with: python
linked to: http://stackoverflow.com/q/879173
has body: Whenever I try to use "sklearn" in PyCharm, I get the following error on the console. DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp I am not sure if it should bother me, because program still working, but it's annoying. How can I get rid of it? I made every change, people recommended in linked question but the error is still there.
has comment: http://stackoverflow.com/comment/95970771
has title: The imp module is deprecated
has comment: http://stackoverflow.com/comment/92127130
has comment: http://stackoverflow.com/comment/115387630
type: Question
has answer: http://stackoverflow.com/a/52596897
answer count: 1
tagged with: scikit-learn
upvote count: 31
downvote count: 1
score: 30
favorite count: 0
has comment: http://stackoverflow.com/comment/97574483
duplicate of: http://stackoverflow.com/q/879173
tagged with: pycharm
has comment: http://stackoverflow.com/comment/94375233
type: UnansweredQuestion

http://stackoverflow.com/comment/92176332
type: Comment
type: QuestionComment
has text: Every time I run the code the turtle just shows for a split second. I am trying to connect the variables x and size1 together so that when it goes to create the shape it calculates in the drawSquareFromCenter function because size1 determines the size of the squares throughout the project. If there is a way for me to do that without having to possibly rewrite anything then that'd be nice.I feel that if I can connect both variables it should work, but I am not sure how. I feel like the answer is really simple, but I am just not seeing it
score: 0
comment on: http://stackoverflow.com/q/52621163

http://stackoverflow.com/q/52695654
favorite count: 0
has comment: http://stackoverflow.com/comment/93522156
upvote count: 2
tagged with: python
has body: Answers to Get default line colour cycle are quite helpful and indicate there's been a change at around version 1.5. I'm wondering if there is a simple way to "pause", "resume" and "reset" the way that Matplotlib cycles through default colors without implementing it manually. Example below is not a good way to do it manually, but just illustrates how hypothetical colorpause(), colorresume(), and colorreset() might be used. def colorpause(): global increment_me increment_me = False def colorresume(): global increment_me increment_me = True def colorreset(): global icolor icolor = 0 import matplotlib.pyplot as plt xx = [[0 + 0.1*d, 1 + 0.1*d] for d in range(20)] y = [1, 0] if True: icolorz = [] plt.figure() colorz = plt.rcParams['axes.prop_cycle'].by_key()['color'] increment_me = True icolor = 0 plt.subplot(2, 1, 1) for i, x in enumerate(xx): plt.plot(x, y, colorz[icolor], linewidth=2) icolorz.append(icolor) icolor += increment_me icolor = icolor%len(colorz) if i == 5: colorpause() if i == 10: colorresume() if i &gt;=12 and not i%3: colorreset() plt.subplot(2, 1, 2) plt.plot(icolorz) plt.ylim(-0.5, 6.5) plt.title('color number used') plt.show()
linked to: http://stackoverflow.com/q/42086276
answer count: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/105540004
has comment: http://stackoverflow.com/comment/93508972
score: 2
downvote count: 0
type: UnansweredQuestion
has title: Way to "pause", "resume" and "reset" default color cycling in Matplotlib besides manually?
has comment: http://stackoverflow.com/comment/105525347
has comment: http://stackoverflow.com/comment/93521046
tagged with: colors
has comment: http://stackoverflow.com/comment/92337225
type: Question
has comment: http://stackoverflow.com/comment/92337250

http://stackoverflow.com/comment/92413161
has text: @ArnavBorborah : It is actually resulting by a `replace()` however, the logical of the solution was not provided into that duplicate.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52744208
type: Comment

http://stackoverflow.com/a/52681082
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52680071
answers question: http://stackoverflow.com/q/52680071
has body: If your JSON file is {"serverID":"498054637245693952"} Then just replace with open("configs/premium.json") as f: premium = json.load(f) with with open("configs/premium.json") as f: premium = json.load(f)['serverID'] Also, you should get rid of the def premium(bot, message): function or use a different name since it's interfering with your server ID variable name, ex.

http://stackoverflow.com/q/52646246
answer count: 1
downvote count: 0
favorite count: 0
tagged with: dask
score: 5
tagged with: python
has answer: http://stackoverflow.com/a/52650279
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52650279
has title: Truth of Delayed objects is not Supported
upvote count: 5
has body: I'm using dask to delay computation of some functions that return series in my code-base. Most operations seem to behave as expected so far - apart from my use of np.average. The function I have returns a pd.Series which I then want to compute a weighted average on. Below is a non-dask and dask version: import dask import numpy as np import pandas as pd s = pd.Series([1,2,3]) a = np.average(s, weights=s) print(a) ds = dask.delayed(lambda: s)() a = np.average(ds, weights=ds) print(a.compute()) The np.average call raises a TypeError: Truth of Delayed objects is not supported. Unsure what part of my usage is wrong here.

http://stackoverflow.com/comment/92202679
comment on: http://stackoverflow.com/a/52634607
score: 1
type: AnswerComment
has text: @George `K.repeat_elements` is used inside the model. If you want to use your own solution, you need to prepare the data **before** feeding it to the model. Either you should increase your memory size or convert image in batches and do the prediction using [`predict_on_batch`](https://keras.io/models/model/#predict_on_batch). You can also define a generator and use [`predict_generator`](https://keras.io/models/model/#predict_generator) instead. However, I will go with the solution I suggested myself because I think it is more logical to have one input layer.
type: Comment

http://stackoverflow.com/comment/92168970
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52600305
has text: Could do that @AjayShah, or potentially change the name each time, but just looking for the most efficient way as possible. Would anyone know the code to automatically change the name or move the files after they have been appended?
type: Comment

http://stackoverflow.com/q/52709762
has body: Why is the top one not working, but the bottom one doing just fine? I think it's an issue with spaces, but it looks identical. What's the problem? Broken code: month = int(input("Enter the month: ")) day = int(input("Enter the day: ")) if (month == 9): if (day &lt;= 15): print ("First half of the month") else: print ("Second half of the month") #The line with the error else: print ("Not in September") Working code: month = int(input("Enter the month: ")) day = int(input("Enter the day: ")) if (month == 9): if (day &lt;= 15): print ("First half of the month") else: print ("Second half of the month") else: print ("Not in September")
possible better answer: http://stackoverflow.com/a/52709851
has title: Line 8: SyntaxError - bad input (' ')
downvote count: 0
has comment: http://stackoverflow.com/comment/92345857
has answer: http://stackoverflow.com/a/52709851
has answer: http://stackoverflow.com/a/52709848
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92346035
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52709848
score: 1
upvote count: 1
type: Question
answer count: 2
tagged with: syntax-error

http://stackoverflow.com/q/52673574
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/92276959
has comment: http://stackoverflow.com/comment/92276910
has answer: http://stackoverflow.com/a/52673628
score: -1
tagged with: python-3.x
has body: I'm making a program that checks for a number in a CSV and then prints out the entire row. The 4th one is the number. Here is what I tried: with open('Info.csv', 'r') as csv_file if 'View C' in choice: read = csv.reader(csv_file) view = str(input("Enter Number: ")) for column in read: if view == column[3]: print(row) The csv file is structured like this: John,Smith,London,131390890 Bob,Builder,Moscow,123123132 Dab,God,LA,131390890 I want the program to be like this: Input: 123123132 Output: Bob,Builder,Moscow,123123132, It also needs to be able to do this: Input: 131390890 Output: John,Smith,London,131390890, Dab,God,LA,131390890, Thank you! Btw using Python 3...
downvote count: 1
has title: How do I search for a variable in a column and then print out all the rows that contain the number in a csv file with Python 3
has answer: http://stackoverflow.com/a/52673616
answer count: 2
upvote count: 0
type: UnansweredQuestion
favorite count: 0
type: Question

http://stackoverflow.com/q/52628669
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92190984
tagged with: python
has body: An bug that has bedeviled me a number of times is calling a function without (), and assuming that it has run when it hasn't. Here's a simple scenario: class testDoubling: def __init__(self, x): self.x = x def update(self): self.x *= 2 Now in my code I initialize: myval = testDoubling( 2 ) Then later in my code I call the following expecting it to double the stored parameter: myval.update Python happily runs without complaining, but does not update myval.x. It only updates myval.x when I call it with the parentheses: myval.update() This lurking bug in my code has caused me a good many lost hours. Surely there is some way either my IDE or python itself can warn me, or an error can be forced when forgetting the ()?
score: 0
has comment: http://stackoverflow.com/comment/94181861
has comment: http://stackoverflow.com/comment/92191994
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52628713
has answer: http://stackoverflow.com/a/52629279
has comment: http://stackoverflow.com/comment/92191057
has title: How to force an error in Python when calling a function without ()
answer count: 2
favorite count: 0

http://stackoverflow.com/comment/92323187
score: 0
type: Comment
type: QuestionComment
has text: @eyllanesc I've used the code in kivy.garden without changing anything. I don't see any reason why that black blurry lines to appear when I look at the code. Is there any reason?
comment on: http://stackoverflow.com/q/52693799

http://stackoverflow.com/comment/92240072
type: Comment
score: 1
has text: That won't perform the correct sort. Presumably `s` is a string, so for string `s` your lambda returns the difference between the index of character `s[0]` and the index of character `s[1]` as the key. If neither char is found in `input` that will give a result of zero, since both `.find` calls will return -1. And it will crash with an IndexError if `s` consists of a single char. The proper key function is given in Bakuriu's answer: `lambda s: input.find(s)`.
type: AnswerComment
comment on: http://stackoverflow.com/a/52654206

http://stackoverflow.com/q/52701748
type: Question
tagged with: debugging
has answer: http://stackoverflow.com/a/52702690
answer count: 1
downvote count: 0
has title: How to debug non-deterministic segmentation faults in a mixed Python-C++ library?
favorite count: 0
has comment: http://stackoverflow.com/comment/92330774
type: UnansweredQuestion
has body: I have the issue of a PyQt-based GUI application occasionally crashing at exit with either a segmentation fault or an error message that indicates an unhandled C++ exception was encountered. While running, there are no such issues, this problem is most likely caused by some step in the application shutdown. How can I best debug such a "mixed" scenario of Python and C++, except for actually wrapping the application launch command with gdb, or explicitly enabling core dumps and trying a "post-mortem" analysis on the resulting core file? Thank you very much! Fabian Aichele
tagged with: python
has comment: http://stackoverflow.com/comment/92330369
tagged with: c++
score: 1
upvote count: 1

http://stackoverflow.com/comment/92340763
type: Comment
type: QuestionComment
has text: I would start with the official Python documentation on [list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions).
score: 1
comment on: http://stackoverflow.com/q/52707239

http://stackoverflow.com/q/52674120
has comment: http://stackoverflow.com/comment/92277845
has answer: http://stackoverflow.com/a/52681281
type: Question
has title: How to access the id of a different slider widget?
has body: Slider: id:slider_id4 min: -90 max: 90 value: 0 step: 1 pos: root.width/2+0.3*root.width/2,0.90*root.height size_hint:0.7,0.05 canvas: PushMatrix Rotate: angle: slider_id4.value origin: 30,65 Color: rgb: [.5,1,.5] Rectangle: pos: 25+slider_id5.value,65 size: 10,25 PopMatrix Slider: id:slider_id5 min: 0 max: 50 value: 0 step: 1 pos: root.width/2+0.3*root.width/2,0.80*root.height size_hint:0.7,0.05 canvas: Color: rgb: [.5,.5,.5] Rectangle: id:r1 pos: 0+slider_id5.value,30 size: 60,20 Color: rgb: [1,.5,.5] Ellipse: pos: 15+slider_id5.value,35 angle_start: 270 angle_end: 450 size: 30,30 I am trying to access slider_id5.value in the slider widget canvas that has an id: slider_id4 but I get an error saying : The name, slider_id5 is not defined I need to access the value of slider_id5 in the slider_id4 widget (under Rectangle). Any Suggestions?
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: kivy

http://stackoverflow.com/a/52734383
answers question: http://stackoverflow.com/q/52733838
upvote count: 1
downvote count: 0
has body: The problem lies in the following line of code in your program: if(t.hour == random.randint(0,11)): Here, you are comparing t.hour (the current hour) with a randomly generated integer between 0 and 11. If t.hour lies between 0-11, the probability of this statement evaluating to true is equal to the probability of random.randint(0,11) generating the same integer, which is 1/12. Hence, chances of printing "Good Evening" are 11/12. The correct way to do this would be: if 0 &lt;= t.hour &lt;= 11: print("Good Morning") else: print("Good Evening")
type: Answer
score: 1

http://stackoverflow.com/a/52708817
type: Answer
answers question: http://stackoverflow.com/q/52708584
has body: Just using the index to slice the array and moving the window by one step. Break when the size of window is less than expected a=[1,2,3,4,5,6,7,8,9] def slicing_window(a,n): new_arr=[] if(len(a)&lt;n): return a for i in range(0,len(a)): if len(a[i:i+n])==n: new_arr.append(a[i:i+n]) else: break return new_arr slicing_window(a,3) Output: [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]] OR from toolz import sliding_window list(sliding_window(3, a))# will generate tuples If you are interested in just list from toolz import sliding_window map(list,sliding_window(3, a))
score: 0

periodicity
tag name: periodicity
tags question: http://stackoverflow.com/q/52600652
type: Tag

http://stackoverflow.com/comment/102721467
type: Comment
has text: consider `rm ../CMakeCache.txt` and rerunning. that worked for me
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52734200

http://stackoverflow.com/comment/131263444
type: AnswerComment
has text: Does this code works with multiple widgets?
type: Comment
comment on: http://stackoverflow.com/a/52673286
score: 0

http://stackoverflow.com/comment/92240249
comment on: http://stackoverflow.com/q/52654160
score: 0
type: QuestionComment
type: Comment
has text: @devssh On Windows there is no fork, which means that `multiprocessing` will spawn a new python process and import your main file. In your case this will cause a new pool to be started etc... basically a "forkbomb". This is clearly documented in the documentation for `multiprocessing`. That's why the documentation says guard the "executable code" in `if __name__ == "__main__":` since that prevents the importing of the module to re-execute it incorrectly.

http://stackoverflow.com/comment/92339671
comment on: http://stackoverflow.com/q/52695236
has text: @cricket_007: I included all import statements, This is the only error that I get.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52716992
has body: You can .annotate(..) this with a Case(..) object: Movie.objects.annotate( role=Min(Case( When(casting__actor=my_actor, then=F('casting__role')), default=None )) ) Now the Movie objects will have an attribute .role that holds the role for that actor. If there are multiple roles for the actor, it will take the lexicographically smallest one, if there is no such actor, it will take None.
score: 1
has comment: http://stackoverflow.com/comment/92360477
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92360431
has comment: http://stackoverflow.com/comment/92360489
type: Answer
answers question: http://stackoverflow.com/q/52716792
has comment: http://stackoverflow.com/comment/92360330
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52716792

http://stackoverflow.com/q/52657844
has title: Problem importing modules and functions in Python
linked to: http://stackoverflow.com/q/9916878
tagged with: python
has body: I have two files: in one of them (named myrandom) I have defined a function called spinner that would choose a random number from 1 to 6 and would return its value. In the second file, named main, I have imported the first one (as a module) and have also called the spinner function. This is the code of the file myrandom: def spinner(): import random val = random.choice([1, 2, 3, 4, 5, 6]) return val And this is the code of main: import myrandom x = spinner() print(x) My problem is that when I run main, I get the following error message: "NameError: name spinner() is not defined". I don't know why I'm getting this error, since I have other files and modules with similar characteristics that run without problems. Any idea?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52657854
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52657854
score: 0
possible better answer: http://stackoverflow.com/a/52657860
has answer: http://stackoverflow.com/a/52657860

http://stackoverflow.com/comment/92269075
comment on: http://stackoverflow.com/a/52669548
type: AnswerComment
score: 0
has text: @ Herc01, glad you got ans yourself.
type: Comment

http://stackoverflow.com/comment/92407479
type: QuestionComment
has text: wouldn't it be easier to `place` the Label instead?
comment on: http://stackoverflow.com/q/52739941
score: 0
type: Comment

http://stackoverflow.com/comment/132104173
type: Comment
comment on: http://stackoverflow.com/a/52623912
score: 0
type: AnswerComment
has text: @lxg95 you can create your own subtype for that which you should ask in seperate question.

http://stackoverflow.com/comment/121945586
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52702678
type: Comment
has text: the above cited link for Bicubic is no more functional. I found the document over here. http://anyflip.com/lxkj/dlpa

http://stackoverflow.com/comment/92123538
score: 0
comment on: http://stackoverflow.com/q/52592549
type: Comment
type: QuestionComment
has text: Sorry but I can't answer your question via comments, you need to post your raw data, your code that loads this data, what the desired result is and your attempts including any errors. SO is not a forum.

http://stackoverflow.com/q/52728368
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52728485
has comment: http://stackoverflow.com/comment/92382178
has comment: http://stackoverflow.com/comment/92553377
has answer: http://stackoverflow.com/a/52728543
accepted answer: http://stackoverflow.com/a/52728431
downvote count: 1
has answer: http://stackoverflow.com/a/52728579
has answer: http://stackoverflow.com/a/52728495
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/55134010
has answer: http://stackoverflow.com/a/53025729
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/52728498
has comment: http://stackoverflow.com/comment/92381901
has comment: http://stackoverflow.com/comment/92382166
favorite count: 0
has title: Python- Adding odd numbers in a range including the limits?
has answer: http://stackoverflow.com/a/52728431
answer count: 9
has body: I need to write a program where the user inputs 2 numbers and then it gives the sum of all odd numbers in that range plus the 2 numbers that the user entered. I've searched around a lot but haven't found anything that includes the limits. So far I have: x=int(input('Enter first number: ')) y=int(input('Enter second number: ')) def SumOdds(x,y): count=0 for i in range(x,y): if (int(i%2==1)): count=count+i print(count) SumOdds(x,y) This gives the sum of the odds, but doesn't include the limits. For example, say I put in 10 and 20. This gives me 75, but it needs to add on the 10 and 20 to make it 105. I'm sure this is a simple fix, but I'm very new to Python so any help would be appreciated. Thanks!
has answer: http://stackoverflow.com/a/58460419
tagged with: range
tagged with: python
possible better answer: http://stackoverflow.com/a/52728485

http://stackoverflow.com/q/52675224
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92279854
has title: Writing into csv files using python
score: -1
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52675260
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92279890
has body: Guys I was trying to write into a csv file using python and the code I used for it is as follows with open(csvfile,'a') as csv_file: writer = csv.writer(csv_file) writer.writerow(row) so after this when I tried to use this code with open(filename,'r') as csvfile: csvFileReader = csv.reader(csvfile) for row in csvFileReader: dates.append(int(row[0])) prices.append(float(row[1])) I get an error as IndexError: list index out of range I checked the file and found that there is an empty line created after every write that has been performed. Is that the cause of this error? If so how can I rectify it? Thanks in advance!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52675260

http://stackoverflow.com/comment/92387973
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52731355
has text: what is words value in your example

http://stackoverflow.com/comment/92397849
has text: Looks like your Qt5 is broken for some reason. Try reinstalling or switch to a different default bakcend. See my answer
comment on: http://stackoverflow.com/q/52735313
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52699872
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52699803
type: Answer
upvote count: 1
has body: You can use a generator expression with zip: pos_2D_new = tuple((x, y) for (x, _), y in zip(pos_2D, y_new)) With your sample input, pos_2D_new would become: ((2, 165), (32, 152), (73, 145), (43, 174))

http://stackoverflow.com/q/52598878
linked to: http://stackoverflow.com/q/50088548
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92133696
answer count: 1
has title: How do I optimise non-equi-joins in Spark SQL?
has comment: http://stackoverflow.com/comment/92142958
has body: I have two dataframes that I need to join together using a non-equi-join (i.e. an inequality join) that has two join predicates. One dataframe is a histogram DataFrame[bin: bigint, lower_bound: double, upper_bound: double] The other dataframe is a collection of observations DataFrame[id: bigint, observation: double] I need to determine which bin of my histogram each observation falls into, like so: observations_df.join(histogram_df, ( (observations_df.observation &gt;= histogram_df.lower_bound) &amp; (observations_df.observation &lt; histogram_df.upper_bound) ) ) Basically it is very slow and I'm looking for some suggestions as to how I can make it go quicker. Below is some sample code the demonstrates the problem. observations_df contains 100000 rows, when the number of rows in histogram_df becomes suitably large (let's say number_of_bins = 500000) then it becomes very very slow and I'm certain its because I'm doing a non-equi-join. If you run this code then play around with the value of number_of_rows, start with something low and then increase until the slow performance is noticeable from pyspark.sql.functions import lit, col, lead from pyspark.sql.types import * from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import rand from pyspark.sql import Window spark = SparkSession \ .builder \ .getOrCreate() number_of_bins = 500000 bin_width = 1.0 / number_of_bins window = Window.orderBy('bin') histogram_df = spark.range(0, number_of_bins)\ .withColumnRenamed('id', 'bin')\ .withColumn('lower_bound', 0 + lit(bin_width) * col('bin'))\ .select('bin', 'lower_bound', lead('lower_bound', 1, 1.0).over(window).alias('upper_bound')) observations_df = spark.range(0, 100000).withColumn('observation', rand()) observations_df.join(histogram_df, ( (observations_df.observation &gt;= histogram_df.lower_bound) &amp; (observations_df.observation &lt; histogram_df.upper_bound) ) ).groupBy('bin').count().head(15)
tagged with: apache-spark
upvote count: 1
tagged with: python
favorite count: 0
duplicate of: http://stackoverflow.com/q/43483576
downvote count: 0
linked to: http://stackoverflow.com/q/47824841
has comment: http://stackoverflow.com/comment/92138919
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52603294
linked to: http://stackoverflow.com/q/43483576
tagged with: apache-spark-sql

http://stackoverflow.com/a/52702400
answers question: http://stackoverflow.com/q/52702247
score: 10
upvote count: 10
downvote count: 0
type: Answer
has body: try: &gt;&gt;&gt; df.columns = ['a', 'b', 'c'] &gt;&gt;&gt; df a b c 0 1 4 7 1 2 5 8 2 3 6 9

http://stackoverflow.com/q/52685346
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/48427185
type: Question
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: apache-spark
upvote count: 1
has comment: http://stackoverflow.com/comment/92302151
has title: Unexplainable behavior with PySpark and dropping nulls
favorite count: 0
has body: I have a Spark DataFrame in PySpark that I am trying to remove the nulls from. Before, when cleaning things up during parsing, I ran a convert_to_null method on the title column that basically checks whether a string literally says "None" and if so, converts that to an actual None. That way, Spark converts it to an internal null type. Now, I'm trying to drop the rows with that null type in the title column. Here is everything I've tried to remove my nulls: new_df = df.na.drop('title') new_df = df[F.col('title').isNotNull()] new_df = df[~F.col('title').isNull()] But I always get this error at the new_df.show() call a few lines after: Py4JJavaError: An error occurred while calling o2022.showString. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 87.0 failed 1 times, most recent failure: Lost task 1.0 in stage 87.0 (TID 314, localhost, executor driver): org.apache.spark.api.python.PythonException: Traceback (most recent call last): File "/usr/local/spark/python/lib/pyspark.zip/pyspark/worker.py", line 230, in main process() File "/usr/local/spark/python/lib/pyspark.zip/pyspark/worker.py", line 225, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 324, in dump_stream self.serializer.dump_stream(self._batched(iterator), stream) File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 139, in dump_stream for obj in iterator: File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 313, in _batched for item in iterator: File "&lt;string&gt;", line 1, in &lt;lambda&gt; File "/usr/local/spark/python/lib/pyspark.zip/pyspark/worker.py", line 75, in &lt;lambda&gt; return lambda *a: f(*a) File "/usr/local/spark/python/pyspark/util.py", line 55, in wrapper return f(*args, **kwargs) File "&lt;ipython-input-16-48bc3ec1b5d9&gt;", line 5, in replace_none_with_null TypeError: 'in &lt;string&gt;' requires string as…
tagged with: python
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/92337654
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52705038
has text: i don't think ad will create any problem, BTW i see the result and nothing contains ads element/text. run this and check.. response.xpath('//*[@class="entry-inner"]/p/text()').extract()
score: 0

http://stackoverflow.com/a/52698144
has comment: http://stackoverflow.com/comment/92325027
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92323037
upvote count: 1
type: Answer
has body: This is easily solved by zipping wedstrijden with an iterator over eventresults: event_itr = iter(eventresults) result = {} for year in jaren: result[year] = dict(zip(wedstrijden, event_itr)) # result: # {'2017': {'NED': [1, 2, 3, 4], 'GER': [1, 2], 'GBR': [1, 2, 3, 4, 5, 6], 'USA': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}, # '2018': {'NED': [3, 2, 1], 'GER': [6, 5, 4, 3, 2, 1], 'GBR': [4, 5, 6, 3], 'USA': [1, 2, 3, 4, 5, 6, 7]}}
answers question: http://stackoverflow.com/q/52698078

http://stackoverflow.com/q/52707075
answer count: 1
accepted answer: http://stackoverflow.com/a/52708247
has title: Cannot align graph because multiple tag doc2vec returning more items in doctag_syn0 than there are in the training data
tagged with: python
tagged with: gensim
tagged with: nlp
type: AnsweredQuestion
tagged with: machine-learning
has body: I am training a doc2vec model with multiple tags, so it includes the typical doc "ID" tag and then it also contains a label tag "Category 1." I'm trying to graph the results such that I get the doc distribution in a 2d (using LargeVis) but am able to color different tags. My problem is that the vectors the model returns exceed the number of training observations by 5 making difficult to align the original tags with the vectors: In[1]: data.shape Out[1]: (17717,5) Training the model on 100 parameters In[2]: model.docvecs.doctag_syn0.shape Out[2]: (17722,100) I have no idea whether the 5 additional observations shift the order of the vectors or whether they're just appended to the end. I want to avoid using string tags for the doc IDs because I am preparing this code to use on a much larger dataset. I found an explanation in a google group https://groups.google.com/forum/#!topic/gensim/OdvQkwuADl0 which explained that using multiple tags per doc can result in this type of output. However, I haven't been able to find a way to avoid or correct it in any forum or documentation.
type: Question
has answer: http://stackoverflow.com/a/52708247
tagged with: doc2vec
score: 0

http://stackoverflow.com/q/52636127
has comment: http://stackoverflow.com/comment/104204441
downvote count: 0
has answer: http://stackoverflow.com/a/55517035
linked to: http://stackoverflow.com/q/46135499
has comment: http://stackoverflow.com/comment/101823511
has answer: http://stackoverflow.com/a/52649515
tagged with: tensorflow
type: Question
answer count: 2
upvote count: 6
tagged with: keras
tagged with: tensorflow-datasets
favorite count: 0
has title: How to use Keras generator with tf.data API
type: UnansweredQuestion
score: 6
tagged with: python
has body: I am trying to use the generator found in Keras preprocessing library. I wanted to experiment with this since Keras provides great functions for image augmentation. However, I am not sure if this is actually possible. Here is how I made a tf dataset from the Keras generator: def make_generator(): train_datagen = ImageDataGenerator(rescale=1. / 255) train_generator = train_datagen.flow_from_directory(train_dataset_folder,target_size=(224, 224), class_mode='categorical', batch_size=32) return train_generator train_dataset = tf.data.Dataset.from_generator(make_generator,(tf.float32, tf.float32)).shuffle(64).repeat().batch(32) Note that if you try to directly give train_generator as the argument to tf.data.Dataset.from_generator there will be an error. However, the above method doesn't produce an error. When I run it within a session to check the output from the dataset I get the following error. iterator = train_dataset.make_one_shot_iterator() next_element = iterator.get_next() sess = tf.Session() for i in range(100): sess.run(next_element) Found 1000 images belonging to 2 classes. --------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 1291 try: -> 1292 return fn(*args) 1293 except errors.OpError as e: /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata) 1276 return self._call_tf_sessionrun( -> 1277 options, feed_dict, fetch_list, target_list, run_metadata) 1278 /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata) 1366 self._session, options, feed_dict, fetch_list, target_list, -> 1367 run_metadata) 1368 InvalidArgumentError: Cannot batch tensors with different shapes in component 0. First ele…

http://stackoverflow.com/comment/92244805
has text: By changing with app.app_context(), the error still exists the same.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52621585
type: Comment

http://stackoverflow.com/comment/92120030
type: AnswerComment
has text: Thanks for the detailed answer. But I keep getting this error: TypeError: unorderable types: str() < float(). I see that my actual data has a each column list value represented with single quotes like this: ['Phone', 'Watch', 'Pen']. I guess this could be the reason. I tried some steps to remove single quotes it doesnt help probably because the values are natively string
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52591727

http://stackoverflow.com/comment/92299797
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52685966
type: AnswerComment
has text: This explanation is ambiguous, because it relies on me already understanding that the "c variable" is its own memory location pointing to another memory location.

http://stackoverflow.com/a/52728233
has body: Try this. This prints all even numbers then the sum of the odd numbers: first = int(raw_input("Input the lower integer : ")) second = int(raw_input("Input the higher integer : ")) def calc(first, second): sumOdds = 0 for i in range(first, second+1): if i % 2 == 0: print 'Even: ', i else: sumOdds += i print(sumOdds) calc(first,second)
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92382373
has comment: http://stackoverflow.com/comment/92382353
type: Answer
has comment: http://stackoverflow.com/comment/92386643
accepted answer of: http://stackoverflow.com/q/52728192
answers question: http://stackoverflow.com/q/52728192

http://stackoverflow.com/a/52693055
has comment: http://stackoverflow.com/comment/92313082
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52692609
score: 1
has body: Your code is not complete since you do not provide the input file IMAG0658.jpg. But some things can still be said and we can still answer your question. From your print statements it looks like GPSLat.values[0] and GPSLat.values[1] are both int values. But we see that GPSLat.values[2] looks like a fraction and thus is not an int value. From your error traceback we see that either GPSLat.values[1] or GPSLat.values[2] is actually an object instance. So at least one of those values prints like a numeric value but is actually an object instance. The solution to your problem is to take those apparent numeric values, which are shown in print functions and thus are accessible by the str function as well, and convert them to numeric values before further computation. Since GPSLat.values[2] does not print like an int but does print like a fraction, we can use the Fraction type in the fractions module to do an easy conversion to float. So for each value, we use str to get the numeric-looking value then convert that to an actual numeric float value. So we can do from fractions import Fraction GPSDDLat = ( float(str(GPSLat.values[0])) + float(str(GPSLat.values[1])) / 60 + float(Fraction(str(GPSLat.values[2]))) / 3600 ) But without that file I cannot do an actual check of that code.
answers question: http://stackoverflow.com/q/52692609
has comment: http://stackoverflow.com/comment/92312988
has comment: http://stackoverflow.com/comment/92313154
has comment: http://stackoverflow.com/comment/92313216
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92313642
has comment: http://stackoverflow.com/comment/92313183
upvote count: 1
type: Answer

http://stackoverflow.com/a/52599733
accepted answer of: http://stackoverflow.com/q/52599549
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52599549
type: Answer
downvote count: 0
score: 1
has body: You need to remove any escaping symbol before v and use r'\bv(?:[0-9]{1,3}\.){2}[0-9]{1,3}\b' Or, to match the whole string, r'^v(?:[0-9]{1,3}\.){2}[0-9]{1,3}$' Note that \v matches a \x0B symbol. Basically, watch out what you escape, some literal chars when escaped form a regex escape sequence and stop matching those chars literally. See Python re docs: Most of the standard escapes supported by Python string literals are also accepted by the regular expression parser: \a \b \f \n \r \t \u \U \v \x \\

http://stackoverflow.com/q/52695868
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
tagged with: django
upvote count: 1
type: Question
has body: AttributeError: Got AttributeError when attempting to get a value for field user on serializer UserKeywordSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. models.py class Keyword(models.Model): name=models.CharField(max_length=500,unique=True) image = models.ImageField(upload_to='keywords/', blank=True, null=True) mood=models.ManyToManyField(Mood,blank=True) def __str__(self): return str(self.name) class UserKeyword(models.Model): keywords=models.ManyToManyField(Keyword) count=models.IntegerField(blank=True,null=True,default=0) user=models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return str(self.id) serializer.py class KeywordsSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields ='__all__' class UserKeywordSerializer(serializers.ModelSerializer): keywords = KeywordsSerializer( read_only=True,many=True) class Meta: model = UserKeyword fields = '__all__' views.py top_keywords=UserKeyword.objects.filter(user_id=request.user.id).select_related().order_by('-count') user_serializer=UserKeywordSerializer(top_keywords).data print(user_serializer)
has answer: http://stackoverflow.com/a/52695885
score: 1
accepted answer: http://stackoverflow.com/a/52695885
has title: Serializers - Django REST framework (AttributeError: Got AttributeError when attempting to get a value for field `user` on serializer)
downvote count: 0
answer count: 1
tagged with: django-rest-framework

http://stackoverflow.com/q/52744147
has comment: http://stackoverflow.com/comment/92414316
has comment: http://stackoverflow.com/comment/92413567
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Iterate through dictionary to create a list of items inside another list
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52746998
tagged with: list
has comment: http://stackoverflow.com/comment/92414544
has body: I have a dictionary called fleet few ships. Each ship in the dictionary is longer than 1 (consists of at least two sets of coordinates, for example [[3, 1], [3, 2]] and [[2, 3], [2, 4], [2, 5]]. With the code below, I manage to get the coordinates of all ships, but somehow I cannot figure out how to make a fleet list, where each element inside is a list of lists with coordinates. For the example above, I need a result like this: [[[3, 1], [3, 2]], [[2, 3], [2, 4], [2, 5]]] I imagine another for loop is needed, but I cannot manage to integrate it properly. The problematic code is in function place_ship() num_cols = 5 # board size direction x num_rows = 4 # board size direction y empty_field = "~" fleet = { "Submarine": [3, "S"], "Patrol Boat": [2, "P"] } def place_ship(): # place ship based on orientation list_ship_coordinates = [] if ori == "v": for i in range(fleet[ship][0]): board[x + i][y] = fleet[ship][1] part_of_ship = [x + i + 1, y + 1] list_ship_coordinates.append(part_of_ship) print(list_ship_coordinates) elif ori == "h": for i in range(fleet[ship][0]): board[x][y + i] = fleet[ship][1] part_of_ship = [x + 1, y + i + 1] list_ship_coordinates.append(part_of_ship) print(list_ship_coordinates) return board def validate(): if ori == "v" and x + fleet[ship][0] &gt; num_rows: return False elif ori == "h" and y + fleet[ship][0] &gt; num_cols: return False else: if ori == "v": for i in range(fleet[ship][0]): if board[x + i][y] != empty_field: return False elif ori == "h": for i in range(fleet[ship][0]): if board[x][y + i] != empty_field: return False return True for ship in fleet: valid = False while not valid: x = randint(0, num_rows - 1) y = randint(0, num_cols - 1) o = randint(0, 1) if o == 0: ori = "v" else: ori = "h" valid = validate() board = place_ship()
type: Question
tagged with: for-loop
upvote count: 0
score: -2

http://stackoverflow.com/q/52721616
has body: What dimension should the LSTM output be? Currently I'm using return_sequences=False and model.summary() suggests that the Dense(1, activation='sigmoid') layer should have output: (None, 1) Where None is the batch size. Does it mean that my y also has to be 2 dimensional? Currently I'm using a 1d array of the shape y.shape = (None,) which seems to work fine, but I wonder if I should add a new axis to match the dimensions as: y = y[:, np.newaxis] EDIT: Below is my model summary. Essentially I'm modelling a binary classifier (0 or 1) and I am feeding batches of variable size in both batch_size and time steps. Hence the dimension of X.shape = (None, None, no_of_features). As we can see below, the output of the Dense() layer is (None, 1) where as my Y is actually (Batch_size, ) , a 1d numpy array. Should I add a new axis so that Y becomes 2d? E.g. (batch_size, 1)? I tried both, and both of them seem to work. So what's the difference? __________________________________________________________________________________________________ concatenate_8 (Concatenate) (None, None, 285) 0 numeric_input[0][0] concatenate_7[0][0] __________________________________________________________________________________________________ dropout_3 (Dropout) (None, None, 285) 0 concatenate_8[0][0] __________________________________________________________________________________________________ lstm_4 (LSTM) (None, 64) 89600 dropout_3[0][0] __________________________________________________________________________________________________ main_output (Dense) (None, 1) 65 lstm_4[0][0] ==================================================================================================
has comment: http://stackoverflow.com/comment/92369552
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/92369795
type: Question
has comment: http://stackoverflow.com/comment/92370502
tagged with: keras
tagged with: lstm
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52723992
has comment: http://stackoverflow.com/comment/92371544
has comment: http://stackoverflow.com/comment/92370346
has title: Dimensionality of the `Y` input for LSTM in Keras
accepted answer: http://stackoverflow.com/a/52723992
has comment: http://stackoverflow.com/comment/92368617
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92370310

http://stackoverflow.com/a/54278185
has body: import ast,sys input_str = sys.stdin.read() input_list = ast.literal_eval(input_str) C = input_list[0] F = input_list[1] H = input_list[2] C = set(input_list[0]) F = set(input_list[1]) H = set(input_list[2]) print(sorted(list(C &amp; F &amp; H))) print(sorted(list((C &amp; F) - (C &amp; F &amp; H)))) print(sorted(list(((C &amp; F) | (F &amp; H) | (C &amp; H)) - (C &amp; F &amp; H)))) print(sorted(list(set(range(1,21)) - (C | F | H))))
has comment: http://stackoverflow.com/comment/95378551
answers question: http://stackoverflow.com/q/52594352
type: Answer
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/a/52686956
has body: if any(item in q for item in d) :is not doing what you think it does. The issue with your if command is that you have a for loop first. The q are the individual strings that you want to check against, so item in q is actually checking that the string (as the object string) is inside one of the element of the q string (so checking one element after the other), which cannot work. I would suggest to split each tested string to keep the filename. Then for item in d is not doing what you think either. It loops one character after the other int he string as well. You may want to split the string first, so the end result could be something like: d = os.popen("""wmic process get name | findstr /v "Name 'System Idle Process' System""").read().lower().split() lists = ["opera.exe" , "chrome.exe" , "iexplore.exe" , "firefox.exe" , "microsoftedgecp.exe"] if any(item.split(os.sep)[-1] in lists for item in d) : May not be perfect, but it's a start.
type: Answer
has comment: http://stackoverflow.com/comment/92301399
answers question: http://stackoverflow.com/q/52686853
accepted answer of: http://stackoverflow.com/q/52686853
has comment: http://stackoverflow.com/comment/92301361
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/52709784
has body: pandas.read_csv uses ',' as the default delimiter. Your columns are separated by white-spaces. You can tell pandas to use white-spaces as a delimiter either by adding sep='\s+' (as you did in the commented line) or delim_whitespace=True as a keyword argument. You can find a detailed description of both arguments in the api: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52709421

http://stackoverflow.com/comment/92140853
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52603227
has text: Ok. co-incidentally my case has only three elements. Even if I give (len(array1)), it is not printing every element. Also I have used [p+1]. So if I use (len(array1)), it would give index out of range error.
score: 0

http://stackoverflow.com/comment/92333676
type: Comment
type: QuestionComment
score: 0
has text: I have up-voted your question, as debugging your code helped me in a project I am personally working on and for which I was at a dead end. I hope that my answer helps you understand where you were blocked at yourself.
comment on: http://stackoverflow.com/q/52697473

http://stackoverflow.com/comment/92196739
comment on: http://stackoverflow.com/q/52631453
has text: will your device have connection to internet at the time of demonstration ? if yes then you should add this feature whether they want to know for certain day and temp ( ask for inputs) or automatically detect day/ time and temp.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52605404
type: Answer
score: 0
has body: There's probably more computationally efficient ways of doing it, but I'd iterate through each list storing the results in a dictionary, which seems to me to be the natural way to handle this relationship in Python. exp_1 = [5,3,2,4] coeff_1 = [1,1,1,1] exp_2 = [5,3,2,1] coeff_2 = [1,1,1,1] def add_coefficient(exp1, coeff1, exp2, coeff2): exponent_coefficient_dict = dict() # Iterate through first pair of lists, storing as exp:coeff pairs. for index, exponent in enumerate(exp1): exponent_coefficient_dict[exponent] = coeff1[index] # Iterate through second pair of lists, storing or updating pairs. for index, exponent in enumerate(exp2): exponent_coefficient_dict[exponent] = exponent_coefficient_dict.get(exponent, 0) + coeff2[index] # Get a sorted list of the keys from the dictionary. combined_exp_list = sorted(exponent_coefficient_dict, reverse=True) combined_coeff_list = [] # Populate a list for the coefficients according to the order # the exponents appear in. for exponent in combined_exp_list: combined_coeff_list.append(exponent_coefficient_dict.get(exponent, 0)) return (combined_exp_list, combined_coeff_list) add_coefficient(exp_1, coeff_1, exp_2, coeff_2)
accepted answer of: http://stackoverflow.com/q/52604396
answers question: http://stackoverflow.com/q/52604396
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92145506

http://stackoverflow.com/a/52681200
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52681156
type: Answer
answers question: http://stackoverflow.com/q/52681156
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92291637
has comment: http://stackoverflow.com/comment/92290993
has body: Use pd.get_dummies as: df'female','male' = pd.get_dummies(df.gender) del df['gender'] print(df) name female male 0 jai 0 1 1 bobby 1 0 2 ram 0 1 print(pd.get_dummies(df.gender)) female male 0 0 1 1 1 0 2 0 1 EDIT : If you have multiple strings in a value then use: df = df.join(df.dep.str.get_dummies(sep=' ')) del df['dep'] print(df) design dev sales 0 0 0 1 1 1 0 0 2 0 1 0 3 1 1 0 print(df.dep.str.get_dummies(sep=' ')) design dev sales 0 0 0 1 1 1 0 0 2 0 1 0 3 1 1 0
type: AcceptedAnswer

http://stackoverflow.com/comment/92234320
type: AnswerComment
has text: Your list comprehension also prints `[None, None, None]`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52651002

http://stackoverflow.com/q/52640018
has comment: http://stackoverflow.com/comment/92249243
has body: How do I accept windows popup of Mozila firefox to save or open a file in ROBOT FRAMEWORK ?
has answer: http://stackoverflow.com/a/52658727
has comment: http://stackoverflow.com/comment/92248854
has comment: http://stackoverflow.com/comment/92224283
has comment: http://stackoverflow.com/comment/92212464
type: Question
answer count: 2
downvote count: 2
tagged with: robotframework
has comment: http://stackoverflow.com/comment/92248296
linked to: http://stackoverflow.com/q/45995869
has comment: http://stackoverflow.com/comment/92213429
score: -2
has title: Handling Windows Pop ups in Robot Framework
has comment: http://stackoverflow.com/comment/92214681
has answer: http://stackoverflow.com/a/56248406
tagged with: python
linked to: http://stackoverflow.com/q/38298162
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/92212961
type: UnansweredQuestion

http://stackoverflow.com/comment/92411636
type: Comment
has text: Just copy those 17 strings and try)) but please add to the beginning: import sqlite
type: AnswerComment
comment on: http://stackoverflow.com/a/52743356
score: 0

http://stackoverflow.com/comment/92138275
has text: Too bad, it looked interesting! I'm sure it will help other people however
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52590821
score: 0

http://stackoverflow.com/comment/92255258
has text: I don't understand the down-vote. This question satisfies all SO requirements: it's reproducible, it provides input/output/desired output. I would not necessarily up-vote it, but why the down-vote?
comment on: http://stackoverflow.com/q/52661840
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/92308819
comment on: http://stackoverflow.com/q/52690131
type: Comment
type: QuestionComment
score: 0
has text: Never ever use `yaml.load()`. If you don't know why not, you don't need it (and then you should read the documentation).

http://stackoverflow.com/comment/92205592
score: 1
type: AnswerComment
has text: Sorry, had wrong link for code I was attempting to use. Fixed it. Anyway, tried your solution but get same empty output file.
type: Comment
comment on: http://stackoverflow.com/a/52636080

http://stackoverflow.com/comment/92190564
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52626003
type: Comment
has text: What's your Ubuntu version?

http://stackoverflow.com/q/52702035
has title: dataframe combine_first does not work as well as fillna
tagged with: python
accepted answer: http://stackoverflow.com/a/52712568
has comment: http://stackoverflow.com/comment/92331137
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52702644
has answer: http://stackoverflow.com/a/52712568
type: Question
has body: the first dataframe is: data_date cookie_type dau next_dau dau_7 dau_15 0 20181006 avg(0-d) 2288 NaN NaN NaN 1 20181006 avg(e-f) 2284 NaN NaN NaN 2 20181007 avg(e-f) 2296 100 NaN NaN the second dataframe is : data_date cookie_type next_dau 0 20181006 avg(e-f) 908 1 20181006 avg(0-d) 904 how to update the first dataframe's next_dau from the second one i have tried combine_first and fillna, they seem not support multi-index: cols = ['data_date', 'cookie_type'] if (frame1 is not None and not frame1.empty): frame1.set_index(cols) print(frame1) print(next_day_dau) frame1.combine_first(next_day_dau.set_index(cols)) frame1.combine_first(dau_7.set_index(cols)) frame1.combine_first(dau_15.set_index(cols)) then i updated to: frame1.index = frame1.data_date.astype(str) + frame1.cookie_type next_day_dau.index = next_day_dau.data_date.astype(str) + next_day_dau.cookie_type dau_7.index = dau_7.data_date.astype(str) + dau_7.cookie_type dau_15.index = dau_15.data_date.astype(str) + dau_15.cookie_type """frame1.loc[next_day_dau.index, "next_dau"] = next_day_dau.next_dau frame1.loc[dau_7.index, "dau_7"] = dau_7.dau_7 frame1.loc[dau_15.index, "dau_15"] = dau_15.dau_15""" frame1.combine_first(next_day_dau) frame1.combine_first(dau_7) frame1.combine_first(dau_15) print(frame1) print(next_day_dau) loc raise a error because of next_day_dau dose not contain all the indexes in frame1 then i tried combine-first and fillna with inplace=True ,all dont work. {'data_date': {'20181007avg(0-d)': 20181007, '20181007avg(e-f)': 20181007, '20181006avg(0-d)': 20181006, '20181006avg(e-f)': 20181006}, 'cookie_type': {'20181007avg(0-d)': 'avg(0-d)', '20181007avg(e-f)': 'avg(e-f)', '20181006avg(0-d)': 'avg(0-d)', '20181006avg(e-f)': 'avg(e-f)'}, 'dau': {'20181007avg(0-d)': 2288, '20181007avg(e-f)': 2284, '20181006avg(0-d)': 2288, '20181006avg(e-f)': 2284}, 'next_dau': {'20181007avg(0-d)': nan, '20181007avg(e-f)': nan, '20181006avg(0-d)': nan, '20181006avg(e-f)': nan}, 'dau_7': {'20181007avg(0-d)': nan, '20…
has answer: http://stackoverflow.com/a/52702644
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92330984
score: 0
answer count: 2
tagged with: fillna
tagged with: pandas

http://stackoverflow.com/a/52664423
upvote count: 1
has body: np.random.randint(1, 2, size=5) returns array([1, 1, 1, 1, 1]). You cannot really compare array of length user_series with a single value 1 or 2. See https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.randint.html Note that also according to documentation high is defined as ... one above the largest (signed) integer ... so np.random.randint(1, 2, size=5) will return only 1's.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52664042
score: 1

http://stackoverflow.com/comment/92351344
has text: On which line did you receive the error?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52712796
score: 1

http://stackoverflow.com/q/52670591
tagged with: python-3.x
tagged with: tuples
has comment: http://stackoverflow.com/comment/92271537
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/92270923
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52670782
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92271270
has comment: http://stackoverflow.com/comment/92271115
has comment: http://stackoverflow.com/comment/92271345
has answer: http://stackoverflow.com/a/52670782
has comment: http://stackoverflow.com/comment/92271147
has comment: http://stackoverflow.com/comment/92271174
has comment: http://stackoverflow.com/comment/92271285
has comment: http://stackoverflow.com/comment/92271084
has comment: http://stackoverflow.com/comment/92271203
has comment: http://stackoverflow.com/comment/92271071
has title: Python 3: How to compare two tuples and find similar values?
has body: I have two dictionaries: (1)Inventory and (2)Items Under these dictionaries are tuples which are added using user's input. dict_inventory = {('fruits', ['apple','mango']) dict_items = {('apple', [3, 5]) ('mango', [4, 6])} How do I compare the two and to match similar values which are apple and mango My code is not printing anything: for itemA in dict_inventory.values(): for itemB in dict_items.keys(): if itemA == itemB: print("Match!")
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92270942
favorite count: 0

http://stackoverflow.com/q/52649715
type: Question
tagged with: pybind11
tagged with: linker-errors
has body: I'm trying to integrate pybind11 in my project with CMake. My structure is as follows: foo ├───pybind11 ├───src └─── __init.py__ (empty) │ └─── mymodule.cpp └─── __init.py__ (empty) └───CMakeLists.txt src ├───core ├───bar ├───baz └───CMakeLists.txt setup.py CMakeLists.txt In my foo project I need to link libraries in the core, bar and baz projects (that have all their own makefile), thus I've set up relative imports in my foo/CmakeLists.txt file, aside from the call to pybind11 obviously: add_subdirectory(pybind11) pybind11_add_module(foo src/mymodule.cpp) set(CORE "../src/core") ... target_link_libraries(foo PUBLIC core bar baz ) target_include_directories(pyceam PUBLIC ${core}/include ... ) inside I've copied the setup.py from the official CMake example, the only line I've modified is in the setup call: ext_modules=[CMakeExtension('foo', sourcedir='.')], This installs correctly, but it does produce an empty module: >>> import foo >>> dir(foo) ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__'] I figured that the problem was the sourcedir parameter, so I've tried two things but none of them worked: move setup.py inside foo and call with sourcedir='..' leave setup.py in the root dir and call with sourcedir='./foo' and in both cases I get: 3>LINK : fatal error LNK1181: cannot open input file 'core.lib' Can anybody please point me in the right direction in order to solve this issue?
downvote count: 0
favorite count: 0
has title: pybind11 problems with directory structure
tagged with: python
tagged with: cmake
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: pip
upvote count: 1

http://stackoverflow.com/q/52709482
possible better answer: http://stackoverflow.com/a/52709618
has answer: http://stackoverflow.com/a/52709770
accepted answer: http://stackoverflow.com/a/52709770
downvote count: 1
type: Question
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/92345173
score: -1
has comment: http://stackoverflow.com/comment/92345122
has comment: http://stackoverflow.com/comment/92345197
has answer: http://stackoverflow.com/a/52709618
favorite count: 0
has body: I am trying to create a loop to download data from a website between 2014 and 2017. I've created a simple loop that should download data from this link, but for 2015, 2016, and 2017. The only text that needs to change in the link is the year: https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h2014.txt.gz&amp;dir=data/historical/stdmet/ Revised: import urllib core = 'https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h' year = 2014 end = '.txt.gz&amp;dir=data/historical/stdmet/' for i in range(0,3): year += 1 year_fixed = str(year) urllib.urlretrieve(core+year_fixed+end) There error that I receive is at the first website address: AttributeError: module 'urllib' has no attribute 'urlretrieve' For some reason it is not importing any data from 2014 - 2017. Is there a better way about creating this? Any help would be appreciated.
has comment: http://stackoverflow.com/comment/92345206
has comment: http://stackoverflow.com/comment/92345698
tagged with: python
has title: Create a Loop to import Data via Multiple URLs
type: AnsweredQuestion

http://stackoverflow.com/comment/92307283
comment on: http://stackoverflow.com/a/52672358
type: Comment
has text: And when I tried it with random data on Anaconda Prompt, it gives the error: `Traceback (most recent call last): File "asd.py", line 30, in <module> print(maxisland_start_len(a, 5)) File "asd.py", line 19, in maxisland_start_len scale = island_lens.max()+1 File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\_methods.py", line 26, in _amax return umr_maximum(a, axis, None, out, keepdims) ValueError: zero-size array to reduction operation maximum which has no identity`
type: AnswerComment
score: 0

http://stackoverflow.com/q/52689260
accepted answer: http://stackoverflow.com/a/52689679
type: AnsweredQuestion
tagged with: conditional-statements
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92306053
has title: how can I calculate new column based on pandas conditions of multiple previous values
tagged with: dataframe
has body: I have the following dataframe. How can I create a new column based on the following: if, for example, the row of 19:24 has a diff &lt; .1 AND the row of 19:21 has a diff of &lt; .1 then create new column and set row equal to say 1 I know how I can do these with if statements, but i'm stuck on trying to use a pandas (more efficient) solution for this. open high low close diff TimeStamp 2018-10-05 19:00:00 6637.90 6645.06 6637.17 6643.52 -0.057705 2018-10-05 19:03:00 6643.52 6650.00 6641.00 6649.99 0.002710 2018-10-05 19:06:00 6648.91 6650.00 6640.82 6642.85 -0.017769 2018-10-05 19:09:00 6642.85 6646.47 6642.00 6646.20 0.000000 2018-10-05 19:12:00 6646.20 6646.21 6642.00 6642.40 0.085065 2018-10-05 19:15:00 6641.00 6641.84 6636.35 6638.54 -0.024863 2018-10-05 19:18:00 6639.26 6643.38 6638.00 6640.00 -0.067340 2018-10-05 19:21:00 6642.49 6643.82 6642.47 6643.63 0.104931 2018-10-05 19:24:00 6643.78 6645.31 6635.50 6640.02 -0.031497
has answer: http://stackoverflow.com/a/52689679
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92305537
upvote count: 1
tagged with: python

http://stackoverflow.com/q/52741065
type: Question
has title: string concatenation with nested ternary operator ignores the string
has comment: http://stackoverflow.com/comment/92406905
score: 0
has answer: http://stackoverflow.com/a/52741193
answer count: 1
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92407016
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52741193
has body: I found differences between the following two statements. message = "a is " + "greater than" if a &gt; 10 else "less than" if a &lt;10 else "equal to" + " 10" and message = "a is " + ("greater than" if a &gt; 10 else ("less than" if a &lt;10 else "equal to")) + " 10" Could someone explain what is happening here

http://stackoverflow.com/q/52676000
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52676096
tagged with: django
type: AnsweredQuestion
has body: Here is the code I'm currently using to test whether my website is deployed locally, on staging, or production: def get_base_url(request=None): BASE_URL = request.META.get('HTTP_HOST') if request else settings.STATIC_SITE_URL if not BASE_URL.startswith('http'): BASE_URL = 'http://' + BASE_URL # such as "localhost:8000" return BASE_URL And to do something like send a link for a password reset, I would do: BASE_URL = get_base_url(request) PATH = BASE_URL.rstrip('/') + reverse('logged_in') Is there a cleaner way to do this? I tried a few others ways but this seems to return the most correct and consistent result.
type: Question
has title: Best way to construct a url in django
score: 0
accepted answer: http://stackoverflow.com/a/52676096
answer count: 1

http://stackoverflow.com/comment/92131422
has text: No this is part of the dataset. But `class` is `0` for the entire dataset.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52598298
score: 0

http://stackoverflow.com/q/52703703
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52704220
has body: I want to do transfer learning with INCEPTION_V4 model as feature extractor and downloaded the code and checkpoint file from GitHub repository of Tensorflow Then I added my own layer for classification in 5 classes. But during model restore using tf.train.Saver, it showing error that it can not find variable values for my layer that I added. To solve this, I created two separate graphs, one for loading pre-trained model and one for my classification layers. But I can't pass output of one graph as input to the second graph. Can you suggest any other way to do transfer learning or solve the problem
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52704220
tagged with: python
type: AnsweredQuestion
has title: How to pass output of one graph as input to another graph in tensorflow

http://stackoverflow.com/comment/92225913
comment on: http://stackoverflow.com/a/52646252
type: AnswerComment
score: 0
type: Comment
has text: The [tutorials mentioned in the docs](http://pandas.pydata.org/pandas-docs/stable/tutorials.html) are a good starting point.

http://stackoverflow.com/q/52649030
has body: I have a sizable dataframe (100GB) in PySpark that I want to split into a training, test and validation set. Here is the kicker, I have done it before where it work but this time around trying it, the dataframe it returned had all its values changed from the actual values to either 1 or 0. The only thing that has changed from working to not working is, that I removed two string columns. When the column containing string is in the dataframe then the code seems to work as intended, ie., does not change the values of the dataframe. I am running on AWS EMR PySpark in Jupyter notebook. dataframe.show() yields -+--------------------+----+--------------------+--------------------+----+--------------------+----+--------------------+----+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+-----+--------------------+--------------------+-----+--------------------+-------------------+-----+ |c_3| c_4| c_5| c_6| c_7| c_8| c_9| c_10| c_11| c_12| c_13| c_14| c_15| c_16| c_17| c_18| c_19| c_20| c_21| c_22| c_23| c_24| c_25| c_26| c_27| c_28| c_29| c_30| c_31| c_32| c_33| c_34| c_35| c_36| c_37| c_38|c_39|c_40|c_41|c_42|c_43|c_44|c_45|c_46|c_47|c_48|c_49| c_50| c_51| c_52| c_53| c_54| c_55| c_56| c_57| c_58| c_59| c_60| c_61| c_62| c_63| c_64| c_65| c_66| c_67| c_68| c_69| c_70| c_71| c_72| c_73| c_74|c_75|c_76| c_77|c_78|c_79| c_80| c_81|c_82|c_83|c_84| c_85| c_86|c_87| c_88| c_89|c_90| c_91|c_92| c_93|c_94| c_95| c_96| c_97| c_98| c_99| c_100| c_101|c_102| c_103| c_104|c_105| c_106| c_107|c_108| +---+------+-----+-----+----+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+------------…
type: Question
score: 3
tagged with: pyspark
has answer: http://stackoverflow.com/a/64938224
answer count: 1
favorite count: 0
upvote count: 3
tagged with: apache-spark
tagged with: amazon-emr
tagged with: python
has title: randomSplit pyspark Changes the values of the dataframe
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52743399
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92413839
has title: jupyter notebook not opening up in anaconda prompt
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92412833
has body: I wanted to activate my environment and change the directory and then launch notebook. But it shows me this error (tensorflow) C:\Users\anesh&gt;jupyter-notebook Unable to create process using 'C:\Users\anesh\Anaconda3\envs\tensorflow\python.exe C:\Users\anesh\Anaconda3\envs\tensorflow\Scripts\jupyter-notebook-script.py ' I tried updating anaconda navigator but still does not work. Can anyone please give me a solution for this?
tagged with: anaconda
answer count: 0

http://stackoverflow.com/comment/92318936
comment on: http://stackoverflow.com/a/52685464
has text: you need the the nubers only from a particular format of string right ?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52727036
answer count: 3
accepted answer: http://stackoverflow.com/a/52727098
downvote count: 0
has answer: http://stackoverflow.com/a/52727377
score: 1
has title: How to consider two columns values in txt file as key, value and write them into a txt file?
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has body: I have a text file with tab delimiter like this: id name age sex Basis Salary 2345 john 23 M Monthly 6000 2345 john 23 M Yearly 72000 4356 mary 26 F Perday 225 4356 mary 26 F Monthly 7000 Take id as key, I need combine the Basis and Salary column values to be the columns in the resultant file as below. Note: If Perday or Monthly or yearly does not have any values then we should give it as "' '". id Name age sex PerDay Monthly Yearly 2345 john 23 M ' ' 6000 72000 4356 mary 26 F 225 7000 ' ' How do we do this in python way?
possible better answer: http://stackoverflow.com/a/52727148
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52727148
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52727098

http://stackoverflow.com/q/52730645
has comment: http://stackoverflow.com/comment/92387521
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92388396
has answer: http://stackoverflow.com/a/52733531
has body: I'm working on a multi-class classification problem with Keras 2.1.3 and a Tensorflow backend. I have two numpy arrays, x and y and I'm using tf.data.Dataset like this: dataset = tf.data.Dataset.from_tensor_slices(({"sequence": x}, y)) dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(self.batch_size)) dataset = dataset.repeat() xt, yt = dataset.make_one_shot_iterator().get_next() Then I make my Keras model (omitted for brevity), compile, and fit: model.compile( loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'], ) model.fit(xt, yt, steps_per_epoch=100, epochs=10) This works perfectly well. But when I add in callbacks, I run into issues. Specifically, if I do this: callbacks = [ tf.keras.callbacks.ModelCheckpoint("model_{epoch:04d}_{val_acc:.4f}.h5", monitor='val_acc', verbose=1, save_best_only=True, mode='max'), tf.keras.callbacks.TensorBoard(os.path.join('.', 'logs')), tf.keras.callbacks.EarlyStopping(monitor='val_acc', patience=5, min_delta=0, mode='max') ] model.fit(xt, yt, steps_per_epoch=10, epochs=100, callbacks=callbacks) I get: KeyError: 'val_acc' Also, if I include validation_split=0.1 in my model.fit(...) call, I'm told: ValueError: If your data is in the form of symbolic tensors, you cannot use validation_split.` What is the normal way to use callbacks and validation splits with tf.data.Dataset (tensors)? Thanks!
tagged with: tensorflow
possible better answer: http://stackoverflow.com/a/52731695
type: Question
accepted answer: http://stackoverflow.com/a/52733531
has comment: http://stackoverflow.com/comment/92387501
has comment: http://stackoverflow.com/comment/92387902
has answer: http://stackoverflow.com/a/52731695
has comment: http://stackoverflow.com/comment/92388254
has comment: http://stackoverflow.com/comment/92391762
has comment: http://stackoverflow.com/comment/92388212
has comment: http://stackoverflow.com/comment/92388199
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92389649
has comment: http://stackoverflow.com/comment/92387423
has title: Keras: Callbacks Requiring Validation Split?
has comment: http://stackoverflow.com/comment/92388469
tagged with: keras
tagged with: python

http://stackoverflow.com/a/52670272
answers question: http://stackoverflow.com/q/52666845
has comment: http://stackoverflow.com/comment/92581552
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92365298
has body: Here is an example of using scipy's differential_evolution genetic algorithm to fit a single data set to two different overlapping straight lines, and also automatically find the breakpoint to switch from one model to another. The scipy implementation of Differential Evolution uses the Latin Hypercube algorithm to ensure a thorough search of parameter space, which requires bounds within which to search - in this example, those bounds are taken from the data max and min values. The example completes the fitting with a call to curve_fit() without passing any bounds just in case the optimal parameters are outside the bounds used for the genetic algorithm. import numpy, scipy, matplotlib import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.optimize import differential_evolution import warnings xData = numpy.array([19.1647, 18.0189, 16.9550, 15.7683, 14.7044, 13.6269, 12.6040, 11.4309, 10.2987, 9.23465, 8.18440, 7.89789, 7.62498, 7.36571, 7.01106, 6.71094, 6.46548, 6.27436, 6.16543, 6.05569, 5.91904, 5.78247, 5.53661, 4.85425, 4.29468, 3.74888, 3.16206, 2.58882, 1.93371, 1.52426, 1.14211, 0.719035, 0.377708, 0.0226971, -0.223181, -0.537231, -0.878491, -1.27484, -1.45266, -1.57583, -1.61717]) yData = numpy.array([0.644557, 0.641059, 0.637555, 0.634059, 0.634135, 0.631825, 0.631899, 0.627209, 0.622516, 0.617818, 0.616103, 0.613736, 0.610175, 0.606613, 0.605445, 0.603676, 0.604887, 0.600127, 0.604909, 0.588207, 0.581056, 0.576292, 0.566761, 0.555472, 0.545367, 0.538842, 0.529336, 0.518635, 0.506747, 0.499018, 0.491885, 0.484754, 0.475230, 0.464514, 0.454387, 0.444861, 0.437128, 0.415076, 0.401363, 0.390034, 0.378698]) def func(xArray, breakpoint, slopeA, offsetA, slopeB, offsetB): returnArray = [] for x in xArray: if x &lt; breakpoint: returnArray.append(slopeA * x + offsetA) else: returnArray.append(slopeB * x + offsetB) return returnArray # function for genetic algorithm to minimize (sum of squared error) def sumOfSquaredError(parameterTuple): w…
has comment: http://stackoverflow.com/comment/92366534
type: Answer
has comment: http://stackoverflow.com/comment/92364776
has comment: http://stackoverflow.com/comment/92583520
has comment: http://stackoverflow.com/comment/92369308
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52666845

http://stackoverflow.com/q/52621406
type: Question
tagged with: boto
has title: App crashes on launch when compiled with py2app and boto3 is included
has body: I created a complex app that uses boto3. It works fine when run from the command line. But when I try to compile it with py2app the application file is created, but it crashes on launch. I simplified it down to 2 files and found that it crashes when boto3 is included but runs fine when boto3 is not included. setup.py import sys from setuptools import setup APP = ['hello.py'] OPTIONS = {'iconfile':'img/icon.icns',} setup( app = APP, options = {'py2app': OPTIONS}, setup_requires = ['py2app'], ) hello.py from tkinter import * import boto3 root = Tk() w = Label(root, text="Hello, world!") w.pack() root.mainloop() I am using the latest of everything, python 3.7 on MacOS 10.14 and on 10.13. I use the command line: python3 setup.py py2app When I compile including boto3 I get these errors from py2app. I can't find a way to install these modules with pip. Modules not found (unconditional imports): * OpenSSL (botocore.vendored.requests.packages.urllib3.contrib.pyopenssl, urllib3.contrib.pyopenssl) * OpenSSL.SSL (urllib3.contrib.pyopenssl) * Queue (botocore.vendored.requests.packages.urllib3.connectionpool) * Queue.Empty (urllib3.util.queue) * Queue.Full (urllib3.util.queue) * Queue.LifoQueue (urllib3.util.queue) * StringIO.StringIO (botocore.vendored.requests.packages.urllib3.packages.six, botocore.vendored.six, pkg_resources._vendor.six, six, urllib3.packages.six) * _abcoll (botocore.vendored.requests.packages.urllib3.packages.ordered_dict, urllib3.packages.ordered_dict) * backports.ssl_match_hostname (botocore.vendored.requests.packages.urllib3.packages.ssl_match_hostname, urllib3.packages.ssl_match_hostname) * botocore.vendored.six.moves (botocore.httpsession, botocore.vendored.six.moves.urllib.request) [module alias] * botocore.vendored.six.moves.http_client (botocore.vendored.six.moves.urllib, botocore.vendored.six.moves.urllib_parse) [module alias] * botocore.vendored.six.moves.urllib (botocore.utils) [module alias] * botocore.vendored.six.moves.urllib.request (botocore…
score: 1
answer count: 1
downvote count: 0
tagged with: boto3
tagged with: python
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52731088
type: UnansweredQuestion
upvote count: 1
tagged with: py2app

http://stackoverflow.com/comment/92294161
type: QuestionComment
comment on: http://stackoverflow.com/q/52682986
score: 0
type: Comment
has text: Why do you try to write this code? Is it a school assignment? It would probably be better to use one of the two formats as your base format and then convert from the other to the base, before testing (most likely as a separate function). ALso, you should split reading in the angle, since it is given in a custom format, and checking if it is in a valid range. Finally, when checking for a valid range, you could use the `and` keyword to test both lower and upper limit in the same `if` statement.

http://stackoverflow.com/a/52765915
answers question: http://stackoverflow.com/q/52733761
has body: I have fixed the issue by using pip install keras instead of conda install -c anaconda keras. By using pip I am only installing keras, and not dependencies that Anaconda includes with it.
score: 0
type: Answer

http://stackoverflow.com/a/52670136
answers question: http://stackoverflow.com/q/52670057
has body: You can use prefetch_related for this. See docs: You want to use performance optimization techniques like deferred fields: queryset = Pizza.objects.only('name') restaurants = Restaurant.objects.prefetch_related(Prefetch('best_pizza', queryset=queryset)) In your case you can do something like this: from django.db.models import Prefetch queryset = A.objects.only('text') b_list = B.objects.prefetch_related(Prefetch('a', queryset=queryset))
score: 0
has comment: http://stackoverflow.com/comment/92270234
has comment: http://stackoverflow.com/comment/92270194
type: Answer
has comment: http://stackoverflow.com/comment/92270287

http://stackoverflow.com/q/52740125
has title: Python pandas return value from other column
downvote count: 0
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52740739
tagged with: pandas
has answer: http://stackoverflow.com/a/52740739
has answer: http://stackoverflow.com/a/52740443
accepted answer: http://stackoverflow.com/a/52740183
answer count: 4
favorite count: 0
has body: I have a file "specieslist.txt" which contain the following information: Bacillus,genus Borrelia,genus Burkholderia,genus Campylobacter,genus Now, I want python to look for a variable in the first column (in this example "Campylobacter") and return the value of the second ("genus"). I wrote the following code import csv import pandas as pd species_import = 'Campylobacter' df = pd.read_csv('specieslist.txt', header=None, names = ['species', 'level'] ) input = df.loc[df['species'] == species_import] print (input['level']) However, my code return too much, while I am only want "genus" 3 genus Name: level, dtype: object
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52740602
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52740183

specifications
type: Tag
tags question: http://stackoverflow.com/q/52617549
tag name: specifications

http://stackoverflow.com/comment/92176731
comment on: http://stackoverflow.com/a/52621353
type: Comment
score: 0
type: AnswerComment
has text: That is exactly what I wanted. Works like a charm! That ".format(exp,link)" also does the job. Many thanks, Albin Paul. M

http://stackoverflow.com/comment/92312848
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52692979
has text: Well, CPython >= 3.6 actually uses an ordered dictionary implementation that I believe will store DictEntry objects (which are just structs that contain pointers to the hash value, the key and the value) in contigous arrays, but again, implementation details... https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6

http://stackoverflow.com/q/52656156
has body: Has anyone integrated these 2 technologies successfully? I want to expose gRPC using Django REST. Is that possible? If so, are there any good examples out there? Any help would be appreciated. Thanks.
has answer: http://stackoverflow.com/a/55874475
accepted answer: http://stackoverflow.com/a/55874475
type: Question
has comment: http://stackoverflow.com/comment/92244035
upvote count: 6
has answer: http://stackoverflow.com/a/62014312
answer count: 2
favorite count: 0
tagged with: rest
has title: Django REST with gRPC
score: 6
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/62014312
type: AnsweredQuestion
downvote count: 0
tagged with: grpc
has comment: http://stackoverflow.com/comment/92243515
tagged with: integration

calibration
tag name: calibration
tags question: http://stackoverflow.com/q/52663062
type: Tag

http://stackoverflow.com/comment/92320803
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52652616
has text: @BryanOakley I have been trying to develop the MCV example to replicate issue but could not either. Arrived at the same finding as you. I will continue to work from the MCV to debug this issue and keep you posted. From your experience, any clues on possible factors causing such an issue? Cheers.

http://stackoverflow.com/q/52597659
tagged with: lambda
answer count: 0
has title: Using python lambda function map when adding elements to a set
type: UnansweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92130003
score: 1
has body: I try to run lst = ['ab','cd','cdc','cd','ab','abcd'] g = set() list(map(lambda x:g.add(x),lst)) Then the set g contains correct elements &gt;&gt;&gt;print(g) {'abcd', 'ab', 'cdc', 'cd'} But if I remove the list conversion lst = ['ab','cd','cdc','cd','ab','abcd'] g = set() map(lambda x:g.add(x),lst) Then g is empty &gt;&gt;&gt;print(g) set() Why does this happen
has comment: http://stackoverflow.com/comment/92130097
has comment: http://stackoverflow.com/comment/92130039
downvote count: 0
linked to: http://stackoverflow.com/q/51671132
favorite count: 0
duplicate of: http://stackoverflow.com/q/31768884
duplicate of: http://stackoverflow.com/q/51671132
tagged with: python

http://stackoverflow.com/q/52722001
has answer: http://stackoverflow.com/a/52722030
tagged with: python
type: AnsweredQuestion
tagged with: list
has title: Python: iterating over a list range without duplicating it
accepted answer: http://stackoverflow.com/a/52722030
type: Question
tagged with: indexing
linked to: http://stackoverflow.com/q/5234090
has body: Suppose that I have the list list_1 and that I want to iterate over its elements from indices i to (j - 1), where j &gt; i. My options, as I know them are: Option 1: Constructing a whole new list for element in list_1[i:j]: # do something Option 2: Iterating over the indices themselves for index in range(i, j): element = list_1[index] # do something Both options are not desirable. The first option is not desirable because it involves construction of a new list. The second option is not desirable especially in terms of readability, as its iteration is over the indices, rather than over the list elements. Is there a built-in generator function that iterates over the elements in a given range?
has comment: http://stackoverflow.com/comment/92370635
score: 0
tagged with: iterator
duplicate of: http://stackoverflow.com/q/8671280
answer count: 1

http://stackoverflow.com/q/52703880
has comment: http://stackoverflow.com/comment/92334349
has title: How to remove area of interest from the background of an image?
downvote count: 2
tagged with: python
tagged with: opencv
type: AnsweredQuestion
tagged with: image-processing
type: Question
upvote count: 2
has body: I'm starting to work with image processing in pattern recognition, and I need to identify the colors of fur spots. With this, I need to remove possible noises from these images, such as hairs, and then work on only the skin spot in order to identify their colors. As a result, plot the colors in a 3D chart.
has comment: http://stackoverflow.com/comment/92334361
has answer: http://stackoverflow.com/a/52706777
has comment: http://stackoverflow.com/comment/92335817
accepted answer: http://stackoverflow.com/a/52706777
score: 0
has comment: http://stackoverflow.com/comment/92334442
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92406970
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52739544
has text: not sure if it makes a difference, but I import as follows: wtforms import DateField , not wtforms.fields import DateField. As Sarthak also points out actually.

http://stackoverflow.com/q/52683975
has answer: http://stackoverflow.com/a/52684937
has title: How to loop inside a dictionary which has values as arrays
answer count: 3
has body: I want to loop inside a dictionary that has arrays as values and get each element of the array. How do I do that? I tried this but it didn't work: array = {'Secretary' : [0,1,2,3,4] , 'Admin' : [0,2,3,4,1]} for key,value in array.items(): for v in value: print(v[count]) count = count + 1
has comment: http://stackoverflow.com/comment/92295862
downvote count: 0
possible better answer: http://stackoverflow.com/a/52684061
has answer: http://stackoverflow.com/a/52684061
favorite count: 0
has answer: http://stackoverflow.com/a/52685136
has comment: http://stackoverflow.com/comment/92295860
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/92295887
accepted answer: http://stackoverflow.com/a/52685136
has comment: http://stackoverflow.com/comment/92295879
has comment: http://stackoverflow.com/comment/92295872
type: Question

http://stackoverflow.com/q/52670717
has answer: http://stackoverflow.com/a/52670959
downvote count: 0
has body: I Have to loop through data of the query set in django and put the data into an array without specifying the model name. My Django view: permissions = Permission.objects.all().order_by('perm_label') arrayData = [] for type in permissions: for value in type: arrayData.append(value) This is giving me error: Permission' object is not iterable
possible better answer: http://stackoverflow.com/a/75508137
has comment: http://stackoverflow.com/comment/92271312
favorite count: 0
has answer: http://stackoverflow.com/a/75508137
has comment: http://stackoverflow.com/comment/92271149
accepted answer: http://stackoverflow.com/a/52670959
has comment: http://stackoverflow.com/comment/92271228
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92271691
has comment: http://stackoverflow.com/comment/92271348
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/92271666
has comment: http://stackoverflow.com/comment/92271435
has comment: http://stackoverflow.com/comment/92271251
has title: how to loop through django queryset data and set the values in an array not a dictionnary
type: Question
has comment: http://stackoverflow.com/comment/92271237
answer count: 2

http://stackoverflow.com/a/52744587
type: Answer
answers question: http://stackoverflow.com/q/52614117
has body: You can use np.where with multiple conditional statements. If you have the original dataframe you can execute the following code import numpy as np df['value'] = np.where((df['Color'] == 'Blue') &amp; (df['Age'] == 28) &amp; (df['City'] == 'Atl'), 1, 0) to yield Color Name Age City Value Blue Bob 28 Atl 1 Green Bob 27 Chi 0 Blue Sam 28 Atl 1 Obviously, you can change the conditions as needed/wanted or even create additional columns using the same technique.
score: 0

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/52690529

http://stackoverflow.com/q/52722840
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92392210
has comment: http://stackoverflow.com/comment/92370925
has comment: http://stackoverflow.com/comment/92370976
type: Question
has body: This is my models: class Journal(models.Model): Start_Date = models.DateField(default=datetime.date(2018,4,1),blank=False) End_Date = models.DateField(default=datetime.date(2019,3,31),blank=False) Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) I want to filter the journal objects within the "Start_Date" and "End_Date" of the journal model... I mean to say The "Date" in journal must be between the "Start_Date" and "End_Date" of journal... This might me a stupid question to ask...But, as I am learning django, its not easy for me... Can anyone tell me how to do this??? Thank you in advance
tagged with: python
has answer: http://stackoverflow.com/a/52723003
score: 0
has title: How to perform reverse relation in django?
tagged with: django
has comment: http://stackoverflow.com/comment/92371030
answer count: 1
has comment: http://stackoverflow.com/comment/92371426
has comment: http://stackoverflow.com/comment/92371094
has comment: http://stackoverflow.com/comment/92371246
tagged with: django-models
accepted answer: http://stackoverflow.com/a/52723003

http://stackoverflow.com/comment/92218263
type: QuestionComment
comment on: http://stackoverflow.com/q/52640386
has text: @RadosławGanczarek I dont get it... but how do i not let it show in the console...
score: 0
type: Comment

http://stackoverflow.com/comment/92354933
type: Comment
comment on: http://stackoverflow.com/q/52702246
type: QuestionComment
score: 0
has text: @BryanOakley do you have a solution?

http://stackoverflow.com/comment/92271631
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52670879
type: Comment
has text: that's probably because `2148000000 > 2**31`

http://stackoverflow.com/q/52694220
tagged with: numpy
tagged with: random
answer count: 1
downvote count: 0
has title: Object to deep for desired array, numpy random choice
tagged with: pandas
has comment: http://stackoverflow.com/comment/92315152
has answer: http://stackoverflow.com/a/52695289
tagged with: python
favorite count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: excel
has body: This is the code that I've been using to generate a random weighted choice from a baseball game simulator that I've been working on as my first python project. elements = ['1b', '2b', '3b', 'hr', 'bb', 'k', 'out'] if order_pos_away == 1: weights = ab1 if order_pos_away == 2: weights = ab2 if order_pos_away == 3: weights = ab3 if order_pos_away == 4: weights = ab4 if order_pos_away == 5: weights = ab5 if order_pos_away == 6: weights = ab6 if order_pos_away == 7: weights = ab7 if order_pos_away == 8: weights = ab8 if order_pos_away == 9: weights = ab9 from numpy.random import choice c = choice(elements, p=weights) Each time the loop runs through order_pos_away is increased by 1 so it will take the next batter's list of probabilities that add up to exactly 1. When the list probabilities are entered manually I have no issues. However, when I try to import them from the excel sheet where they are stored I get the error: ValueError: object too deep for desired array I've tried multiple ways of getting the excel data into python (read_csv, xlrd, numpy, pandas). Regardless of what I try, I always end up with the same error. I've found no solution for this as much as I've searched and have had difficulty even finding a good explanation of what is happening when I get this error.
type: Question
has comment: http://stackoverflow.com/comment/92316760
score: 3

http://stackoverflow.com/comment/92426995
type: QuestionComment
has text: @kvish: Clarification: I train for a maximum of 100 epochs. I use keras early stopping callbacks so the actual training epochs are typically < 100.
score: 0
comment on: http://stackoverflow.com/q/52733031
type: Comment

http://stackoverflow.com/q/52713401
favorite count: 0
tagged with: windows
tagged with: python
has title: Best practice for an infinite loop Python script that runs on Windows as a Service
tagged with: service
accepted answer: http://stackoverflow.com/a/52713941
upvote count: 2
score: 2
type: AnsweredQuestion
tagged with: loops
type: Question
has body: I have a python script that reads data from an OPCDA server and then push it to InfluxDB. So basically it connects to the OPCDA using the OpenOPC library and to InfluxDB using the InfluxDB Python client and then starts an infinite while loop that runs every 5 seconds to read and push data to the database. I have installed the script as a Service using NSSM. What is the best practice to ensure that the script is running 24/7 ? How to avoid crashes ? Should i daemonize the script ? Thank you in advance, Bnjroos
has answer: http://stackoverflow.com/a/52713941
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52653755
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52653694
type: Answer
answers question: http://stackoverflow.com/q/52653694
has comment: http://stackoverflow.com/comment/92239604
score: 4
upvote count: 4
has body: 1. Here's one: df.groupby(by = ['a', 'b', 'c']).size().unstack(fill_value=0).reset_index() Output: c a b 5 6 7 8 9 0 1 0 2 0 0 0 0 1 1 1 1 0 0 1 0 2 2 0 0 0 0 0 2 3 2 1 0 2 0 0 0 4 3 0 0 0 1 1 0 5 3 1 0 0 0 0 2 2. Here's another way: pd.crosstab([df.a,df.b], df.c).reset_index() Output: c a b 5 6 7 8 9 0 1 0 2 0 0 0 0 1 1 1 1 0 0 1 0 2 2 0 0 0 0 0 2 3 2 1 0 2 0 0 0 4 3 0 0 0 1 1 0 5 3 1 0 0 0 0 2

http://stackoverflow.com/comment/92248457
has text: Thank you @Vikas! Return should be out of the loop. Got it.
score: 1
comment on: http://stackoverflow.com/a/52658961
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52699454
has body: By default Robot Framework treat all scalar variables as strings, so your custom keyword is comparing string "91" with string "10000". There are two options: Inside your keyword convert arguments to desired data types Explicitly pass numbers to your keyword. To do so use ${} syntax i.e ${91}
upvote count: 7
score: 7
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52699272
answers question: http://stackoverflow.com/q/52699272
type: Answer
has comment: http://stackoverflow.com/comment/92326731

http://stackoverflow.com/comment/92382388
has text: A 2-line batch file or shell script could do this, and you could call the batch file/script with a one-line command.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52728564

http://stackoverflow.com/comment/92175646
score: 2
has text: The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific problem you're having in a [MCVE]. For more information, please see [ask] and take the [tour].
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52620953

http://stackoverflow.com/a/52732435
has comment: http://stackoverflow.com/comment/92390176
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92390560
has comment: http://stackoverflow.com/comment/92390607
has comment: http://stackoverflow.com/comment/92390635
type: Answer
has comment: http://stackoverflow.com/comment/92390411
score: 3
has comment: http://stackoverflow.com/comment/92390369
upvote count: 3
answers question: http://stackoverflow.com/q/52732397
accepted answer of: http://stackoverflow.com/q/52732397
has body: You don't import the settings directly from your settings file, but load them via django.conf.settings. From the documentation: In your Django apps, use settings by importing the object django.conf.settings. Example: from django.conf import settings if settings.DEBUG: # Do something django.conf.settings will itself correctly load the settings file you want to use based on the settings module you specify in wsgi.py. manage.py also looks for an environment variable specifying which settings module to use, so you can choose which settings module to use by setting the enviroment variable, e.g., : export DJANGO_SETTINGS_MODULE=settings_development ./manage.py runserver

http://stackoverflow.com/a/52654122
has body: An approach using pivot_table: (df.pivot_table( index='ID', values='code', aggfunc=','.join).join(df.groupby('ID').happened.first())) code happened ID 1 A,B,A 1 2 A,c,D 0 3 E,E 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52654011
upvote count: 1
has comment: http://stackoverflow.com/comment/92240155

http://stackoverflow.com/comment/92180247
type: QuestionComment
has text: you mean to say, two loops? there is only one while loop in the code
comment on: http://stackoverflow.com/q/52623338
score: 0
type: Comment

http://stackoverflow.com/comment/92264454
has text: it says invalid syntax
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52667206

http://stackoverflow.com/comment/92227076
has text: I might actually write an answer explaining this in detail (when I have the time) if no one else does. It is important to understand the limitation of our means of computing, be that of an algorithm or a regexp/finite automaton.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52646925
type: Comment

http://stackoverflow.com/comment/92146690
score: 0
comment on: http://stackoverflow.com/a/52606218
has text: Thanks, I've got to fix something else in the meantime but I'll try hook this up with my code straight after :)
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52628631
has title: Python's _winapi module
tagged with: python
tagged with: cpython
has comment: http://stackoverflow.com/comment/94091773
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/54145393
type: AnsweredQuestion
tagged with: winapi
score: 7
has body: I was trying to write some python code that requires calls to native WINAPI functions. At first I came across the pypiwin32 package. Then, somewhere on the internet I saw someone using the _winapi module. I found no proper documentation for this module, only this link to cpython's GitHub page. Is this a cpython-specific module? That is, is it not guaranteed that other implementations have this module? Do I need the pypiwin32 package if the functions I need are already implemented in the _winapi module?
answer count: 1
favorite count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/95121351
has answer: http://stackoverflow.com/a/54145393

http://stackoverflow.com/q/52715727
tagged with: python-imaging-library
tagged with: image-processing
has comment: http://stackoverflow.com/comment/92358431
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92391308
has comment: http://stackoverflow.com/comment/92358680
linked to: http://stackoverflow.com/q/2164570
has body: I have a graph with a circular x-axis and some objects in it. I want to convert the graph and make its x-axis horizontal. I want to measure the height (pixel distance) of each object above the x-axis. I tried this with numpy arrays but was only able to get the vertical pixel difference between axis and object, not the true minimum pixel difference. I think I should make an iteration over all circular x-axis points and measure the distance to one object but how would I do that? Edit: This is the original Image
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92358911
has answer: http://stackoverflow.com/a/52717152
has title: Convert circular graph to horizontal graph
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92357110
accepted answer: http://stackoverflow.com/a/52717152

http://stackoverflow.com/q/52743460
tagged with: xbrl
has title: python-xbrl installation error - ordereddict
type: Question
has comment: http://stackoverflow.com/comment/92489081
has comment: http://stackoverflow.com/comment/92431755
score: 0
has comment: http://stackoverflow.com/comment/92448949
has comment: http://stackoverflow.com/comment/92411644
has comment: http://stackoverflow.com/comment/92429596
has comment: http://stackoverflow.com/comment/92412090
type: UnansweredQuestion
tagged with: windows
tagged with: python
tagged with: easy-install
has body: I try to install python-xbrl on Windows (Python 3.6.4) using easy_install. However, I get the error that "Could not find suitable distribution for Requirement.parse&lt;"ordereddict">: :\python-xbrl-master&gt;easy_install python-xbrl Searching for python-xbrl Best match: python-xbrl 1.1.1 Processing python_xbrl-1.1.1-py3.6.egg python-xbrl 1.1.1 is already the active version in easy-install.pth Using c:\anaconda3\lib\site-packages\python_xbrl-1.1.1-py3.6.egg Processing dependencies for python-xbrl Searching for ordereddict Reading https://pypi.python.org/simple/ordereddict/ Download error on https://pypi.python.org/simple/ordereddict/: [Errno 11004] get addrinfo failed -- Some packages may not be found! Couldn't find index page for 'ordereddict' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: [Errno 11004] getaddrinfo failed -- Some packages may not be found! No local packages or working download links found for ordereddict error: Could not find suitable distribution for Requirement.parse('ordereddict') I have also tried with pip install python-xbrl, but I get: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by NewConnectionError('&lt;pip._vendor.urllib3.connection .VerifiedHTTPSConnection object at 0x0000000004FBC240&gt;: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',)': /simple/marshmallow/ Could not find a version that satisfies the requirement marshmallow (from python-xbrl) (from versions: ) No matching distribution found for marshmallow (from python-xbrl) Can it be that my employer is blocking the network access?
answer count: 0

http://stackoverflow.com/a/52637938
has body: note that def __init__() should only have two underscores before and after the init word. also, i think you have to properly indent def __init__() block under the class Player(), indent the for iteration under the move function, and same thing for your if conditions. class Player(): def __init__(self): self.x = 500 self.y = 300 def move(self): for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT and self.x &lt; 720: self.x += 2.5 if event.key == pygame.K_LEFT and self.x &gt; 280: self.x -= 2.5 if event.key == pygame.K_UP and self.y &gt; 80: self.y -= 2.5 if event.key == pygame.K_DOWN and self.y &lt; 520: self.y += 2.5 /ogs
answers question: http://stackoverflow.com/q/52637875
score: 2
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/52693019
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52693135
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/52706581
type: Question
has answer: http://stackoverflow.com/a/52706581
has body: I have a frame with two element in it; namely, an Entry and a Button. class MyEntry(tk.Frame): def __init__(self, root, *args, **kwargs): super().__init__(root) self.var = tk.StringVar(self) self.var.trace("w", self.changed) self.entry = tk.Entry(self, textvariable=self.var) self.button = tk.Button(self, text='▼',command=lambda: self.changed('','','arrow')) Whenever I try to pack() or place() the frame to the parent widget I always get different things - not what I want. I want this: If I use place: self.entry.place(relx=0,rely=0,relwidth=0.95,relheight=1) self.button.place(relx=0.95,rely=0,relwidth=0.05,relheight=1) I get this: Whereas, if I use pack: self.entry.pack(side='left') self.button.pack(side='right') I get this: I use place() for the parent widget. I have tried all combinations of options (fill, expand, propagate etc.) but nothing works!!! Any help would be much appreciated!
has title: Tkinter problem with geometry of composite frame
score: 0
has answer: http://stackoverflow.com/a/52693135
answer count: 2
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/a/52726045
answers question: http://stackoverflow.com/q/52722534
has body: I found a solution a while after I posted the question. The API sends a few entries (filenames) and a link to another page in the header of the response. The files from the question are the first few in the alphabetical order, the first page.
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/52722534
type: Answer

http://stackoverflow.com/a/52736986
type: Answer
has comment: http://stackoverflow.com/comment/92398840
has comment: http://stackoverflow.com/comment/92398713
has comment: http://stackoverflow.com/comment/92402257
has comment: http://stackoverflow.com/comment/92401001
answers question: http://stackoverflow.com/q/52736679
has comment: http://stackoverflow.com/comment/92398760
has body: You can use numpy.busday_count to achieve that: import numpy as np df['BusinessDaysToNextMat'] = df'date', 'matdate'.apply(lambda x: np.busday_count(*x), axis=1) df # date matdate code BusinessDaysToNextMat #0 2018-01-01 2018-01-05 A 4 #1 2018-01-03 2018-01-06 A 3 #2 2018-01-08 2018-01-12 B 4 #3 2018-01-10 2018-01-15 A 3 #4 2018-01-11 2018-01-16 B 3 #5 2018-01-15 2018-01-17 A 2 #6 2018-01-20 2018-01-22 A 0 This doesn't seem completely what you had in your example, but does the most: index = pd.MultiIndex.from_product( [pd.date_range( df['date'].min(), df['date'].max(), freq='C').values, df['code'].unique()], names = ['date', 'code']) resampled = pd.DataFrame(index=index).reset_index().merge(df, on=['date', 'code'], how='left') calc = resampled.dropna() calc['BusinessDaysToNextMat'] = calc'date', 'matdate'.apply(lambda x: np.busday_count(*x), axis=1) final = resampled.merge(calc, on=['date', 'code', 'matdate'], how='left') final['BusinessDaysToNextMat'].fillna(0, inplace=True) final # date code matdate BusinessDaysToNextMat #0 2018-01-02 A 2018-01-05 3.0 #1 2018-01-02 B NaT 0.0 #2 2018-01-03 A 2018-01-06 3.0 #3 2018-01-03 B NaT 0.0 #4 2018-01-04 A NaT 0.0 #5 2018-01-04 B NaT 0.0 #6 2018-01-05 A NaT 0.0 #7 2018-01-05 B NaT 0.0 #8 2018-01-08 A NaT 0.0 #9 2018-01-08 B 2018-01-12 4.0 #10 2018-01-09 A NaT 0.0 #11 2018-01-09 B NaT 0.0 #12 2018-01-10 A 2018-01-15 3.0 #13 2018-01-10 B NaT 0.0 #14 2018-01-11 A NaT 0.0 #15 2018-01-11 B 2018-01-16 3.0 #16 2018-01-12 A NaT 0.0 #17 2018-01-12 B NaT 0.0 #18 2018-01-15 A 2018-01-17 2.0 #19 2018-01-15 B NaT 0.0
score: 0
has comment: http://stackoverflow.com/comment/92428791
has comment: http://stackoverflow.com/comment/92398771
has comment: http://stackoverflow.com/comment/92398864
has comment: http://stackoverflow.com/comment/92398843

http://stackoverflow.com/comment/92324443
type: QuestionComment
has text: @MKJ What is the maximum value in `DOY` column? Is it 31 or 365?
comment on: http://stackoverflow.com/q/52698657
score: 0
type: Comment

http://stackoverflow.com/a/52685182
answers question: http://stackoverflow.com/q/52669019
has body: This may not fully answer the question, but might point you in the right direction and is too long for a comment anyway. Without knowing the details of your xlsx file, it looks like your code should work. I think the most likely clue from the traceback is the message "... is not a proper array of floats". You are coercing the data and x array to be numpy arrays, but they may not be Float64 (double precision) arrays. So check the datatype as well as the shape and type of the ndarrays: print("t2 shape: ", t2.shape, "t2 type: ", type(t2), "t2 dtype: ", t2.dtype) For the fit to work, this must be dtype('float64'). The arrays might be integer array if the values in the spreadsheet are all integers. In that case, just do t2 = np.array(t2, dtype='float64') or t2 = np.asfarray(t2) and so on to force the arrays to be Float64. Or, it might also be that the arrays are "object arrays" if the Series from the spreadsheet mixes numerical and non-numerical data. In that case, you'll have to remove the non-numerical rows, and/or force the dtype to Float64.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92313214
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52669019

http://stackoverflow.com/comment/92344781
comment on: http://stackoverflow.com/q/52709284
has text: Take a look at EPCPyYes: https://pypi.org/project/EPCPyYes/
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92197520
type: QuestionComment
has text: I see one problem with it. Before I was storing my threads in a list. Now I'm not. Maybe I can store the futures too and pass them in.
score: 1
comment on: http://stackoverflow.com/q/52631315
type: Comment

http://stackoverflow.com/q/52627681
has answer: http://stackoverflow.com/a/52627709
accepted answer: http://stackoverflow.com/a/52627709
answer count: 1
downvote count: 0
upvote count: 13
has comment: http://stackoverflow.com/comment/92188847
favorite count: 0
has body: I am on Python 3.7. My code on line 3 works fine, however when I insert the underlying formula into line 4, my code returns the error: SyntaxError: f-string: mismatched '(', '{', or '[' (the error points to the first '(' in line 4. My code is: cheapest_plan_point = 3122.54 phrase = format(round(cheapest_plan_point), ",") print(f"1: {phrase}") print(f"2: {format(round(cheapest_plan_point), ",")}") I can't figure out what is wrong with line 4.
has title: f-string formula inside curly brackets not working
tagged with: python
score: 13
type: AnsweredQuestion
tagged with: f-string
type: Question

http://stackoverflow.com/q/52714925
tagged with: module
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/52727382
has title: Odoo 10 : How to pass parameter to a tree view from button?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52727382
tagged with: odoo
has body: I added a button in contacts form like this : which opens the below tree view of survey but without a filter on email id . how to pass email id with this button to the below tree view of survey?? Info: I tried to add context in the button tag but didnt work. context="{'email': email}"
possible better answer: http://stackoverflow.com/a/52740186
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52740186
tagged with: button
score: 0

http://stackoverflow.com/comment/92216426
type: Comment
comment on: http://stackoverflow.com/a/52641941
type: AnswerComment
score: 0
has text: @jeremydevera - because values not matched. Check `print(df1[df1['SHA-1'].isin(df2['SHA1'])]` with new code and also with original.

http://stackoverflow.com/comment/92405824
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52737245
has text: Edited. Added two images for better understanding
score: 0

http://stackoverflow.com/comment/92284315
type: AnswerComment
comment on: http://stackoverflow.com/a/52677139
type: Comment
has text: This is probably the most straight forward method of trying to resolve my issue. My one concern is I have to check to see if I can run each part of the code, should I just do: `def find(): try: animal_list = getattr(Animal,Global.cur_word) animal_part = next(filter(lambda pdct: Global.nxt_word in pdct, animal_list)) animal_part_data = animal_part[Global.nxt_word][Global.prv_word] return animal_part_data except: None` or should I throw if statements in there? What is your opinion?
score: 0

http://stackoverflow.com/comment/92217481
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52642469
has text: no doubt a good way, but I think OP is interested in `sum` of `Requirement` and `mean` of `Inventory`, not both

http://stackoverflow.com/comment/92126741
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52595776
has text: The OP shouldn't use this library at all. But if you execute something like this, you also need to consume the error and output stream of that process, otherwise the process might block.

http://stackoverflow.com/q/52601337
has comment: http://stackoverflow.com/comment/92137175
linked to: http://stackoverflow.com/q/448271
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92137063
has answer: http://stackoverflow.com/a/52613204
tagged with: python
has comment: http://stackoverflow.com/comment/92159236
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92159109
score: 1
has body: Can anyone guide on resolving the error ? The manager class method will need capability to create instance of User Class but it is not finding the module Below is the folder structure and code and other details. init.py file is empty Internal folder -&gt;main.py -&gt;__init__.py -&gt;User Folder -&gt; user.py -&gt; models.py -&gt; usermanager.py -&gt; __init__.py ModuleNotFoundError: No module named 'models' at &lt;module&gt; (/home/vmagent/app/internal/user/usermanager.py:4) at &lt;module&gt; (/home/vmagent/app/main.py:2) at import_app (/env/lib/python3.6/site-packages/gunicorn/util.py:352) at load_wsgiapp (/env/lib/python3.6/site- packages/gunicorn/app/wsgiapp.py:52) at load (/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py:65) at wsgi (/env/lib/python3.6/site-packages/gunicorn/app/base.py:67) at load_wsgi (/env/lib/python3.6/site- packages/gunicorn/workers/base.py:135) at init_process (/env/lib/python3.6/site- packages/gunicorn/workers/base.py:126) at spawn_worker (/env/lib/python3.6/site- packages/gunicorn/arbiter.py:578) main.py code from internal.account import user,usermanager def registerBlueprint(app, blueprint, manager): blueprint.manager = manager app.register_blueprint(blueprint) registerBlueprint(app, user.request, usermanager) user.py code request = Blueprint('flex.user', __name__) @request.route('/v1/user', methods=['POST']) def CreateAccount(): test = request.manager.UserManager() return test.CreateUser() usermanager.py from models import User class UserManager: def __init__(self): pass def CreateUser(self): logger.log_text("AccountManger") data = json.dumps(dict( email="Hello@123.com", password="Test124" )) user = User(data) user.create() responseObject = dict(status='success', message='Successfully registered.') return make_response(jsonify(responseObject)), 201
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52603583
accepted answer: http://stackoverflow.com/a/52613204
linked to: http://stackoverflow.com/q/4383571
possible better answer: http://stackoverflow.com/a/52603583
tagged with: python-2.7
answer count: 2
has title: Python - Error importing class from another file

http://stackoverflow.com/a/52726563
type: Answer
answers question: http://stackoverflow.com/q/52726395
has comment: http://stackoverflow.com/comment/92378573
has comment: http://stackoverflow.com/comment/92378871
score: 0
has body: It looks like it is unnecessary to keep all the file contents in the file_contents variable. You could save memory by getting rid of this line file_contents += line and just process the file line by line, using line variable instead of file_contents. If you just need to get the most common words you could update the counter with the words of each line and finally get the most commons using the Counter most_common method: from timeit import default_timer as timer from collections import Counter start = timer() cnt = Counter() with open("word5gb.txt", 'r') as input_file: for line in input_file: word_list = line.split() #create word list cnt.update(word_list) print(cnt.most_common(20)) end = timer() print('\n', "Time: ", round(end - start, 2), "s (", round(((end - start)/60),2), " min)")

http://stackoverflow.com/comment/92119517
has text: @HassanMehmood Please post your desired output.
type: Comment
comment on: http://stackoverflow.com/a/52591963
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92219956
has text: Thank you for this answer, this works perfectly on my test data, however my larger dataset contains multiple columns with semicolons. What would you recommend as the quickest way around that? pd.concat?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52633233

http://stackoverflow.com/q/52675373
downvote count: 0
answer count: 1
has title: How to change an element in a list of lists if it has a specific index and condition that is met?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92288619
score: 3
tagged with: performance
has answer: http://stackoverflow.com/a/54165616
upvote count: 3
has body: I want to be able to take a list of lists (lst) and a list of indexes and those elements in lst that have that have those indexes and also meet the condition ( == '1') to be changed to '0'. If I input lst = [['1','2','3'],[],['4','2','1']] and specific_indexes = [(0, 0), (0, 2), (2, 0), (2, 2)] I get [['0', '2', '3'], [], ['4', '2', '0']] but I would like faster way to do this. def change(lst, specific_indexes): for (x,y) in specific_indexes: if lst[y][x] == '1': lst[y][x] = '0' return lst
type: Question

http://stackoverflow.com/q/52711414
tagged with: python
type: Question
has title: List index out of range preventing 404 error?
tagged with: server
score: 0
has answer: http://stackoverflow.com/a/52711489
answer count: 1
has body: I'm trying to complete this lab but cannot seem to get it to work correctly. When I try to get a file not present of the server, I am given This page isn’t working 127.0.0.1 sent an invalid response. ERR_INVALID_HTTP_RESPONSE The response I'd like to get is along the lines of 404 File not found When I try to load a file not present, the compiler says for line 16: filename = message.split()[1] IndexError: list index out of range The code compiles and I am able to open my Hello World file, but I am just not able to get this 404 error. I was given a skeleton code, so there are some things that I cannot change without deviating from course material. from socket import * serverSocket = socket(AF_INET, SOCK_STREAM) #Prepare a server socket serverPort = 7000 serverSocket.bind(('127.0.0.1', serverPort)) serverSocket.listen(5) while True: print('Ready to serve...') connectionSocket, addr = serverSocket.accept() #Fill in start #Fill in end try: message = connectionSocket.recv(1024) print (message) filename = message.split()[1] f = open(filename[1:]) outputdata = f.read() #Send one HTTP header line into socket #Fill in start connectionSocket.send('\nHTTP/1.x 200 OK\n'.encode()) #Fill in end #Send the content of the requested file to the client for i in range(0, len(outputdata)): connectionSocket.send(outputdata[i].encode()) connectionSocket.send("\r\n".encode()) connectionSocket.close() print ('File Recieved') except IOError: connectionSocket.send('\n404 File Not Found\n'.encode()) connectionSocket.close() #Close client socket serverSocket.close() sys.exit() The skeleton code appears to be Python 2, and I'm using Python 3. I've made some minor syntax adjustments to adjust. Removing print(message) yields "File Recieved" in the compiler, but still no 404 error in the browser. I'm at loss after 8 hours.
type: UnansweredQuestion

pycharm
tags question: http://stackoverflow.com/q/52728604
tags question: http://stackoverflow.com/q/52696075
tags question: http://stackoverflow.com/q/52599469
tags question: http://stackoverflow.com/q/52721912
tags question: http://stackoverflow.com/q/52672463
tags question: http://stackoverflow.com/q/52613258
tags question: http://stackoverflow.com/q/52685063
tags question: http://stackoverflow.com/q/52664293
tag name: pycharm
tags question: http://stackoverflow.com/q/52699331
tags question: http://stackoverflow.com/q/52621583
tags question: http://stackoverflow.com/q/52689200
tags question: http://stackoverflow.com/q/52642123
tags question: http://stackoverflow.com/q/52600459
tags question: http://stackoverflow.com/q/52601383
tags question: http://stackoverflow.com/q/52644393
tags question: http://stackoverflow.com/q/52646280
tags question: http://stackoverflow.com/q/52682585
tags question: http://stackoverflow.com/q/52727838
tags question: http://stackoverflow.com/q/52597057
tags question: http://stackoverflow.com/q/52670478
tags question: http://stackoverflow.com/q/52644973
tags question: http://stackoverflow.com/q/52643581
tags question: http://stackoverflow.com/q/52602484
tags question: http://stackoverflow.com/q/52738880
tags question: http://stackoverflow.com/q/52713682
tags question: http://stackoverflow.com/q/52596204
tags question: http://stackoverflow.com/q/52636098
type: Tag
tags question: http://stackoverflow.com/q/52639733
tags question: http://stackoverflow.com/q/52668290

http://stackoverflow.com/comment/92350450
type: AnswerComment
type: Comment
has text: I just took out the parameter given it's the default. I am now getting an error with this line
comment on: http://stackoverflow.com/a/52712074
score: 0

http://stackoverflow.com/a/52741091
downvote count: 0
answers question: http://stackoverflow.com/q/52740901
upvote count: 2
type: Answer
score: 2
has body: In windows 10: Go to start->Network proxy settings->disable 'Use a proxy server' in Manual proxy setup. Now, try to install again using pip install numpy Hope, this helps.

http://stackoverflow.com/comment/92124614
has text: @JeanPaul: Extrapolating to >3 sports is probably best done with `collections.Counter`. `update` the `Counter` with all the `set`s, then `set` comprehension for `{sid for sid, cnt in counter.items() if cnt == 2}`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52594562
type: Comment

http://stackoverflow.com/comment/92461570
has text: The version mismatch is odd; when you run `python -c "import platform; print(platform.mac_ver())"` from the terminal, what do you get?
comment on: http://stackoverflow.com/q/52728792
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52653068
has body: There currently isn't support to specify an alternative REPL that isn't the Python interpreter you use to execute code. One trick some people do if you want this just for sending code to the REPL is they launch the REPL once, exit it, and then launch ipython manually as the extension will continue to use that terminal instance for future code sent to the REPL.
score: 5
has comment: http://stackoverflow.com/comment/123621942
has comment: http://stackoverflow.com/comment/123293342
has comment: http://stackoverflow.com/comment/92566174
upvote count: 5
has comment: http://stackoverflow.com/comment/93880458
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52615414
has comment: http://stackoverflow.com/comment/92507684

http://stackoverflow.com/a/52624063
upvote count: 4
has comment: http://stackoverflow.com/comment/92181810
downvote count: 0
has comment: http://stackoverflow.com/comment/92181854
has comment: http://stackoverflow.com/comment/92181754
has body: You are losing values because the values of the original dict (which can have duplicates) becomes keys in this one. You could do something like inverted = defaultdict(list) for key, value in original_dict.items(): inverted[value].append(key)
score: 4
answers question: http://stackoverflow.com/q/52623971
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52623971
type: Answer

http://stackoverflow.com/a/65977248
has body: The python.exe of the base environment resides in the C:\Users\USERNAME\AppData\Local\Anaconda3 folder If you add this folder to the PATH, you can call that version directly from the prompt and Python will also find many of the installed packages via that anchor folder. However, this is not true for e.g. the Numpy package which heavily depends on compiled C libraries. So you would also need to add the following folders to the PATH: C:\Users\USERNAME\AppData\Local\Anaconda3\Library\mingw-w64\bin; C:\Users\USERNAME\AppData\Local\Anaconda3\Library\usr\bin; C:\Users\USERNAME\AppData\Local\Anaconda3\Library\bin; C:\Users\USERNAME\AppData\Local\Anaconda3\Scripts; C:\Users\USERNAME\AppData\Local\Anaconda3\bin; This is exctly what the activation is for, plus it also gives you the option to easily switch between environments. Bottom line: Adding Anaconda to the PATH might help in simple cases, but the whole concept of Anaconda's dependency management depends on environments and their activation. It's better to use Anacona the proper way right from the beginning and NOT to add Anaconda to the PATH.
downvote count: 0
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/52664293
score: 10

http://stackoverflow.com/comment/92420755
score: 0
type: AnswerComment
has text: This returns Matrix[i][i+1] = -(D/pow(Delta,2)) IndexError: index 101 is out of bounds for axis 0 with size 101
type: Comment
comment on: http://stackoverflow.com/a/52746942

http://stackoverflow.com/a/52819440
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52618451
answers question: http://stackoverflow.com/q/52618451
has body: You're not going to be successful faking out SAML2 SSO. The identity provider (IdP) at UW is looking to support an authentication request from the service provider (SP) polleverywhere.com. Part of that is verifying the request actually originated from polleverywhere. This could be as simple has requiring SSL connection from polleverywhere, it could be as complicated as requiring an encrypted &amp; signed authentication request. Since you don't have those credentials, the resulting response isn't going to be readable. SPs are registered with IdPs. Now, there may be a different way to sign into polleverywhere -- a different URL which will not trigger an SSO request, but that might be network restricted or require other difficult authentication.
type: AcceptedAnswer
downvote count: 0
score: 3

http://stackoverflow.com/comment/92232099
type: AnswerComment
has text: import csv rowdata = [] with open(r'C:\Users\ARPLAB31\Desktop\SPdata.csv') as inputfile: reader = csv.reader(inputfile) rowdata = list(reader) r= [] for i in range(1,718,1): for j in range(28): if len(rowdata[i][j])!=0: r.append(rowdata[i][j]) cardref = [r[x:x+4] for x in range(0, len(r),4)] '''cardref contains the partitioned data.''' print(cardref)
type: Comment
comment on: http://stackoverflow.com/a/52640352
score: 0

http://stackoverflow.com/comment/92163813
score: 0
type: QuestionComment
type: Comment
has text: Thanks for the heads up. Will read up on this.
comment on: http://stackoverflow.com/q/52612667

http://stackoverflow.com/a/52741165
answers question: http://stackoverflow.com/q/52740989
accepted answer of: http://stackoverflow.com/q/52740989
has comment: http://stackoverflow.com/comment/92407125
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92407222
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92407091
has comment: http://stackoverflow.com/comment/92407107
has body: int(n) will return an Integer. If n is a float, it will be truncated. The difference between two integers is (surprisingly...) an integer, so yes the final result is a truncated Integer. Consider using float(n) instead of int(n).

http://stackoverflow.com/a/52685068
has comment: http://stackoverflow.com/comment/92297812
has comment: http://stackoverflow.com/comment/92297889
answers question: http://stackoverflow.com/q/52685052
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52685052
has comment: http://stackoverflow.com/comment/92297828
type: Answer
has comment: http://stackoverflow.com/comment/92297899
has body: You meant to check the divisibility of i, which increments every loop, not of number which doesn't change. You also meant to print(i) in the else clause.
has comment: http://stackoverflow.com/comment/92297876
score: 2
upvote count: 2

data-science
tags question: http://stackoverflow.com/q/52590331
tags question: http://stackoverflow.com/q/52666760
tags question: http://stackoverflow.com/q/52604956
type: Tag
tags question: http://stackoverflow.com/q/52663996
tags question: http://stackoverflow.com/q/52625307
tags question: http://stackoverflow.com/q/52680331
tags question: http://stackoverflow.com/q/52687493
tags question: http://stackoverflow.com/q/52711973
tags question: http://stackoverflow.com/q/52605515
tags question: http://stackoverflow.com/q/52704126
tags question: http://stackoverflow.com/q/52658139
tags question: http://stackoverflow.com/q/52675993
tags question: http://stackoverflow.com/q/52742319
tags question: http://stackoverflow.com/q/52596724
tag name: data-science
tags question: http://stackoverflow.com/q/52596553
tags question: http://stackoverflow.com/q/52642940

http://stackoverflow.com/comment/92369792
comment on: http://stackoverflow.com/a/52722166
type: Comment
has text: Thanks a lot. I wasted lot of time.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92417284
type: QuestionComment
comment on: http://stackoverflow.com/q/52745916
has text: Are you sure the `driver` is getting your expected page view? Perhaps the install button was not available in the page. This seems especially likely on the Play Store as the Install button can be dynamic based on pricing and region. Or perhaps upon clicking it prompts you to login.
score: 0
type: Comment

http://stackoverflow.com/q/52689047
favorite count: 0
has answer: http://stackoverflow.com/a/52689938
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52690011
tagged with: python
possible better answer: http://stackoverflow.com/a/52689938
has title: Moving QSlider to Mouse Click Position
tagged with: qslider
answer count: 4
has answer: http://stackoverflow.com/a/79050235
type: AnsweredQuestion
tagged with: pyqt5
type: Question
score: 9
upvote count: 9
has body: I have a QSlider that I want to move to the position of the mouse cursor when the user presses the left mouse button. I've been hunting around and couldn't find anything that was recent and solved my problem. This is the slider I have. I want to be able to click to have the slider jump to the position where the mouse clicks. I can drag the slider, but I want to be able to click. I tested out clicking on the slider in the Dolphin file manager. It incremented rather than jumping to the exact position of the mouse. Looking at the Qt5 documentation QSlider has very few of its own functions [...] This would indicate that there is no built-in way to do this. Is there no way to get where the mouse clicked and move the slider to that point?
has answer: http://stackoverflow.com/a/52690011
has answer: http://stackoverflow.com/a/69532572
tagged with: pyqt
downvote count: 0

http://stackoverflow.com/a/52664300
has body: This is one approach. Demo: import pandas as pd df = pd.read_csv(filename) def get_nested_rec(key, grp): rec = {} rec['PrimaryId'] = key[0] rec['City'] = key[3] rec["Name"] = [{'FirstName': key[1], 'LastName': key[2]}] #Update. for field in ['CarName','DogName']: rec[field] = list(grp[field].unique()) return rec records = [] for key, grp in df.groupby(['PrimaryId','FirstName','LastName','City']): rec = get_nested_rec(key, grp) records.append(rec) records = dict(data = records) print(records) Output: {'data': [{'CarName': ['Toyota', 'BMW'], 'City': 'NewYork', 'DogName': ['Spike', 'Rusty'], 'Name': [{'FirstName': 'John', 'LastName': 'Smith'}], 'PrimaryId': 100}, {'CarName': ['Volkswagen', 'Ford', 'Audi'], 'City': 'Sydney', 'DogName': ['Buddy', 'Max'], 'Name': [{'FirstName': 'Ben', 'LastName': 'Swan'}], 'PrimaryId': 101}, {'CarName': ['Mini'], 'City': 'London', 'DogName': ['Lucy'], 'Name': [{'FirstName': 'Julia', 'LastName': 'Brown'}], 'PrimaryId': 102}]}
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92304721
has comment: http://stackoverflow.com/comment/92261401
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/52664136
downvote count: 0
answers question: http://stackoverflow.com/q/52664136

http://stackoverflow.com/comment/92180251
type: Comment
comment on: http://stackoverflow.com/q/52623338
has text: What about using an outside `for` loop?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/137578834
has text: `sudo apt install python3.7-distutils`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56384656

http://stackoverflow.com/comment/92113640
type: Comment
type: QuestionComment
score: 5
has text: Where is `logger` coming from? Your code sample produces a`NameError` because `logger` is neither imported nor defined.
comment on: http://stackoverflow.com/q/52589404

http://stackoverflow.com/comment/92409436
comment on: http://stackoverflow.com/q/52742319
type: Comment
has text: Possible duplicate of [Python Pandas: Check if string in one column is contained in string of another column in the same row](https://stackoverflow.com/questions/43855685/python-pandas-check-if-string-in-one-column-is-contained-in-string-of-another-c)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92358856
comment on: http://stackoverflow.com/q/52713154
score: 0
type: Comment
type: QuestionComment
has text: If you are sure you are using the same interpreter on running the program and tests, it must be a `sys.path` difference. Running `/Library/Frameworks/Python.framework/Versions/2.7/bin/python -c "import requests; print(requests.__file__)"` should give you the path to where `requests` are imported from, probably some `/usr/local/lib/python2.7/site-packages` dir. Now add the lines to the test script: `import sys` and `print(sys.path)`, run the test script via `pytest -s testscript.py` and check whether the dir above is present in `sys.path` list.

http://stackoverflow.com/a/52638230
downvote count: 0
answers question: http://stackoverflow.com/q/52638173
upvote count: 2
type: Answer
score: 2
has body: Yes you are passing parameters to the ContractfMapp object. Specifically, a ContractfMapp object is callable. You can verify this: callable(ContractfMapp(context={"context_data": self.context})) &gt;&gt;&gt; True It may make more sense to see that line written like this: f = ContractfMapp(context={"context_data": self.context}) initial = f(pref_data)

http://stackoverflow.com/a/52658853
has comment: http://stackoverflow.com/comment/92248228
answers question: http://stackoverflow.com/q/52658767
type: Answer
has comment: http://stackoverflow.com/comment/92248252
has comment: http://stackoverflow.com/comment/92270516
upvote count: 1
has body: Since you want to flatten the inner sub-lists, you can use list comprehension within a list comprehension: [[i for s in l for i in s] for l in a] This returns: [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
downvote count: 1
score: 0

http://stackoverflow.com/comment/92325734
type: QuestionComment
comment on: http://stackoverflow.com/q/52698670
score: 0
has text: https://www.tensorflow.org/api_docs/python/tf/slice i believe slice is what you are looking for
type: Comment

http://stackoverflow.com/q/52733263
answer count: 1
has title: The Way to Connect Multiple Neural Networks in a Series(Not Parallel)
tagged with: python
has body: I wonder there is any way to connect multiple NN as a series in tensorflow. For example, input features to DNN structure, and get the result values for input data of RNN structure. Example code: import tensorflow as tf import numpy as np a = 50 #batch_size b = 60 #sequence in RNN c = 40 #features d = 6 #label classes rnn_size = b x_data = np.random.rand(a,b,c) y_data = np.random.randint(0,high=d,size=[a,1]) tf.reset_default_graph() X = tf.placeholder(tf.float32, shape=[None,b,c]) Y = tf.placeholder(tf.float32, shape=[None,d]) X = tf.transpose(X, (1,0,2)) X = tf.reshape(X, (-1,c)) X = tf.split(X, b) hidden_units = [40,20,10] #DNN Structure dnn = [] for i in range(len(hidden_units)): if i == 0: T = X else: T = dnn[-1] dnn.append(tf.layers.dense(T, hidden_units[i], activation=tf.nn.relu, kernel_initializer=tf.contrib.layers.xavier_initializer())) # RNN Structure rnn = {'w': tf.Variable(tf.random_normal([rnn_size, d], stddev = 0.01), dtype=tf.float32), 'b': tf.Variable(tf.random_normal([d], stddev = 0.01), dtype=tf.float32)} cell = tf.nn.rnn_cell.BasicLSTMCell(rnn_size) outputs, states = tf.contrib.rnn.static_rnn(cell, dnn[-1], dtype=tf.float32) output = tf.matmul(outputs[-1], rnn['w'])+rnn['b'] cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y,logits=output)) optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) correct = tf.equal(tf.argmax(output,1),tf.argmax(cost,1)) acc = tf.reduce_mean(tf.cast(correct, tf.float32)) # Run Session sess = tf.Session() sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()]) _, c = sess.run([optimizer, cost],feed_dict={X: x_data, Y: tf.Session().run(tf.one_hot(y_data), d)}) print('Accuracy: ', sess.run(acc, feed_dict={X: x_data, Y: tf.Session().run(tf.one_hot(y_data), d)})) When I run this code, there is an error raised: File "C:\Anaconda3\Lib\site-packages\tensorflow\python\layers\core.py", line 250, in dense dtype=inputs.dtype.base_dtype, AttributeError: 'list' object ha…
type: UnansweredQuestion
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52737247
type: Question
score: 0

http://stackoverflow.com/q/52590439
has body: I have a dataset that contains a few columns that are a list of items. I have given an example below. I am trying to find the entries that have items within the list with a 100% match. I would like to find the ones that have 90% or lower. &gt;&gt;&gt; df2 = pd.DataFrame({ 'ID':['1', '2', '3', '4', '5', '6', '7', '8'], 'Productdetailed': [['Phone', 'Watch', 'Pen'], ['Pencil', 'fork', 'Eraser'], ['Apple', 'Mango', 'Orange'], ['Something', 'Nothing', 'Everything'], ['Eraser', 'fork', 'Pencil'], ['Phone', 'Watch', 'Pen'],['Apple', 'Mango'], ['Pen', 'Phone', 'Watch']]}) &gt;&gt;&gt; df2 ID Productdetailed 0 1 [Phone, Watch, Pen] 1 2 [Pencil, fork, Eraser] 2 3 [Apple, Mango, Orange] 3 4 [Something, Nothing, Everything] 4 5 [Eraser, fork, Pencil] 5 6 [Phone, Watch, Pen] 6 7 [Apple, Mango] 7 8 [Pen, Phone, Watch] If you notice the index 0 and index 7 in df2, have the same set of items but in different order. Where as index 0 and index 5 have same items in same order. I would like to consider both of them as a match. I tried groupby and series.isin(). I also tried intersection by splitting the dataset into two but it fails with type error. First I would like to count the number of exact matched items(number of matched row count will do) along with the row index numbers it matched to. But when there are items that have only partially matched like index 2 and index 6 in df2. I would like to say the percent of items that have matched and against which column numbers. I mentioned. I tried to split the data on specific column value into two parts. Then applied df2['Intersection'] = [list(set(a).intersection(set(b))) for a, b in zip(df2_part1.Productdetailed, df2_part2.Productdetailed) ] , where a and b are the Productdetailed column from the broken pieces of df2_part1 and df2_part2. Is there a way to do this? Please help
possible better answer: http://stackoverflow.com/a/52591738
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/92115663
has comment: http://stackoverflow.com/comment/92115690
tagged with: string-matching
type: AnsweredQuestion
downvote count: 0
has title: Find common values within a column containing list of items
type: Question
has comment: http://stackoverflow.com/comment/92115604
score: 3
has answer: http://stackoverflow.com/a/52591727
accepted answer: http://stackoverflow.com/a/52591727
upvote count: 3
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52591738
favorite count: 0

http://stackoverflow.com/comment/92152971
comment on: http://stackoverflow.com/q/52608956
score: 0
type: Comment
type: QuestionComment
has text: i have shared the url .. please check this.. tables

http://stackoverflow.com/comment/92217091
comment on: http://stackoverflow.com/q/52642078
has text: I understood auth_views.PasswordResetConfirmView.as_view() as the builtin function with the definition
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52655847
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52655873
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/62890456
upvote count: 1
has answer: http://stackoverflow.com/a/52680369
accepted answer: http://stackoverflow.com/a/52680369
answer count: 6
has answer: http://stackoverflow.com/a/66621471
has title: ModuleNotFoundError: No module named 'mpl_finance'
has body: Hi I am following a tutorial that was using matplotlib.finance to use candlestick.ohlc. When researching I found out that that lib was deprecated and to use mlp_finance. I believe I have installed it by running the command prompt and entering the line pip install mpl_finance. The result that I get this I tried re running the script but I still get the error: from mpl_finance import candlestick_ohlc ModuleNotFoundError: No module named 'mpl_finance' I checked the python library path and I don't see a folder labeled mlp_finance(Im not sure if Im suppose to). But I do see a file labeled mpl_finance-0.10.0-py3.7.egg Any help on resolving this issue? Downloaded the git package and ran the command prompt install ran the command line pip install git clone https://github.com/matplotlib/mpl_finance.git mpl_finance.git
favorite count: 0
has answer: http://stackoverflow.com/a/69323493
tagged with: mplfinance
has answer: http://stackoverflow.com/a/66615498
possible better answer: http://stackoverflow.com/a/62890456
tagged with: python

http://stackoverflow.com/q/52644413
upvote count: 1
type: Question
tagged with: pybind11
has title: How to catch the exit signal raised by Py_Finalize()?
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92658632
tagged with: c++
has body: I am using pybind11 to embed python interpreter into C++ with pybind11::scoped_interpreter guard{}. I import my own module, run some functions, then exit the program. When the software exits, pybind11 eventually calls Py_Finalize(). I want to catch the exit signal inside my python module to call some destructors, when Py_Finalize() called inside C++. How can I achieve that? C++ code: pybind11::scoped_interpreter guard{}; py::module my_module = py::module::import("my_module"); my_module.attr("my_function")(someData); python code (my_module.py): session.init() def my_func(input): output = session.foo(input) return output #how to catch exit signal to run this function def run_at_exit(session): session.finalize()
answer count: 0
score: 1

http://stackoverflow.com/q/52711429
has comment: http://stackoverflow.com/comment/92351721
upvote count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
linked to: http://stackoverflow.com/q/38258457
tagged with: algorithm
has title: Binary Search: Infinite Loop
score: -1
type: Question
answer count: 1
favorite count: 0
tagged with: binary-search
has answer: http://stackoverflow.com/a/52711486
has body: I am trying to solve a binary search problem, however, I keep getting an infinite loop, since the values of lo hi and mid do not change as they suppose to. I am trying to search for a minimum mid value where function count_lines(mid,k) &gt;= n. I have spent hours debugging this code but I still couldn't figure out what is wrong with the values of lo hi and mid. Could someone please look at my code and show me why this happen? Many thanks! Failed testing case where: n=9 k=2 Here is my code: def count_lines(v,k): ... ... return count_lines #count_lines is an integer` def binarySearch_v(n, k): lo = 0 hi = n mid = (lo + hi)//2 while (lo &lt;= hi): if (count_lines(mid, k) &lt; n): lo = mid elif (count_lines(mid, k) &gt; n): hi = mid elif (count_lines(mid, k) &gt;= n and count_lines(mid-1, k) &lt; n): return mid mid = (lo + hi) // 2 def main(): print(binarySearch_v(n,k)) # Failed at n=9 &amp; k=2 main()

sparse-matrix
tags question: http://stackoverflow.com/q/52743352
tag name: sparse-matrix
tags question: http://stackoverflow.com/q/52707684
tags question: http://stackoverflow.com/q/52685560
tags question: http://stackoverflow.com/q/52620232
tags question: http://stackoverflow.com/q/52704189
type: Tag
tags question: http://stackoverflow.com/q/52685069

http://stackoverflow.com/a/52607240
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52606289
score: 2
has comment: http://stackoverflow.com/comment/92176048
upvote count: 2
has body: I don't think resize 1x1 is a good method to get the average color of the image. I don't know what wand is. But if you have read the image into numpy.ndarray, then you can get the avg like this: #!/usr/bin/python3 # 2018.10.02 19:07:21 CST import cv2 def getAvg(img): nh,nw = img.shape[:2] nc = 1 if img.ndim==2 else img.shape[2] avg = img.reshape(-1, nc).sum(axis=0)/(nw*nh) return avg img = cv2.imread("doll.jpg") avg = getAvg(img) print("Avg: {}".format(avg)) # Avg: [148.661125 146.273425 155.205675]

http://stackoverflow.com/comment/92292794
comment on: http://stackoverflow.com/q/52681280
has text: You want to use [cloudbilling.projects.updateBillingInfo] API (https://cloud.google.com/billing/reference/rest/v1/projects/updateBillingInfo) to update the `billingAccountName` in individual projects when your billing costs shoots about 200 USD
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92260041
has text: Quoting [Alex Martelli](https://stackoverflow.com/users/95810/alex-martelli) from the answer [here](https://stackoverflow.com/questions/1637807/modifying-list-while-iterating), *Never alter the container you're looping on, because iterators on that container are not going to be informed of your alterations and, as you've noticed, that's quite likely to produce a very different loop and/or an incorrect one.*
type: QuestionComment
comment on: http://stackoverflow.com/q/52665167
type: Comment
score: 3

http://stackoverflow.com/comment/92171599
score: 1
has text: Neat, glad it works again!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52616841

http://stackoverflow.com/q/52673814
has answer: http://stackoverflow.com/a/52673918
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52673916
has comment: http://stackoverflow.com/comment/92277431
favorite count: 0
has answer: http://stackoverflow.com/a/52674021
has comment: http://stackoverflow.com/comment/92277461
possible better answer: http://stackoverflow.com/a/52673916
has body: What is the best way for removing decimals in a pandas dataframe? Example Data: 1.10 2.20 3.30 4.40 Expected result: 110 220 330 440
tagged with: python
accepted answer: http://stackoverflow.com/a/52673918
has comment: http://stackoverflow.com/comment/92277486
score: 2
type: AnsweredQuestion
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/92277411
type: Question
has title: How to remove the decimal point in a Pandas DataFrame
tagged with: dataframe

http://stackoverflow.com/comment/92358431
type: QuestionComment
comment on: http://stackoverflow.com/q/52715727
has text: First I convert the image into numpy arrays. But how do I convert a numpy array into polar coordinates?
score: 0
type: Comment

http://stackoverflow.com/q/52711175
has comment: http://stackoverflow.com/comment/92349975
has comment: http://stackoverflow.com/comment/92348833
tagged with: python
has body: I have a data frame with a variable called 'Countdown' that counts down the days in my data frame even though some days have multiple entries (rows). full dates Countdown 0 2008-01-01 3652 1 2008-01-02 3651 2 2008-01-03 3650 3 2008-01-04 3649 4 2008-01-05 3648 5 2008-01-06 3647 I would like the countdown variable to 'restart' after certain days. So I would like one countdown from 2008-01-01 to 2008-01-03 then 2008-01-03 to 2008-01-06, etc. Desired output: full dates Countdown 0 2008-01-01 2 1 2008-01-02 1 2 2008-01-03 0 3 2008-01-04 2 4 2008-01-05 1 5 2008-01-06 0 My dataframe is much larger but the idea is the same: between two given days I would like to start a countdown and then 'restart' it at another day (in the example it 'restarted' on 2008-01-03 and 2008-01-06.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52712074
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/92349517
has title: Restarting a countdown based on another column
answer count: 1
has comment: http://stackoverflow.com/comment/92348615
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52712074

http://stackoverflow.com/a/72596872
type: Answer
has body: You could do this by joining the elements together into a string and then splitting the string back again using a regex: import re sentence = ["I", "am", "good", ".", "I", "like", "you", ".", "we", "are", "not", "friends", "."] result = [m.split('\0') for m in re.findall(r'(?<=\0).*?\.(?=\0|$)', '\0'.join(['.']+sentence))] Output: [ ['I', 'am', 'good', '.'], ['I', 'like', 'you', '.'], ['we', 'are', 'not', 'friends', '.'] ]
score: 0
answers question: http://stackoverflow.com/q/52590886

http://stackoverflow.com/q/52647476
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/66995078
tagged with: python
has title: python unit-test assert called with partial
downvote count: 0
score: 19
tagged with: unit-testing
has body: using python 3.5.3 I want to assert that mocked function received specific arguments, but I don't want to check all received arguments, only the ones which are important for the test. for example, instead of doing that: my_func_mock.assert_called_with('arg1','arg2','arg3') I would like to do something like: my_func_mock.assert_called_with_partial(arg2='arg2') Is it possible?
type: Question
tagged with: assertion
has comment: http://stackoverflow.com/comment/92253680
has comment: http://stackoverflow.com/comment/92300271
upvote count: 19
has answer: http://stackoverflow.com/a/66009632
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/52648238

http://stackoverflow.com/comment/92390505
score: 0
type: Comment
type: QuestionComment
has text: Yes but here i have only 2 stocks, when its 200 stocks. I have to manually write ticker1 to ticker200. Right?
comment on: http://stackoverflow.com/q/52732739

http://stackoverflow.com/comment/92311949
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52692420
has text: perhaps, I'm new to using async, asncid, and async_to_sync, so learning things now. Is there a difference between what your code does and mine? Or is yours just a cleaner approach?

http://stackoverflow.com/a/52647821
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52647650
upvote count: 1
has body: I think the problem will be that worksheets themselves do not contain any VBA code. This is stored as a blob in the XLSX package and may well contain hard-coded references to particular worksheets. Unfortunately the VBA blobs are not covered by the OOXML specification so there is no way to know. You might be okay if you copy the vba_code property manually but there is no guarantee and it's just as likely that Excel will complain about the file.
has comment: http://stackoverflow.com/comment/92229261
has comment: http://stackoverflow.com/comment/92230392

http://stackoverflow.com/q/52594382
tagged with: tensorflow
type: Question
has body: It could be a replicate question, but none of the existing questiones have been useful for me. I've tried all the solutions given here (stackoverflow) I get this error: Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow I have this version of the pip on my Pycharm machine with Python 3.6 (Windows 10): Package Version ------- pip 18.0 -- setuptools 40.4.3 -- wheel 0.32.0 I would like to install tensorflow and I have tried to take a look at this link as most of the people suggested. Does anybody want to guide me in my installation?
linked to: http://stackoverflow.com/q/38896424
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52594638
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92136232
has answer: http://stackoverflow.com/a/57761310
tagged with: python
linked to: http://stackoverflow.com/q/45317706
has title: Installing Tensorflow for Python 3.6 (Windows 10)

http://stackoverflow.com/comment/92201390
type: QuestionComment
type: Comment
has text: Well, I'd try to find out if there is someone else using this for whom the code works. Or I'd look at the git history to see who added that import and with what excuse
comment on: http://stackoverflow.com/q/52633535
score: 0

http://stackoverflow.com/q/52669705
has title: AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d' [Opencv 3.4.3]
accepted answer: http://stackoverflow.com/a/52685991
has answer: http://stackoverflow.com/a/52674646
downvote count: 1
tagged with: opencv
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/52574336
has comment: http://stackoverflow.com/comment/92278701
has comment: http://stackoverflow.com/comment/92287544
possible better answer: http://stackoverflow.com/a/70595382
has answer: http://stackoverflow.com/a/70595382
has comment: http://stackoverflow.com/comment/92269305
upvote count: 10
has comment: http://stackoverflow.com/comment/92269374
type: Question
score: 9
has comment: http://stackoverflow.com/comment/92299790
has body: I have opencv 3.4.3 installed (using pip3 install opencv-python and pip3 install opencv-python-contrib) When I run a code containing this line: sift = cv2.xfeatures2d.SIFT_create() I got this error: AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d' Is xfeatures2d function not anymore supported by opencv 3.4.3?
has answer: http://stackoverflow.com/a/64674347
has comment: http://stackoverflow.com/comment/118778702
has comment: http://stackoverflow.com/comment/92269418
has answer: http://stackoverflow.com/a/52685991
has comment: http://stackoverflow.com/comment/92295140
favorite count: 0
has comment: http://stackoverflow.com/comment/92269273
has comment: http://stackoverflow.com/comment/92287481
tagged with: python
has comment: http://stackoverflow.com/comment/92287527
answer count: 4

http://stackoverflow.com/comment/92379629
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52726134
type: Comment
has text: No that's what I'm assuming. My code example is a way to achieve this communication between client and server

http://stackoverflow.com/a/52721364
has comment: http://stackoverflow.com/comment/92369015
downvote count: 3
has comment: http://stackoverflow.com/comment/92370535
score: 3
upvote count: 6
answers question: http://stackoverflow.com/q/52717761
has comment: http://stackoverflow.com/comment/92370641
type: Answer
has body: You can use the --install-option to forward options to setuptools, so the following should work: pip install --install-option="--extras-require=server" git+ssh://git@bitbucket.org/org/repo.git See also: $ pip install --help Usage: pip install [options] &lt;archive url/path&gt; ... [...] Install Options: [...] --install-option &lt;options&gt; Extra arguments to be supplied to the setup.py install command (use like --install-option="--install-scripts=/usr/local/bin"). Use multiple --install-option options to pass multiple options to setup.py install. If you are using an option with a directory path, be sure to use absolute path. --global-option &lt;options&gt; Extra global options to be supplied to the setup.py call before the install command.

http://stackoverflow.com/q/52633383
score: 0
answer count: 2
tagged with: django
has answer: http://stackoverflow.com/a/52634550
has comment: http://stackoverflow.com/comment/92200207
has title: How to show Python print() in html div
has answer: http://stackoverflow.com/a/52635020
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92202716
has body: I am using Django to write my website. During writing my Python code I have many print functions. They all are shown in standard console. I would like to show (live without refreshing a page) all my prints in div in my HTML code not only in console. How to do that? My code do: You press button then selenium starts using ajax without refreshing page and during that I would like to show progress on a page using div. For example, my code: views.py bot = Instagram() class InstabotFormView(AjaxFormMixin, FormView): form_class = LoginInstagramForm template_name = 'instabot.html' success_url = 'runinstabot.html' def form_invalid(self, form): response = super(InstabotFormView, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(InstabotFormView, self).form_valid(form) login = form.cleaned_data.get('login') password = form.cleaned_data.get('password') tagi = form.cleaned_data.get('tags') func = form.cleaned_data.get('function') tags = [] tagi = tagi.split(',') tags.extend(tagi) if self.request.is_ajax(): print('It is AJAX') bot.login(login,password) bot.search(tags) if func == '1': bot.downloadPhoto(tags) elif func == '2': bot.doCalculation(tags) print(tags) data = { 'message': "Succesfully opened Selenium." } return JsonResponse(data) else: return response Instagram() def downloadPhoto(self): i = 0 time.sleep(2) self.driver.find_element_by_xpath('/html/body/span/section/main/div/header/section/ul/li[2]/a').click() print('Start function downloadPhoto') print(self.myCurrentList) for photo in self.myCurrentList: followerPhoto = self.myCurrentList.index(photo) + 1 print(followerPhoto) How to show all prints from def downloadPhoto(self) in html div?
tagged with: ajax
type: Question
has comment: http://stackoverflow.com/comment/92202232
tagged with: python

http://stackoverflow.com/comment/92226159
type: Comment
type: QuestionComment
has text: @JudismarArpiniJunior yes that's it, and the bar is always at the 6th or 7th position
comment on: http://stackoverflow.com/q/52646581
score: 0

http://stackoverflow.com/comment/140203284
comment on: http://stackoverflow.com/q/52665596
type: Comment
type: QuestionComment
has text: Now there's also [uv](https://github.com/astral-sh/uv), which is "designed as a drop-in replacement for common `pip` and `pip-tools` workflows" ([docs](https://docs.astral.sh/uv/pip/compatibility/)), and provides lock file functionality.
score: 0

http://stackoverflow.com/q/52643010
has comment: http://stackoverflow.com/comment/92218356
answer count: 0
has title: Python QApplication segmentation fault
type: Question
has comment: http://stackoverflow.com/comment/92218505
tagged with: python
has body: I'm trying to run pyt5 on an Ubuntu machine, but even the basic example fails: import sys from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget from PyQt5.QtCore import QSize class HelloWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(640, 480)) self.setWindowTitle("Hello world") centralWidget = QWidget(self) self.setCentralWidget(centralWidget) gridLayout = QGridLayout(self) centralWidget.setLayout(gridLayout) title = QLabel("Hello World from PyQt", self) title.setAlignment(QtCore.Qt.AlignCenter) gridLayout.addWidget(title, 0, 0) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) #&lt;--crash after this line mainWin = HelloWindow() mainWin.show() sys.exit( app.exec_()) when trying to build the QApplication object I get: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) running the same file from outside PyCharm (terminal) yields: Segmentation fault (core dumped) I'm using Python 3.6.5 on Ubuntu 16.04.5 LTS
score: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/92218285
type: UnansweredQuestion
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/92218423

http://stackoverflow.com/comment/92355564
comment on: http://stackoverflow.com/a/52715015
has text: Actually `gprospect_linkedin_button gprospect_linkedin_button_style_medium`, are two classes. The OP used the method correctly.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/128626680
comment on: http://stackoverflow.com/a/61250010
score: 0
type: AnswerComment
has text: Not available in Python
type: Comment

http://stackoverflow.com/a/52749500
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52728326
answers question: http://stackoverflow.com/q/52728326
type: Answer
has body: So actually this is quite simple to do with Java having this built in from the box. Java has this thing that is called 'ScriptEngineManager'. To use it you just do the following: ScriptEngineManager sem = new ScriptEngineManager (); ScriptEngine se = sem.getEngineByName ( "python" ); Now there are a few ways to runa script. Simple call the se.eval () method. You can give this either a String or a Reader and this way it will run the script. Now to make it have some variables simply use the se.put method. You need to give this two parameters; a String and an Object. For example: se.put ( "entity", entity ); // with entity being defined earlier The onlt thing to keep in mind is that this script manager does not have built in python support. You need to either create your own ScriptEngine for this or use third party software. I found jython and this seems to be working prety well. If you download the standalone jar and put that in your classpath it works. No need for any function calling. Now in the Script you can call any public member of entity. All the objects, values and those sub-objects get passed through to the script. My end-code: Entity class public class Entity { String source = "entity.loc_x += 1\n" + "entity.loc_z = entity.loc_x"; ScriptEngine se; loc_x = 0; loc_y = 0; loc_z = 0; public Entity () { ScriptEngineManager sem = new ScriptEngineManager (); se = sem.getEngineByName ( "python" ); se.put ( "entity", this ); } public void update () { se.eval ( source ); } } I hope I helped anyone with this. It was pretty fun tinkering with all of this.
score: 2

http://stackoverflow.com/q/52736245
downvote count: 0
favorite count: 0
has title: browsing eeg with mne_browse_raw in python windows
type: UnansweredQuestion
tagged with: python
tagged with: plot
has body: I want to use the seemingly nice mne browser but with the python mne version on windows. Seems I cannot resort to the C version as it's not supported in windows. I saw a previous post but wanted to ask if there are any updates on this or any way to go around it.
answer count: 0
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/92184668
type: QuestionComment
score: 1
has text: Related: [What is the difference between native int type and the numpy.int types?](https://stackoverflow.com/questions/38155039/what-is-the-difference-between-native-int-type-and-the-numpy-int-types)
comment on: http://stackoverflow.com/q/52622708
type: Comment

http://stackoverflow.com/q/52694689
type: Question
has body: I am working with a list of dictionaries: student_list = [{'id': 12341, 'first_name': 'Alice', 'last_name': 'Anderson', 'assignments': [('assignment_1', 0), ('assignment_2', 2), ('assignment_3', 4)]}, {'id': 12342, 'first_name': 'Boris', 'last_name': 'Bank', 'assignments': [('assignment_1', 1), ('assignment_2', 3), ('assignment_3', 0)]}, {'id': 12343, 'first_name': 'Carl', 'last_name': 'Cape', 'assignments': [('assignment_1', 2), ('assignment_2', 4), ('assignment_3', 1)]}, {'id': 12344, 'first_name': 'Didi', 'last_name': 'Dawson', 'assignments': [('assignment_1', 3), ('assignment_2', 0), ('assignment_3', 2)]}, {'id': 12345, 'first_name': 'Ed', 'last_name': 'Enders', 'assignments': [('assignment_1', 4), ('assignment_2', 1), ('assignment_3', 3)]}] I need to write a function that searches for a dictionary by the students name, looks to see if there is matching assignment name and grade. If there is it returns True, if there isn't it returns False and adds it too the list. I am close with what I have, but regardless of if I type a true or false set if parameters it reads false and adds the assignment in as a tuple. Can you help me find the missing piece of instruction needed in this function? def add_grade(student, assignment_name, grade): for s in student_list: if s['first_name'] == student: if any(s['assignments']) == (assignment_name, grade): print(True) else: s['assignments'].append((assignment_name, grade)) print(False) add_grade('Carl', 'assignment_2', 2) print(student_list) EDIT: The first answer helped me get the code working (Thanks!) Now I've bulked it out and made it sloppier so that instead of an assignment being added twice with two different grades it puts an output that it exists already. What I have made is bulky and messy, and it seems like the fix should be easy but I can't figure it out. Thoughts? def add_grade2(student, assignment_name, grade): for s in student_list: if s['first_name'] == student: if (assignment_name, grade) in s['assignments']: prin…
has title: Programming resorting to Else statement when If is True
answer count: 2
accepted answer: http://stackoverflow.com/a/52694723
has answer: http://stackoverflow.com/a/52694774
possible better answer: http://stackoverflow.com/a/52694774
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52694723

http://stackoverflow.com/a/52658790
has body: Regarding the answer function you posted: At the end of each iteration of the outer loop, coefficients[x] is the number of staircases you can make with height at most i, having used a total of x blocks. (including staircases with only one stair or zero stairs). coefficients is initialized to [1,0,0...] before the loop, indicating that there is only one staircase you can make with height at most 0. It is the one with no stairs, so you will have consumed 0 blocks to make it. In each iteration of the loop, the coefficients array is transformed from representing max height i-1 to representing max height i, by incorporating the possibility of adding a step of height i to any shorter staircase that leaves you with at least i blocks. finally it returns the number of ways you can get to the end after having used all n blocks, minus one since the single stair of height n is invalid. This algorithm is an example of "dynamic programming".
score: 5
answers question: http://stackoverflow.com/q/52654530
has comment: http://stackoverflow.com/comment/125244812
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/92298679
type: AnswerComment
comment on: http://stackoverflow.com/a/52685418
score: 0
has text: This works, but it makes very inefficient use of the limited number of guesses available.
type: Comment

http://stackoverflow.com/a/52700700
has comment: http://stackoverflow.com/comment/92327935
has comment: http://stackoverflow.com/comment/92327859
type: Answer
answers question: http://stackoverflow.com/q/52700655
has comment: http://stackoverflow.com/comment/92328111
has body: Change it as from .views import * or from .views import ViewName
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92328090
has comment: http://stackoverflow.com/comment/92327945
score: 0
has comment: http://stackoverflow.com/comment/92328057

http://stackoverflow.com/comment/92322203
type: QuestionComment
has text: Please post your code and not the screenshots
score: 0
comment on: http://stackoverflow.com/q/52697884
type: Comment

http://stackoverflow.com/q/52614773
linked to: http://stackoverflow.com/q/5658369
favorite count: 0
has answer: http://stackoverflow.com/a/52615169
accepted answer: http://stackoverflow.com/a/52615169
has comment: http://stackoverflow.com/comment/92165034
has body: I would like to replace all double backslashes \\ enclosed between $ symbols or $$ symbols with four backslashes \\\\. E.g., I want to convert some \\ random text $ 5\\ 6$ to some \\ random text $ 5\\\\ 6$, and some $5x^2 \$ random text $$ 5 \\ 6$$ to some $5x^2 \$ random text $$ 5 \\\\ 6$$. How can I do this using regex and Python?
tagged with: python
has comment: http://stackoverflow.com/comment/92164180
tagged with: regex
tagged with: mathjax
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92164006
has comment: http://stackoverflow.com/comment/92164242
has comment: http://stackoverflow.com/comment/92164050
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/2081640
has title: How to Replace 2 Backslashes Between $ Symbols with 4 Backslashes using Python and Regex?
has comment: http://stackoverflow.com/comment/92163964
score: -1
has comment: http://stackoverflow.com/comment/92163913
has comment: http://stackoverflow.com/comment/92165129
upvote count: 0
answer count: 1

http://stackoverflow.com/q/52609695
type: Question
has comment: http://stackoverflow.com/comment/92162526
linked to: http://stackoverflow.com/q/18259067
accepted answer: http://stackoverflow.com/a/52610238
upvote count: 0
has title: Panda Data frame : How to merge columns of 1 and 0 to a new column
score: -1
tagged with: pandas
has comment: http://stackoverflow.com/comment/92164633
answer count: 1
has comment: http://stackoverflow.com/comment/92154561
favorite count: 0
has comment: http://stackoverflow.com/comment/92154895
has comment: http://stackoverflow.com/comment/92163870
has comment: http://stackoverflow.com/comment/92162385
has comment: http://stackoverflow.com/comment/92162363
tagged with: python
has body: I have a data frame like as below I am trying to get Merged DataFrame I am able to merge Company_Candidate_Dataframe and Candidate_Detail_Dataframe. But that is not what I exactly need. I also thought of creating a dictionary from Company_Candidate_Dataframe and feed to Candidate_Detail_Dataframe.apply(some lambda) What should be a better way of doing this? Edit: Data as text Candidate Google Netflix Microsoft Amazon Paypal John 0 0 1 0 0 Mary 1 0 0 0 0 Ravenshaw 0 1 0 0 0 Lohan 1 0 0 0 0 Nile 0 0 0 1 0 ------------------------- Candidate Id Address Score John 1 ABC 13 Mary 2 XYZ 24 Ravenshaw 3 A1B1 90 Lohan 4 Lqw 102 Nile 5 Arou 23
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52610238
linked to: http://stackoverflow.com/q/10202570
downvote count: 1

http://stackoverflow.com/comment/92270287
comment on: http://stackoverflow.com/a/52670136
score: 1
type: AnswerComment
has text: I see, thanks for the clarification, kind of forgot that you can use prefetch_related as a more flexible select_related. I guess the other difference is that with prefetch_related you'd always see an extra query, while select_related would use a join in one query.
type: Comment

http://stackoverflow.com/a/52620793
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52620256
type: Answer
score: 2
downvote count: 0
has body: you could try placing all the contents of the text file in a list, and iterate through that list to delete that particular file. import os file_list = [x.strip("\n") for x in open("file_containing_pys.txt","r")] for file in file_list: os.system("sudo kill $(ps aux | grep 'python %s.py' | awk '{ print $2 }')"%file) /ogs
upvote count: 2
answers question: http://stackoverflow.com/q/52620256

http://stackoverflow.com/q/52740014
has answer: http://stackoverflow.com/a/52740242
has comment: http://stackoverflow.com/comment/92405013
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52740171
has comment: http://stackoverflow.com/comment/92404733
tagged with: python
has answer: http://stackoverflow.com/a/52740226
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52741343
has body: i'm new to python and right now i'm out of ideas. What i'm trying to: i got a file example: 254 578 name1 *--21-&gt;28--* secname1 854 548 name2 *--21-&gt;28--* secname2 944 785 name3 *--21-&gt;28--* secname3 1025 654 name4 *--21-&gt;28--* secname4 between those files are a lot of spaces and i wan't to remove specific spaces between "name*" and "secname*" for each row. I don't know what to do to as seen in the example remove the character/spaces 21 -> 28 What i got so far: fobj_in = open("85488_66325_R85V54.txt") fobj_out = open("85488_66325_R85V54.txt","w") for line in fobj_in: fobj_in.close() fobj_out.close() At the end it should look like: 254 578 name1 secname1 854 548 name2 secname2 944 785 name3 secname3 1025 654 name4 secname4
score: 1
has answer: http://stackoverflow.com/a/52740204
possible better answer: http://stackoverflow.com/a/52740226
has title: Deleting specific columns of each row
has answer: http://stackoverflow.com/a/52740234
accepted answer: http://stackoverflow.com/a/52740234
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/92404813
answer count: 6

http://stackoverflow.com/a/52640877
has body: I think you need to empty the all_images list inside the loop as: def getalbum(self,request): albums=Album.objects.filter(user=request.user) album={} image_list={} all_results=[] for a in albums: album_images=AlbumImage.objects.filter(album=a) all_images = [] for i in album_images: image_object=Upload.objects.get(id=str(i.image)) image_list=str(image_object.image) all_images.append(image_list) album[a.name]=all_images all_results.append(album) return Response(all_results)
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52640677
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52640677
upvote count: 2

http://stackoverflow.com/comment/92149465
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52605821
has text: @Isma I added an example

http://stackoverflow.com/a/52740234
has comment: http://stackoverflow.com/comment/92407301
score: 3
has comment: http://stackoverflow.com/comment/92406060
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52740014
has comment: http://stackoverflow.com/comment/92406361
has body: To remove characters by specific index positions you have to use slicing for line in open('85488_66325_R85V54.txt'): newline = line[:21] + line[29:] print(newline) removes the characters in column 21:28 (which are all whitespaces in your example)
accepted answer of: http://stackoverflow.com/q/52740014
has comment: http://stackoverflow.com/comment/92406524
type: Answer
upvote count: 3

http://stackoverflow.com/q/52686489
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/64002706
upvote count: 12
has answer: http://stackoverflow.com/a/64002706
score: 10
has body: for example. Data A: y female male 1 2 3 4 5 6 I want to 'gather' it to this: y gender value 1 female 2 1 male 3 4 female 5 4 male 6 It's easy in R. What about python pandas?
tagged with: pandas
has answer: http://stackoverflow.com/a/52686609
has answer: http://stackoverflow.com/a/63085677
favorite count: 0
accepted answer: http://stackoverflow.com/a/52686609
has title: Equivalent 'spread' and 'gather' in R/tidyverse in python/pandas?
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/67309014
answer count: 4

http://stackoverflow.com/a/71226861
score: 102
type: Answer
downvote count: 0
upvote count: 102
has body: Posting as it might help future users. As correctly pointed out by others, np.isnan won't work for object or string dtypes. If you're using pandas, as mentioned here you can directly use pd.isnull, which should work in your case. import pandas as pd import numpy as np var1 = '' var2 = np.nan &gt;&gt;&gt; type(var1) &lt;class 'str'&gt; &gt;&gt;&gt; type(var2) &lt;class 'float'&gt; &gt;&gt;&gt; pd.isnull(var1) False &gt;&gt;&gt; pd.isnull(var2) True
answers question: http://stackoverflow.com/q/52657223

http://stackoverflow.com/comment/92216025
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52641768
has text: how do i get the doc type and xml version tags. Thanks
score: 0

http://stackoverflow.com/q/52614334
has comment: http://stackoverflow.com/comment/92164434
answer count: 0
has body: I have a time series table of inventory with a function that tells me whether I have to restock based on quantity (if available is less than 10, restock) I need to iterate over each row to subtract the amount of DVDs rented every day from my available inventory so that I can flag days where I need to restock. How would I be able to update a window of rows to add the amount in an iterable way? There's no real way to use vectoring/loc because there are functions reliant on data for that current row Example: date dvd avail rented buy more? 1/1/2018 a 10 2 N 1/1/2018 b 20 4 N 1/2/2018 a 11 3 N 1/2/2018 b 28 2 N 1/3/2018 a 14 5 N 1/3/2018 b 28 6 N What I need: date dvd avail rented rolling_rentals buy more? bought 1/1/2018 a 10 2 0 N 0 1/1/2018 b 20 4 0 N 0 1/2/2018 a 9 3 2 Y 1 1/2/2018 b 24 2 4 N 0 1/3/2018 a 9 5 5 Y 1 1/3/2018 b 22 6 6 N 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92163094
tagged with: lambda
has comment: http://stackoverflow.com/comment/92167441
has comment: http://stackoverflow.com/comment/92167372
has comment: http://stackoverflow.com/comment/92164091
tagged with: loops
has comment: http://stackoverflow.com/comment/92163132
type: Question
has comment: http://stackoverflow.com/comment/92163805
has comment: http://stackoverflow.com/comment/92164166
score: 0
tagged with: pandas
tagged with: python
has title: How to iterate over Pandas rows while updating a series of rows based on a loc condition?

http://stackoverflow.com/comment/92218123
comment on: http://stackoverflow.com/q/52639543
score: 0
type: QuestionComment
type: Comment
has text: And is there another way to extract tables from pdf in python. Appreciate the help!

http://stackoverflow.com/comment/92297113
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52684644
has text: Right. One usual way is to multiply tolerance with `max(abs(a), abs(b))`
type: Comment

http://stackoverflow.com/comment/94201273
type: AnswerComment
has text: If you choose to scale horizontally, you could start more instances and configure a few spiders to run on them thus dividing the load. One strategy could be that the largest spiders gets an instance of its own, while the rest of them keep running on the monolithic system. Also, you could choose to take the database out and run it on a separate instance too, with which all the spiders connect.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52643555

tkinter
tags question: http://stackoverflow.com/q/52611032
tags question: http://stackoverflow.com/q/52645542
tags question: http://stackoverflow.com/q/52664005
tags question: http://stackoverflow.com/q/52726745
tags question: http://stackoverflow.com/q/52623056
tags question: http://stackoverflow.com/q/52697394
tags question: http://stackoverflow.com/q/52634921
tags question: http://stackoverflow.com/q/52675162
tags question: http://stackoverflow.com/q/52741723
tags question: http://stackoverflow.com/q/52669006
tags question: http://stackoverflow.com/q/52709289
tags question: http://stackoverflow.com/q/52594951
tags question: http://stackoverflow.com/q/52662321
tags question: http://stackoverflow.com/q/52645557
tags question: http://stackoverflow.com/q/52654504
tags question: http://stackoverflow.com/q/52706538
tag name: tkinter
tags question: http://stackoverflow.com/q/52724369
tags question: http://stackoverflow.com/q/52727332
tags question: http://stackoverflow.com/q/52616268
tags question: http://stackoverflow.com/q/52745321
tags question: http://stackoverflow.com/q/52649477
tags question: http://stackoverflow.com/q/52708118
tags question: http://stackoverflow.com/q/52735664
tags question: http://stackoverflow.com/q/52596847
tags question: http://stackoverflow.com/q/52618894
tags question: http://stackoverflow.com/q/52724060
tags question: http://stackoverflow.com/q/52654752
tags question: http://stackoverflow.com/q/52594673
tags question: http://stackoverflow.com/q/52628387
tags question: http://stackoverflow.com/q/52739941
tags question: http://stackoverflow.com/q/52697473
tags question: http://stackoverflow.com/q/52702246
tags question: http://stackoverflow.com/q/52680358
tags question: http://stackoverflow.com/q/52733442
tags question: http://stackoverflow.com/q/52716922
tags question: http://stackoverflow.com/q/52659769
tags question: http://stackoverflow.com/q/52595293
tags question: http://stackoverflow.com/q/52659268
tags question: http://stackoverflow.com/q/52742882
tags question: http://stackoverflow.com/q/52696075
tags question: http://stackoverflow.com/q/52683773
tags question: http://stackoverflow.com/q/52593557
tags question: http://stackoverflow.com/q/52609819
tags question: http://stackoverflow.com/q/52678369
tags question: http://stackoverflow.com/q/52727527
tags question: http://stackoverflow.com/q/52632997
tags question: http://stackoverflow.com/q/52643763
tags question: http://stackoverflow.com/q/52605323
tags question: http://stackoverflow.com/q/52664255
tags question: http://stackoverflow.com/q/52732765
tags question: http://stackoverflow.com/q/52648384
tags question: http://stackoverflow.com/q/52617975
tags question: http://stackoverflow.com/q/52635228
tags question: http://stackoverflow.com/q/52690173
tags question: http://stackoverflow.com/q/52738511
tags question: http://stackoverflow.com/q/52679038
tags question: http://stackoverflow.com/q/52679654
tags question: http://stackoverflow.com/q/52708678
tags question: http://stackoverflow.com/q/52708418
tags question: http://stackoverflow.com/q/52670729
tags question: http://stackoverflow.com/q/52679159
tags question: http://stackoverflow.com/q/52667640
tags question: http://stackoverflow.com/q/52665546
tags question: http://stackoverflow.com/q/52642355
tags question: http://stackoverflow.com/q/52681613
tags question: http://stackoverflow.com/q/52660289
tags question: http://stackoverflow.com/q/52673683
tags question: http://stackoverflow.com/q/52653065
tags question: http://stackoverflow.com/q/52688867
tags question: http://stackoverflow.com/q/52728609
tags question: http://stackoverflow.com/q/52646089
tags question: http://stackoverflow.com/q/52739334
tags question: http://stackoverflow.com/q/52594774
tags question: http://stackoverflow.com/q/52693019
tags question: http://stackoverflow.com/q/52605469
tags question: http://stackoverflow.com/q/52656336
tags question: http://stackoverflow.com/q/52725403
tags question: http://stackoverflow.com/q/52652616
tags question: http://stackoverflow.com/q/52711885

http://stackoverflow.com/q/52620784
has comment: http://stackoverflow.com/comment/92175332
has answer: http://stackoverflow.com/a/52620884
answer count: 4
has comment: http://stackoverflow.com/comment/92175358
has answer: http://stackoverflow.com/a/52620859
has answer: http://stackoverflow.com/a/52620902
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92175298
linked to: http://stackoverflow.com/q/52603288
has comment: http://stackoverflow.com/comment/92175469
has comment: http://stackoverflow.com/comment/92175349
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92175264
tagged with: django-views
has title: Django auto assign value to foreign key when a form is submitted?
score: 1
has body: I want to render the name of the company into the database automatically whenever user submits the create form... This is my model: class company(models.Model): User = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True) Name = models.CharField(max_length=50,blank=False) class group1(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) group_Name = models.CharField(max_length=32) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Company_group') This is what I was trying to do in my views.py: class group1CreateView(LoginRequiredMixin,CreateView): form_class = group1Form template_name = "accounting_double_entry/group1_form.html" def form_valid(self, form): form.instance.User = self.request.user form.instance.Company = company return super(group1CreateView, self).form_valid(form) But got this error: ValueError: Cannot assign "&lt;class 'company.models.company'&gt;": "group1.Company" must be a "company" instance. It worked for the User but is not working for the Company.. Can anyone tell me what I am doing wrong in this??? Thank you...
tagged with: django-models
tagged with: django-forms
type: Question
possible better answer: http://stackoverflow.com/a/52620859
has answer: http://stackoverflow.com/a/52620836
accepted answer: http://stackoverflow.com/a/52620836
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/92119911
type: QuestionComment
has text: Ok, I will come up with an example of what I think you are asking for then and hopefully this will at least lead you in the right direction.
comment on: http://stackoverflow.com/q/52592298
score: 0
type: Comment

wifi
tag name: wifi
type: Tag
tags question: http://stackoverflow.com/q/52652339
tags question: http://stackoverflow.com/q/52670151

http://stackoverflow.com/q/52650041
answer count: 2
upvote count: 0
has body: I have a dataframe in pandas, with a column which is a vector: df = pd.DataFrame({'ID':[1,2], 'Averages':[[1,2,3],[4,5,6]]}) and I wish to split and divide it into elements which would look like this: df2 = pd.DataFrame({'ID':[1,2], 'A':[1,4], 'B':[2,5], 'C':[3,6]}) I have tried df['Averages'].astype(str).str.split(' ') but with no luck. any help would be appreciated.
tagged with: dataframe
score: -1
accepted answer: http://stackoverflow.com/a/52650082
tagged with: pandas
has title: python split pandas numeric vector column into multiple columns
favorite count: 0
linked to: http://stackoverflow.com/q/35491274
tagged with: python
duplicate of: http://stackoverflow.com/q/35491274
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52650082
possible better answer: http://stackoverflow.com/a/52650099
has answer: http://stackoverflow.com/a/52650099
type: Question

http://stackoverflow.com/a/52680862
has comment: http://stackoverflow.com/comment/92290174
score: 1
accepted answer of: http://stackoverflow.com/q/52680772
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52680772
has comment: http://stackoverflow.com/comment/92312857
type: Answer
has body: Simply add the given number to a sum until it's string only contains 0 and 1: # you already solved the input part, so skipping it here n = 34 summed = n allowed = {"0","1"} while set(str(summed)) - allowed: # @MadPhysicists suggestion instead of # any(x not in allowed for x in str(summed)): summed += n else: print(summed) Output: 111010 No idea, but my guess would be that adding is faster then multiplying in the long run.
upvote count: 1
has comment: http://stackoverflow.com/comment/92300714

http://stackoverflow.com/a/52707826
score: 1
has body: Keras layers, and tf.keras.layers layers, support get_weights / set_weights methods, which return numpy arrays for the weights. So you can call get_weights, modify the result in numpy, and call set_weights back to put the new numpy values into tensorflow. Something like this: model = tf.keras.Sequential(...) for batch in data: model.fit(batch) if ...: weights_as_numpy = model.get_weights() # modify the weights model.set_weights(weights_as_numpy)
has comment: http://stackoverflow.com/comment/92406509
accepted answer of: http://stackoverflow.com/q/52702220
answers question: http://stackoverflow.com/q/52702220
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92404930
type: Answer

http://stackoverflow.com/q/52727998
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/92381649
has comment: http://stackoverflow.com/comment/92382088
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92381463
type: Question
has body: I'm having difficulty getting my dataframe data into their own timeseries. Here is my code so far: data = pd.read_csv(s3_data_path, index_col=0, parse_dates=True, dtype="float64") num_timeseries = data.shape[1] print("This is the number of time series you're running:") print(num_timeseries) data_length = num_timeseries t0 = data.index[0] print("This is the beginning date:") print(t0) time_series=[] for i in range(num_timeseries): index = pd.DatetimeIndex(start=t0, freq=freq, periods=data_length) time_series.append(pd.Series(data=data.iloc[:,i], index=index)) print(data.head(10)) print(time_series[0] Whenever I run print(data.head(10)) I see the following, which is what I expect: However, my time_series object has values of NaN: I don't quite understand what I'm missing to get the correct values in my time_series object. Thanks for the help! Edit--- Whenever I remove the index=index out of my time_series.append the code generates my expected result (pictured below.) However, this creates an issue as no frequency is defined which is a requirement.
has comment: http://stackoverflow.com/comment/92381769
has comment: http://stackoverflow.com/comment/92381519
has comment: http://stackoverflow.com/comment/92381606
has comment: http://stackoverflow.com/comment/92381887
has title: Pandas series append returning NaN values
score: 0

http://stackoverflow.com/comment/92397649
has text: And what about simply: `lines = stdout.split('\n')[1:10]`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52736034
score: 0

http://stackoverflow.com/q/52699163
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: Convert conv2d into tf.nn.separable_conv2d running into memory error
score: 1
favorite count: 0
type: Question
has body: I am currently trying to make my network a little bit faster by using separable convolutions instead of regular ones. One remark dont get confused by the additional code snippets. They are put there to emphesise the problem. My guess is I build the depthwise and pointwise conv the wrong way but I have no clue how I can use it otherwise. THanks in advance! I used the code below with my regular convolutions as an input I give a (1,800,800,3) input and use a 3x3 kernel and 32 filters. Both methods have the same syntax def conv(input, kernel_size, filters, stride, is_training, batchnorm=True, activation=tf.nn.relu, name="conv"): afterwards I define my variables w and b and batch norm. with tf.variable_scope(name): weights = tf.get_variable('weights', shape=[kernel_size, kernel_size, input.get_shape()[3], filters], initializer=tf.contrib.layers.xavier_initializer() ) biases = tf.get_variable('biases', shape=[filters], initializer=tf.constant_initializer(0.0) ) conv = tf.nn.conv2d(input, weights, strides=[1, stride, stride, 1], padding='SAME') output = tf.nn.bias_add(conv, biases) if batchnorm: output = tf.layers.batch_normalization(output, training=is_training, center=True, scale=False) if activation is not None: output = activation(output) return output Until here everything works as expected and when I run my code i can train my network. Now I tried to derive a separate convolution using the tf.nn.separable_conv2d Therefore I used with tf.variable_scope(name): weights = tf.get_variable('weights', shape=[kernel_size, kernel_size, input.get_shape()[3], filters], initializer=tf.contrib.layers.xavier_initializer()) pointwise_filter = tf.get_variable("pointwise_filter",shape = [1,1,input.get_shape()[3]*filters, filters], initializer = tf.contrib.layers.xavier_initializer()) biases = tf.get_variable('biases', shape=[filters], initializer=tf.constant_initializer(0.0) ) conv = tf.nn.separable_conv2d(input, weights, pointwise_filter, strides=[1, stride, stride, 1], padding='SAM…
tagged with: python
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/92379462
type: QuestionComment
has text: Waaay too much code. You can research the error and start tracing it back.
comment on: http://stackoverflow.com/q/52726959
type: Comment
score: 1

http://stackoverflow.com/comment/92425133
comment on: http://stackoverflow.com/a/52740973
type: Comment
has text: It definitely does.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92248429
comment on: http://stackoverflow.com/a/52658923
score: 1
has text: Cool. This answered my question. Thanks a lot.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52636911
tagged with: typeerror
type: Question
tagged with: python
tagged with: discord
has answer: http://stackoverflow.com/a/52637128
score: 0
answer count: 2
tagged with: discord.py
has title: TypeError: format() argument after ** must be a mapping, not Attachment
accepted answer: http://stackoverflow.com/a/52637128
has answer: http://stackoverflow.com/a/52647486
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52647486
has body: Hi I'm trying to fix an issue with a log module with my discord bot. I'm getting the error TypeError: format() argument after ** must be a mapping, not Attachment cogs\core.py", line 351, in on_message_delete delmessage.add_field(name='**Attachment**', value='[{filename}]({url})'.format(**attachment), inline=True) TypeError: format() argument after ** must be a mapping, not Attachment I'm not sure whats causing this. Heres what I'm working with: async def on_message_delete(self, message): guild = message.guild author = message.author bot_member = guild.me time = dt.datetime.utcnow() now = dt.datetime.utcnow() if author.bot: return if not guild: return cleanmsg = message.content for i in message.mentions: cleanmsg = cleanmsg.replace(i.mention, str(i)) name = author name = " ~ ".join((name.name, name.nick)) if name.nick else name.name changes = True if author.id != self.bot.user.id: infomessage = "A message by {} was deleted.".format(message.author.mention, message.channel.mention) delmessage = discord.Embed(description=infomessage, colour=discord.Color.purple(), timestamp=time) delmessage.add_field(name="Message:", value=cleanmsg) delmessage.set_footer(text="ID: {}".format(message.author.id)) delmessage.set_author(name=name + "'s message was deleted.", icon_url=message.author.avatar_url) if message.attachments: for attachment in message.attachments: delmessage.add_field(name='**Attachment**', value='[{filename}]({url})'.format(**attachment), inline=True) await self.bot.send_log_message(guild, embed=delmessage)

http://stackoverflow.com/a/52646730
answers question: http://stackoverflow.com/q/52646581
score: 0
upvote count: 1
type: Answer
has body: One solution is to remove every space then run the regex. import re s='THIS IS 50325/654 A TEST STRING 56 968/325 THIS IS A 65646 TEST 46546/ 564 STRING THIS 259 65/456 IS A TEST 54654/65 4 STRING' t=s.replace(' ','') print(re.findall('\d{5}/\d{3}',t)) #['50325/654', '56968/325', '46546/564', '25965/456', '54654/654'] With the edit I believe if you modify your regex to (?:\D)\d{5}/\d{3}(?!\d) it will only get patterns that don't have an extra number at the beginning or end.
downvote count: 1

http://stackoverflow.com/a/52638313
upvote count: 1
answers question: http://stackoverflow.com/q/52638259
type: Answer
has body: This will filter the list using lambda for x==8. Then any will return True if any items populated the filtered list or False if not print(any(list(filter(lambda x: x == 8, [11, 3, 11, 1, 8, 12])))) # =&gt; True
downvote count: 0
score: 1

http://stackoverflow.com/q/52668547
score: -2
has answer: http://stackoverflow.com/a/52668758
has body: I want to make loop generate from random generator with no duplicate values like below: 1,4 1,2 1,3 1,1 1,7 1,9 1,8 2,5 2,2 2,1 2,3 2,4 2,5 2,7 What I mean is, that there are no duplicated value on the second value for each first value. And the value range for second value is from (1 to 10). My code below still gives duplicated values: import random for i in range(2): for j in range(7): print(i, ',', random.randint(1,10)) any ideas on how to address this problems? Any response really appreciated.
has answer: http://stackoverflow.com/a/52668683
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52668660
has answer: http://stackoverflow.com/a/52668625
has comment: http://stackoverflow.com/comment/92267268
has comment: http://stackoverflow.com/comment/92267005
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/92269449
has title: Generate Random with no repeating numbers
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/92267994
has comment: http://stackoverflow.com/comment/92269145
type: Question

http://stackoverflow.com/comment/92128111
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52595735
has text: Thanks. I thought it was the other way around. Do you know if there's a way to set DEBUG as an upper bound?
type: AnswerComment

http://stackoverflow.com/q/52649191
possible better answer: http://stackoverflow.com/a/52650468
has answer: http://stackoverflow.com/a/52650468
tagged with: python
tagged with: nearest-neighbor
tagged with: scipy-spatial
type: AnsweredQuestion
has title: Find 10 closest points in decreasing order
score: 0
tagged with: scipy
type: Question
has body: I am trying to find the distance between a point and other 40,000 points. Each point is a 300 dimension vector. I am able to find the closes point. How do I find the 10 nearest points in decreasing order? Function for closest point: from scipy.spatial import distance def closest_node(node,df): closest_index = distance.cdist([node],df.feature.tolist()).argmin() return pd.Series([df.title.tolist([closest_index],df.id.tolist()[closest_index]]) This command returns the closest title and id: df3"closest_title","closest_id"=df3.feature.apply(lambda row: closest_node(row,df2)) df2- pandas dataframe of 40,000 points (each 300 dimension) How do I return the title and index for the 10 closest points Thanks
has answer: http://stackoverflow.com/a/52650820
tagged with: distance
answer count: 2
accepted answer: http://stackoverflow.com/a/52650820

http://stackoverflow.com/a/77092793
has body: It has resolved to use the builtin function # Display each DICOM slice for i, dcm in enumerate(dicom_files): img = dcm.pixel_array img2 = dcm.ImagePositionPatient # height, width, depth = dcm.shape # print(f"dcm {i + 1} - Size: Height: {height}, Width: {width}, Depth: {depth}") plt.figure(figsize=(6, 6)) plt.imshow(dcm.pixel_array, cmap='gray') plt.title(f"Slice {i + 1}") plt.axis('off') plt.show()
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52708245

http://stackoverflow.com/q/52622343
has answer: http://stackoverflow.com/a/52626700
score: 2
linked to: http://stackoverflow.com/q/36456436
upvote count: 2
accepted answer: http://stackoverflow.com/a/52626700
tagged with: gradient
linked to: http://stackoverflow.com/q/43256517
tagged with: tensorflow
type: AnsweredQuestion
type: Question
has body: Although there are many references showing how to register a gradient, but I'm still not very clear what exactly kind of gradient need to be defined. Some similar topics: How to register a custom gradient for a operation composed of tf operations How Can I Define Only the Gradient for a Tensorflow Subgraph? Okay, here comes my question: I have a forward function y = f(A,B), where the size of each of them are: y: (batch_size, m, n) A: (batch_size, a, a) B: (batch_size, b, b) Suppose I can write down the mathematical partial derivatives of every element of y with respect every element of A and B. dy/dA, dy/dB. My question is what should I return in the gradient function? @ops.RegisterGradient("f") def f_grad(op, grad): ... return ???, ??? Here says that The result of the gradient function must be a list of Tensor objects representing the gradients with respect to each input. It is very easy to understand the gradient to be defined when y is scalar and A, B are matrix. But when y is matrix and A, B are also matrix, what should that gradient be?
has title: Tensorflow: What gradients needed to be defined for custom operation?
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python

http://stackoverflow.com/a/52646658
has comment: http://stackoverflow.com/comment/92228531
score: 2
has comment: http://stackoverflow.com/comment/92225417
downvote count: 0
answers question: http://stackoverflow.com/q/52646571
has body: well actually when you do: i == range(7, 98, 10) you are comparing an integer with a iterable. So this condition always evaluates to False. What you want to do is to check whether the string representation of you number contains 7. You can do: '7' in str(i) So globally, you could write the following: for i in range(0, 101): if i % 7 == 0 or '7' in str(i): print i
upvote count: 2
has comment: http://stackoverflow.com/comment/92225629
type: Answer

http://stackoverflow.com/comment/92310455
type: Comment
has text: Hi @sraw, thanks for the feedback. Do I understand correctly that I must not import the module in `conf.py`? As for the rest: The module needs to have some user input to save their API Key. How would you solve the problem?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52690039

http://stackoverflow.com/q/52729686
favorite count: 0
score: 11
has comment: http://stackoverflow.com/comment/94131217
linked to: http://stackoverflow.com/q/12671944
linked to: http://stackoverflow.com/q/27093746
has comment: http://stackoverflow.com/comment/92515646
has comment: http://stackoverflow.com/comment/92515505
has comment: http://stackoverflow.com/comment/94131305
upvote count: 11
has comment: http://stackoverflow.com/comment/92515126
answer count: 0
has comment: http://stackoverflow.com/comment/92515341
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92515214
has comment: http://stackoverflow.com/comment/94131863
tagged with: django
has comment: http://stackoverflow.com/comment/92515151
tagged with: python
has title: Django Error on Travis: RuntimeError: populate() isn't reentrant
has comment: http://stackoverflow.com/comment/92515095
has comment: http://stackoverflow.com/comment/101279486
has comment: http://stackoverflow.com/comment/92515612
has comment: http://stackoverflow.com/comment/92677324
has comment: http://stackoverflow.com/comment/92515842
has comment: http://stackoverflow.com/comment/92515111
has comment: http://stackoverflow.com/comment/92515170
type: Question
tagged with: continuous-integration
has comment: http://stackoverflow.com/comment/101731760
has comment: http://stackoverflow.com/comment/92515526
downvote count: 0
has body: I am maintaining a project, with Travis CI implemented, and from one day. All my builds start failing without me touching anything or any dependence update ... I guess that Travis changed something, I tried to investigate, but honestly I have no clue. If I run a previous build which perfectly worked, now it fails with this everytime I call python manage.py ##whatever## $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 35, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/django/apps/registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant By the way, I obtain the exact same error with Python 3.6 and 3.5. $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 35, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/django/apps/registry.py", line 81, in populate raise Run…
has comment: http://stackoverflow.com/comment/92515519
tagged with: travis-ci

http://stackoverflow.com/a/52716301
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92446366
type: Answer
answers question: http://stackoverflow.com/q/52715103
upvote count: 2
has body: As I wrote in the comments to my question, I've found a working solution. I'm not 100% sure, it's the correct one (at least for the part relating to the manual editing the .ui file) but I get the dialog to show up and behave the way I was expecting. First I had to modify the XML in the .ui file and use two different class names in the .py and .ui files. I've modified the one in the .ui to be named AlertDialog and to be of type Dialog instead of QDialog. I could not find a way to modiffy the type in Qt Designer. 3,4c3,4 < Dialog < <widget class="QDialog" name="Dialog"> --- > AlertDialog > <widget class="Dialog" name="AlertDialog"> 18c18 < <widget class="QLineEdit" name="lineEdit"/> --- > <widget class="QLineEdit" name="text_field"/> 66c66 < Dialog --- > AlertDialog As you see above, there was also a small typo in the name of the input box: that was the reason why, I got the .ui file pasted in the question!). In the Python code I simply had to correctly decorate my function as a Slot. Here is the full code: from PySide2.QtWidgets import QApplication from PySide2.QtWidgets import QDialog, QMessageBox from PySide2.QtCore import QFile, Slot from PySide2.QtUiTools import QUiLoader class Dialog(QDialog): def __init__(self, parent = None): super(Dialog, self).__init__(parent) @Slot() def alert(self): alert = QMessageBox() alert.setText(self.text_field.text()) alert.exec_() if __name__ == '__main__': app = QApplication([]) loader = QUiLoader() loader.registerCustomWidget(Dialog) ui_file = QFile('alert-quit.ui') ui_file.open(QFile.ReadOnly) dialog = loader.load(ui_file) ui_file.close() dialog.show() app.exec_() Neat, isn't it? If anybody (my future self included...) knows how to get rid of the .ui tweaking or has otherwise improvements to this solutions, your comments are very welcome!

http://stackoverflow.com/comment/92322309
comment on: http://stackoverflow.com/q/52697909
type: Comment
score: 0
type: QuestionComment
has text: Note: Python uses the name `list`, not `array`, for the mutable sequence data structure. There is a [separate `array` module](https://docs.python.org/3/library/array.html) supporting a single numeric type for each value only.

http://stackoverflow.com/comment/92308145
type: Comment
type: QuestionComment
has text: Just so you know, you can accept only one answer. Be sure you select the one you believe is the best.
comment on: http://stackoverflow.com/q/52690468
score: 0

http://stackoverflow.com/q/52638068
type: Question
tagged with: if-statement
has title: about half of my if statements not working properly
tagged with: printing
has body: I am to make a python program using basic operators to ask for an income from the user, in order to calculate the 2017 progressive tax along with 2018. The output should look like this: Income: 15000 2017 tax: (tax amount here) #will skip the math for samples 2018 tax: (tax amount here) My program as of now produces both prints for 2017 / 2018 but will stop at the 2018 nested if bracket of 82501 to 157500 (which is nested in the 4th elif)... Here's my program as of now, since its long I'll mark out where it stops working. income = float(input("Enter your income to calculate tax: ")) #Loop input/calculations while income &gt; 0: print("----------------------------------------------") if income &gt;= 0 and income &lt;= 9325: bracket1 = income * 0.10 tax2017 = bracket1 print("Income: ",income) print("2017 tax: ",format(tax2017,'.2f')) if income &gt;= 0 and income &lt;= 9525: newbracket1 = income * 0.10 tax2018 = newbracket1 print("2018 tax: ",format(tax2018,'.2f')) income = float(input("\nEnter your income as and integer with no commas: ")) elif income &gt;= 9326 and income &lt;= 37950: bracket1 = 9325 * 0.10 bracket2 = (income - 9326) * 0.15 tax2017 = bracket1 + bracket2 print("Income: ",income) print("2017 tax: ",format(tax2017,'.2f')) if income &gt;= 9526 and income &lt;=38700: newbracket1 = 9526 * 0.10 newbracket2 = (income - 9525) * 0.12 tax2018 = newbracket1 + newbracket2 print("2018 tax: ",format(tax2018,'.2f')) income = float(input("\nEnter your income as and integer with no commas: ")) elif income &gt;= 37951 and income &lt;= 91900: bracket1 = 9325 * 0.10 bracket2 = (37950 - 9325) * 0.15 bracket3 = (income - 37951) * 0.25 tax2017 = bracket1 + bracket2 + bracket3 print("Income: ",income) print("2017 tax: ",format(tax2017,'.2f')) if income &gt;= 38701 and income &lt;= 82500: newbracket1 = 9526 * 0.10 newbracket2 = (38700 - 9526) * 0.12 newbracket3 = (income - 38700) * 0.22 tax2018 = newbracket1 + newbracket2 + newbracket3 print("2018 tax: ",format(tax2018,'.2f')…
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/92209091
accepted answer: http://stackoverflow.com/a/52638116
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52638116
has comment: http://stackoverflow.com/comment/92209035
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92209041
downvote count: 0
score: 1

http://stackoverflow.com/a/52729725
has comment: http://stackoverflow.com/comment/92384980
has comment: http://stackoverflow.com/comment/92385002
has comment: http://stackoverflow.com/comment/92384654
downvote count: 0
has comment: http://stackoverflow.com/comment/92384686
has comment: http://stackoverflow.com/comment/92384926
score: 3
answers question: http://stackoverflow.com/q/52729650
has comment: http://stackoverflow.com/comment/92384596
has comment: http://stackoverflow.com/comment/92384835
has comment: http://stackoverflow.com/comment/92384614
has comment: http://stackoverflow.com/comment/92385042
has comment: http://stackoverflow.com/comment/92385054
has body: I'd like to suggest an alternative. You can initialise both a and b on the same line: with A() as a, B() as b: do_things() This is more concise and reduces the amount of indentation in deeply nested code. However, if you absolutely must use a class, then override the __enter__ and __exit__ methods: class C: def __enter__(self): self._a = A() self._b = B() return (self._a.__enter__(), self._b.__enter__()) def __exit__(self ,type, value, traceback): # Cleanup code here. self._b.__exit__(type, value, traceback) self._a.__exit__(type, value, traceback) And then use C inside a context manager like this: with C() as (a, b): do_things() If you don't want to reference a and b, or if you don't plan on doing anything with them, then with C(): do_things() Will also work. This should be enough to get started, but please note there are drawbacks as kindly mentioned by users in the comments. The main one being that if self._b.__enter__ throws errors, self._a.__enter__ will need to be cleaned up (this can be done using try-except-finally). Furthermore, some context managers may need to be treated differently based on what resource is being managed.
has comment: http://stackoverflow.com/comment/92384636
has comment: http://stackoverflow.com/comment/92385024
upvote count: 3
has comment: http://stackoverflow.com/comment/92384790
type: Answer

http://stackoverflow.com/comment/92326962
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52698797
has text: @usr2564301 Agree.
type: Comment

http://stackoverflow.com/a/52610482
score: 0
answers question: http://stackoverflow.com/q/52610116
type: Answer
has body: The error is occurring because the CSV reader encounters lines that are of a different width than the header row (which it assumes to be the first row). To avoid this, tell it that the data has no header and instead to name the columns based on a numbered range: df = pd.read_csv(file, header=None, names=range(20)) (Replace 20 with the maximum width of your data.) If necessary you can later relabel your column headings using df.columns=..., and if you need to drop the first row of data (because it contains headings rather than data), use df = df.drop(0). To shift the misplaced cells to the left, you will need to do something like the following: import numpy as np ... df.loc[~np.isnan(df[19]), [17, 18]] = df[[19, 20]] This will replace columns 17 and 18 with columns 19 and 20 in rows where the cell in column 19 is not empty.

http://stackoverflow.com/comment/92344696
has text: are you looking for the `break` control flow statement?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52708813

http://stackoverflow.com/comment/92262219
type: Comment
comment on: http://stackoverflow.com/a/52666053
has text: Thanks. Do you know how to convert numbers like `1.29E+3` into `1290` since the latter is the output format in the problem.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92157138
score: 0
has text: Even if you use a list you still have to do the addition eventually. The addition itself is pretty fast, creating a new Python integer object eventually gets slow when the number has thousands of digits. But that's not an issue here.
type: AnswerComment
comment on: http://stackoverflow.com/a/52610992
type: Comment

http://stackoverflow.com/a/52680728
downvote count: 0
answers question: http://stackoverflow.com/q/52679150
type: Answer
upvote count: 1
score: 1
has body: The simplest and easiest solution would be to opt for .replace() function. All you need to do is kick out this signs from the html elements and the rest are as it is. Take a look at the below script. from bs4 import BeautifulSoup htdoc = """ """ elem = htdoc.replace(" ","") soup = BeautifulSoup(elem,'lxml') views = soup.select_one('span.views').get_text(strip=True) likes = soup.select_one('span.interaction')['likes'] print(f'{views}\n{likes}') Output: 1.56M Clicks 0

http://stackoverflow.com/comment/92213322
comment on: http://stackoverflow.com/q/52639703
has text: Possible duplicate of [AES-128 CBC decryption in Python](https://stackoverflow.com/questions/46904355/aes-128-cbc-decryption-in-python)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92367904
comment on: http://stackoverflow.com/a/52721369
has text: Thank you! fabio.avigo, what are the other issues? thanks
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92271897
type: QuestionComment
comment on: http://stackoverflow.com/q/52671019
score: 0
has text: I'm confused what you're asking. Delete the script?
type: Comment

http://stackoverflow.com/comment/92251903
type: AnswerComment
has text: So the code would be: jpype.startJVM(jpype.getDefaultJVMPath(), "-ea","-Xmx1024m" ,"-Djava.class.path=" + jarLocation)
type: Comment
comment on: http://stackoverflow.com/a/52644796
score: 0

http://stackoverflow.com/comment/92295830
comment on: http://stackoverflow.com/q/52683825
has text: const { spawn } = require('child_process'); const ls = spawn('python', ['./HackRU2018/face_detect.py']); I called my python script using this. When clicking a button from web page, I want to run multiple files. The webcam seems to work for just a second, and the webcam light goes off.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52669761
score: 1
favorite count: 0
type: Question
answer count: 2
upvote count: 1
tagged with: python
tagged with: airflow-scheduler
has answer: http://stackoverflow.com/a/52673177
has body: I am trying to schedule tasks in airflow but apparently it's not so obvious. The task I want to run is pretty simple, here is the DAG configuration: from datetime import datetime from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators.python_operator import PythonOperator def print_hello(): return 'Hello world!' dag = DAG('hello_world', description='Simple tutorial DAG', schedule_interval='30 15 * * *', start_date=datetime(2018, 10, 3), catchup=False) dummy_operator = DummyOperator(task_id='dummy_task', retries=3, dag=dag) hello_operator = PythonOperator(task_id='hello_task', python_callable=print_hello, dag=dag) dummy_operator &gt;&gt; hello_operator It means I want to run it every day at 15:30. If I put this task ON today, for instance, it doesn't trigger at 15:30, but will trigger tomorrow at this time. This is related to the idea of left-border of the interval of execution (quite a strange feature of Airflow). So the question is: How to trigger the task exactly today at 15:30 and not tomorrow at the end of the execution interval? Any suggestions or clarifications would be appreciated.
has title: How to correctly set Airflow scheduler
tagged with: airflow
tagged with: scheduler
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52671300
downvote count: 0

http://stackoverflow.com/q/52707091
has body: With the Python igraph library, I have a directed graph representing a road network, with distance between each vertex (coordinates) as the weight. It is quite possible that there can be two or more edges between a vertex pair, with different weights. I need to retrieve these weights from the graph by querying the vertex IDs e.g. an example graph: import igraph as ig g = ig.Graph(directed=True) g.add_vertices(4) edges = [(0, 1), (1, 2), (1, 2), (2, 3)] g.add_edges(edges) g.es[:]["dist"] = [1, 2, 3, 4] I know I can get the id of an edge, and then the attributes as follows, but this only seems to find the last added e.g: g.get_eid((0, 1)) # returns 0 g.get_eid((1, 2)) # returns 2 So, there are two edges between 1 and 2, but only one is returned by get_eid - I need to know both to then query the edge attributes and return the weightings, to select the correct minimum distances from the graph, as were used by a distance-weighted shortest path query. Is there a way to do this with igraph?
score: 2
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/52731003
tagged with: python
tagged with: igraph
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76842450
has answer: http://stackoverflow.com/a/67871994
type: Question
downvote count: 0
possible better answer: http://stackoverflow.com/a/67871994
has answer: http://stackoverflow.com/a/52731003
has title: Find IDs of all edges between vertexes with igraph Python
answer count: 3

http://stackoverflow.com/comment/92412402
score: 0
comment on: http://stackoverflow.com/q/52743921
has text: Try to format your answer please
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52694907
has comment: http://stackoverflow.com/comment/92316729
answers question: http://stackoverflow.com/q/52694844
has comment: http://stackoverflow.com/comment/92316549
score: 0
has body: First of all, it's not Flask or Django that does such a thing! The one that you used with Flask is SQL-Alchemy and The one that you used with Django is Django ORM, You can use them standalone without a Flask or Django Project! On both snippets, You are assigning an object to a variable! obj = User.objects.filter(uname=username,pwd=password) is equal to MySQL query SELECT * FROM users WHERE uname = &lt;username&gt; AND pwd = &lt;password&gt;; while obj = User.query.filter(User.uname == username, User.pwd == password).first() is equal to MySQL query SELECT * FROM users WHERE uname = &lt;username&gt; AND pwd = &lt;password&gt; LIMIT BY 1; So the Django ORM one will return an iterable of rows that met our condition! You can use all() instead of first() on SQL-Alchemy and get the same result like Django ORM! There is a method called filter_by() on SQL-Alchemy which seems more like your Django ORM example, It still gets only one or 404 if you use first() at the end, But you can set condition without condition operators but by assigning them on method parameters, like: obj = User.query.filter_by(uname=username, pwd=password).first() Check this StackOverflow Question for more information about filter vs filter_by on SQL-Alchemy
type: Answer
has comment: http://stackoverflow.com/comment/92316576

http://stackoverflow.com/comment/92418709
type: QuestionComment
score: 1
has text: Can you make sure that the indentation is exactly the one of your code?
comment on: http://stackoverflow.com/q/52747073
type: Comment

http://stackoverflow.com/a/52625286
downvote count: 0
has body: The issue is in how bash passes the arguments. Python has nothing do to with it. So, you have to solve all these stuff before sending it to Python, I decided to use awk and xargs for this. (but xargs is the actual MVP here.) LINE=$(cat $tmp_file) awk -v ORS="\0" -v FPAT='"[^"]+"' '{for (i=1;i&lt;=NF;i++){print substr($i,2,length($i)-2)}}' &lt;&lt;&lt;$LINE | xargs -0 python ./script.py First $(..) is preferred over backticks, because it is more readable. You are making a variable after all. awk only reads from stdin or a file, but you can force it to read from a variable with the &lt;&lt;&lt;, also called "here string". With awk I loop over all fields (as defined by the regex in the FPAT variable), and print them without the "". The output record separator I choose is the NULL character (-v ORF='\0'), xargs will split on this character. xargs will now parse the piped input by separating the arguments on NULL characters (set with -0) and execute the command given with the parsed arguments. Note, while awk is found on most UNIX systems, I make use of FPAT which is a GNU awk extension and you might not be having GNU awk as default (for example Ubuntu), but gnu awk is usually just a install gawk away. Also, the next command would be a quick and easy solution, but generally considered as unsafe, since eval will execute everything it receives. eval "python ./script "$LINE
type: Answer
answers question: http://stackoverflow.com/q/52623323
upvote count: 1
score: 1

http://stackoverflow.com/a/52703779
has body: The matplotlib event handling tutorial gives a good introduction into events. Here, I see two options: Create new figure on click You can create a figure inside a callback to a button_press_event. Depending on which axes has been clicked you may recreate the same plot inside the new figure. import matplotlib.pyplot as plt import numpy as np def create_plot(num, ax=None): ax = ax or plt.gca() t = np.linspace(0,2*np.pi,101) ax.plot(t, np.sin(num*t), label="Label {}".format(num)) ax.legend() fig, axes = plt.subplots(5,4) for i,ax in enumerate(axes.flat): create_plot(i, ax=ax) def create_fig(evt): if evt.inaxes: newfig, newax = plt.subplots() num = fig.axes.index(evt.inaxes) create_plot(num, ax=newax) newfig.show() fig.canvas.mpl_connect("button_press_event", create_fig) plt.show() Zoom within the Figure. You may perform all actions within the same figure. The idea would be, once a click occurs to, set all but the clicked axes invisible and make the clicked axes fill the entire subplotgrid's space. Another click on the single axes, turns all axes visible again and positions the axes back to its original position. The advantage is that you do not need to recreate any plots. import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec fig, axes = plt.subplots(5,4) for i,ax in enumerate(axes.flat): ax.plot(np.arange(20), np.cumsum(np.random.randn(20)), label="Label {}".format(i)) ax.legend() gs = GridSpec(1,1) class Toggle(): def __init__(self): self.all_visible = True self.opos = None def toggle(self,evt): if evt.inaxes: if self.all_visible: for ax in fig.axes: if ax != evt.inaxes: ax.set_visible(False) self.opos = evt.inaxes.get_position() evt.inaxes.set_position(gs[0].get_position(fig)) self.all_visible=False else: for ax in fig.axes: ax.set_visible(True) evt.inaxes.set_position(self.opos) self.all_visible = True self.opos = None fig.canvas.draw_idle() t = Toggle() fig.canvas.mpl_connect("button_press_event", t.toggle) plt.show()
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52701000
has comment: http://stackoverflow.com/comment/92478084
upvote count: 2

http://stackoverflow.com/comment/92397332
comment on: http://stackoverflow.com/q/52735664
score: 0
type: Comment
type: QuestionComment
has text: Thank you all for checking, do you have any idea on how to make it work for Notepad++? Do you require more information?

list-comprehension
tags question: http://stackoverflow.com/q/52618146
tags question: http://stackoverflow.com/q/52719472
tags question: http://stackoverflow.com/q/52683748
tags question: http://stackoverflow.com/q/52653042
tags question: http://stackoverflow.com/q/52698027
tags question: http://stackoverflow.com/q/52614350
tag name: list-comprehension
tags question: http://stackoverflow.com/q/52620865
tags question: http://stackoverflow.com/q/52607864
tags question: http://stackoverflow.com/q/52696711
tags question: http://stackoverflow.com/q/52743695
type: Tag
tags question: http://stackoverflow.com/q/52737997
tags question: http://stackoverflow.com/q/52724172
tags question: http://stackoverflow.com/q/52718194
tags question: http://stackoverflow.com/q/52633247
tags question: http://stackoverflow.com/q/52649823
tags question: http://stackoverflow.com/q/52711122
tags question: http://stackoverflow.com/q/52731355
tags question: http://stackoverflow.com/q/52653278
tags question: http://stackoverflow.com/q/52629423
tags question: http://stackoverflow.com/q/52743344
tags question: http://stackoverflow.com/q/52719830
tags question: http://stackoverflow.com/q/52655834

http://stackoverflow.com/q/52735653
has body: i don't understand why this one is not working: df = pd.read_csv("EXAMPLE_2.csv",sep=';') df.head() then i use: df=df.fillna(df.mean()) I would expect to have the yellow NaN values replaced with the mean of the column but I get exactly the same output as before? Thank you, R
has comment: http://stackoverflow.com/comment/92396194
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92396119
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/52735738
has comment: http://stackoverflow.com/comment/92396207
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/92396251
has title: df.fillna(df.mean()) does not work as expected
type: Question
has answer: http://stackoverflow.com/a/52735738

http://stackoverflow.com/q/52739871
has answer: http://stackoverflow.com/a/52740212
has comment: http://stackoverflow.com/comment/92405084
has title: Binary output Python optimization
type: Question
has comment: http://stackoverflow.com/comment/92404910
answer count: 1
favorite count: 0
tagged with: optimization
score: 0
has comment: http://stackoverflow.com/comment/92404494
has comment: http://stackoverflow.com/comment/92405800
tagged with: python
tagged with: binary
tagged with: correlation
has comment: http://stackoverflow.com/comment/92405304
has comment: http://stackoverflow.com/comment/92404673
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92404527
upvote count: 1
has body: I wrote the following code. The objective of this code, is to generate a (binary) column with a given correlation with the first (binary) column. However, it generates a column with the required correlation, but the generated column is not binary. col1 = np.random.randint(2,size=(10,2)) df = pd.DataFrame(col1) corr_intra_semaine =0.61 corr_inter_semaine =0.57 start_1 =0 end_1=1 def f(corr, x, start_1, end_1): y = 0 for k in range(start_1, end_1 + 1): y += abs(corr - pearsonr(df.iloc[:,k] , x)[0]) return y for i in range(1, len(df.columns)): df.iloc[:,i] = minimize(lambda x : f(corr_intra_semaine, x, 0, i-1) , np.random.rand(len(df))).x df The result of this programe is the following 0 - 0.000000 0 - 0.579208 0 - 0.968021 1 - 0.938635 0 - 0.639041 0 - 0.503649 ... What I want is df[:,i] to be a binary vector. That is an output like that 0 - 0 0 - 1 0 - 0 1 - 1 0 - 0 0 - 1 ... Do you have any idea how to solve it?
downvote count: 1

http://stackoverflow.com/a/52603770
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52603515
has comment: http://stackoverflow.com/comment/92142352
has comment: http://stackoverflow.com/comment/92142849
answers question: http://stackoverflow.com/q/52603515
type: Answer
upvote count: 1
has body: The library you are using to read the data stream does not support the rtsp protocol so it will never work, maybe you can use the following instead: import cv2 capture_video = cv2.VideoCapture('rtsp://10.10.111.200/profile2/media.smp') while(True): ret, img = capture_video.read() cv2.imshow('Test', img) if cv2.waitKey(10) == ord('q'): exit(0)
has comment: http://stackoverflow.com/comment/92149381
score: 1
has comment: http://stackoverflow.com/comment/92143048

http://stackoverflow.com/q/52656862
tagged with: python
type: AnsweredQuestion
has title: Python pandas dataframe skipping lines
type: Question
tagged with: dataframe
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52656875
accepted answer: http://stackoverflow.com/a/52656875
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has body: So i have this loop that adds a string to a dataframe. This works fine. However, when I try to add a number in the second column, it skips lines (as you can see in the output).` while counter &lt; 50: #gets just the subreddit name e = str(elem[counter].get_attribute("href")) e = e.replace("https://www.reddit.com/r/", "") e = e[:-1] #e is the subreddit string df = df.append({'Subreddit': e}, ignore_index=True) df = df.append({'Appearances': 1 }, ignore_index=True) print(e) counter = counter + 2 print(df)` output - Subreddit Appearances 0 worldnews NaN 1 NaN 1 2 pics NaN 3 NaN 1 4 aww NaN 5 NaN 1 6 RedditInReddit NaN I know it has something to do with the way I am looping but I can't seem to understand what. Also I have to increment by 2 each time because the subreddits appear twice on the page, and i only need to grab 1.

http://stackoverflow.com/a/52662338
type: Answer
score: 6
has body: This works nicely, from scipy.optimize import minimize # Define the Model model = lambda b, X: b[0] * X[:,0] + b[1] * X[:,1] + b[2] * X[:,2] # The objective Function to minimize (least-squares regression) obj = lambda b, Y, X: np.sum(np.abs(Y-model(b, X))**2) # Bounds: b[0], b[1], b[2] &gt;= 0 bnds = [(0, None), (0, None), (0, None)] # Constraint: b[0] + b[1] + b[2] - 1 = 0 cons = [{"type": "eq", "fun": lambda b: b[0]+b[1]+b[2] - 1}] # Initial guess for b[1], b[2], b[3]: xinit = np.array([0, 0, 1]) res = minimize(obj, args=(Y, X), x0=xinit, bounds=bnds, constraints=cons) print(f"b1={res.x[0]}, b2={res.x[1]}, b3={res.x[2]}") #Save the coefficients for further analysis on goodness of fit beta1 = res.x[0] beta2 = res.x[1] beta3 = res.x[2]
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52589230
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52589230

executemany
tags question: http://stackoverflow.com/q/52730351
type: Tag
tag name: executemany

http://stackoverflow.com/comment/92179599
score: 0
type: QuestionComment
type: Comment
has text: I think you'll find a solution here : [How can I make one python file run another?](https://stackoverflow.com/a/7975511/10196815)
comment on: http://stackoverflow.com/q/52622963

http://stackoverflow.com/a/52638815
has comment: http://stackoverflow.com/comment/92210288
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/92210681
has comment: http://stackoverflow.com/comment/92210455
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52638666
has comment: http://stackoverflow.com/comment/92210348
answers question: http://stackoverflow.com/q/52638666
has comment: http://stackoverflow.com/comment/92210540
type: Answer
has comment: http://stackoverflow.com/comment/92210382
has comment: http://stackoverflow.com/comment/92210338
has body: This code worked fine for me. I saved it as common.py, then ran it from the command line in the directory where common.py is located. Here's the session: C:\temp\so&gt; python common.py enter: common.py common.py The code does the following: - Requests input - If the input is a filename in the working directory, it prints out the filename. - If the input is not a filename in the working directory, it outputs None. Is there something else you want this code to do?

http://stackoverflow.com/a/52632803
score: 0
type: Answer
has body: Perhaps not the most elegant way, but this just solves the problem: Step 1 Data we have: df 'Value' ID_1 ID_2 0 11122222 ABC42123 33333 1 21219299 YOF21233 88821 2 00022011 ERE00091 23124 3 75643311;21233332 ROB21288 99421 4 12412421 POW94277 12231;33221 5 54221721 IRS21231;YOU28137 13123 Step 2 Let's split misbehaving columns df["'Value'_Dupe"] = df["'Value'"].apply(lambda x: x.split(";")[1] if len(x.split(";"))&gt;1 else np.NaN) df["'Value'"] = df["'Value'"].apply(lambda x: x.split(";")[0]) df["ID_1_Dupe"] = df["ID_1"].apply(lambda x: x.split(";")[1] if len(x.split(";"))&gt;1 else np.NaN) df["ID_1"] = df["ID_1"].apply(lambda x: x.split(";")[0]) df["ID_2_Dupe"] = df["ID_2"].apply(lambda x: x.split(";")[1] if len(x.split(";"))&gt;1 else np.NaN) df["ID_2"] = df["ID_2"].apply(lambda x: x.split(";")[0]) df 'Value' ID_1 ID_2 'Value'_Dupe ID_1_Dupe ID_2_Dupe 0 11122222 ABC42123 33333 NaN NaN NaN 1 21219299 YOF21233 88821 NaN NaN NaN 2 00022011 ERE00091 23124 NaN NaN NaN 3 75643311 ROB21288 99421 21233332 NaN NaN 4 12412421 POW94277 12231 NaN NaN 33221 5 54221721 IRS21231 13123 NaN YOU28137 NaN Step 3 Let's combine dupes with original data into single dataframe: df2 = df[pd.notna(df["'Value'_Dupe"])]"'Value'_Dupe","ID_1","ID_2" df2.columns = ["'Value'","ID_1","ID_2"] df3 = df[pd.notna(df["ID_1_Dupe"])]"'Value'","ID_1_Dupe","ID_2" df3.columns = ["'Value'","ID_1","ID_2"] df4 = df[pd.notna(df["ID_2_Dupe"])]"'Value'","ID_1","ID_2_Dupe" df4.columns = ["'Value'","ID_1","ID_2"] df5 = df"'Value'","ID_1","ID_2" df_result = pd.concat([df5,df2,df3,df4]) df_result 'Value' ID_1 ID_2 0 11122222 ABC42123 33333 1 21219299 YOF21233 88821 2 00022011 ERE00091 23124 3 75643311 ROB21288 99421 4 12412421 POW94277 12231 5 54221721 IRS21231 13123 3 21233332 ROB21288 99421 5 54221721 YOU28137 13123 4 12412421 POW94277 33221 Please let me know if this solves your problem.
answers question: http://stackoverflow.com/q/52631416
has comment: http://stackoverflow.com/comment/92219026
has comment: http://stackoverflow.com/comment/92225713

http://stackoverflow.com/q/52684552
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/52697657
accepted answer: http://stackoverflow.com/a/52697657
has body: I recently got a new Mac (macOS 10.14) and am trying to run the video capture method with openCV and python2.7.15. import cv2 cv2.VideoCapture(0) And I am getting the following error message: Abort trap: 6 I have no idea why this is happening, it worked fine on my old computer, my guess is something with camera permissions maybe? Any help would be greatly appreciated.
duplicate of: http://stackoverflow.com/q/52634009
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92537857
upvote count: 1
answer count: 1
tagged with: macos
favorite count: 0
linked to: http://stackoverflow.com/q/52634009
tagged with: python
has title: Python opencv video capture giving abort trap

http://stackoverflow.com/q/52728144
has comment: http://stackoverflow.com/comment/92402251
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52728321
score: 0
has body: I have created an html input in a js script this way: var compte = document.createElement("input"); compte.setAttribute("name", "compte"); I need to retrieve that input value into a django view. Usually, I use the name attribute of the input: num=request.POST['compte'] In this case, it didn't work knowing the html input was created using javascript. So how do I get the value? I'm adding below the whole code. I've actually inserted a new row containing the inputs to the table. {% csrf_token %} Compte Intitulé {% for el in ViewPC_query %} {{ el.Num }} {{ el.Intitule }} Action Créer avant Créer après Créer first child Créer last child Modifier Supprimer {% endfor %} function beforeFunction (element) { var myTable = document.getElementById("myTable"); var currentRow = myTable.insertRow(element.id); var compte = document.createElement("input"); compte.setAttribute("id", "idcompte"); compte.setAttribute("name", "compte"); compte.setAttribute("class", "form-control"); var intitule = document.createElement("input"); intitule.setAttribute("name", "intitule"); intitule.setAttribute("class", "form-control"); var button = document.createElement("button"); button.setAttribute("name", "action" + element.id); button.setAttribute("class", "btn btn-primary dropdown-toggle"); button.setAttribute("data-toggle", "dropdown"); var textnode1 = document.createTextNode("Action"); var textnode2 = document.createTextNode("Enregistrer"); var textnode3 = document.createTextNode("Annuler"); var span = document.createElement("span"); span.setAttribute("class", "caret"); var ul = document.createElement("ul"); ul.setAttribute("class", "dropdown-menu"); var li1 = document.createElement("li"); var li2 = document.createElement("li"); var Enregistrer = document.createElement("a"); Enregistrer.setAttribute("href", "UpdatePC_before"); var Supprimer = document.createElement("a"); Supprimer.setAttribute("href", "{% url 'comptes' %}"); var div = document.createElement("div"); div.setAttribute("class", "drop…
type: Question
has title: Retrieve input value from js script to django view
has comment: http://stackoverflow.com/comment/92381445
tagged with: javascript

http://stackoverflow.com/a/52669618
accepted answer of: http://stackoverflow.com/q/52669226
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52669226
type: Answer
has comment: http://stackoverflow.com/comment/92269352
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92269407
has body: You can calculate a Boolean column and then convert to int: df['Operator'] = df['Score'].diff(-1).lt(0).astype(int)
upvote count: 1

http://stackoverflow.com/q/52709421
tagged with: python
has answer: http://stackoverflow.com/a/52709744
type: AnsweredQuestion
tagged with: urllib
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52709744
possible better answer: http://stackoverflow.com/a/52709784
has title: Importing URL Data comes Under One Index - Python
has answer: http://stackoverflow.com/a/52709784
score: 0
has body: I am trying to import data from the National Oceanic and Atmospheric Association. The data can be downloaded manually in txt format, but I want to download it via Python's urlopen. After importing the data, all columns and rows are inside a single index column, rather a standard dataframe with headers. Any information would be helpful. import pandas as pd from urllib.request import urlopen url = "https://www.ndbc.noaa.gov/view_text_file.php?filename=42887h2014.txt.gz&amp;dir=data/historical/stdmet/" #df = pd.read_csv(url, header=NONE, sep='\s+') data_csv = urlopen(url) df2014 = pandas.read_csv(data_csv, index_col=0, parse_dates=True) df2014.head() Result: df2014.head() Out[26]: Empty DataFrame Columns: [] Index: [#yr mo dy hr mn degT m/s m/s m sec sec degT hPa degC degC degC mi ft, 2014 01 01 00 00 61 7.4 99.0 1.12 4.34 99.00 999 9999.0 19.2 999.0 12.5 99.0 99.00, 2014 01 01 00 20 60 7.8 99.0 1.12 4.34 99.00 999 9999.0 19.4 999.0 12.9 99.0 99.00, 2014 01 01 00 40 66 7.8 99.0 1.12 4.34 99.00 999 9999.0 19.3 999.0 13.0 99.0 99.00, 2014 01 01 01 00 76 8.6 99.0 1.18 4.49 99.00 999 9999.0 19.4 999.0 13.3 99.0 99.00]

http://stackoverflow.com/a/52720815
score: 1
upvote count: 1
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92371916
has body: How did you run the test suite? I used your code and ran it using 'python3 -m unittest test.py': import unittest class MyBaseTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.abs = "test" class MyTestClass(MyBaseTestCase): def test_abs(self): if self.abs: pass class MyTestSuite(unittest.TestSuite): def __init__(self): super().__init__() self.addTest(MyTestClass.test_abs) And it works.
answers question: http://stackoverflow.com/q/52716859
type: Answer
accepted answer of: http://stackoverflow.com/q/52716859

http://stackoverflow.com/comment/92327664
score: 0
type: Comment
has text: @Masterbuilder - I think your solution working nice, only need `|` for `OR` - `cdf[(cdf.score < 2) | (cdf.score >4) ]`
comment on: http://stackoverflow.com/a/52700554
type: AnswerComment

http://stackoverflow.com/comment/92416307
comment on: http://stackoverflow.com/q/52744334
has text: Yes Rahlf is correct. There is no division involved. Just if the second occurrence within a sorted group has a specific value ( the criterion is in the function) then it is *_red
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92175649
has text: Why aren't *you* faintly familiar with regex yet? Have you tried to come up with a regex?
comment on: http://stackoverflow.com/q/52620953
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52684290
has answer: http://stackoverflow.com/a/52684321
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52684321
answer count: 3
tagged with: python
has title: Create a new list in a list of lists that has the same length as the longest one
tagged with: list
has comment: http://stackoverflow.com/comment/92296509
has body: If I have the following list of lists: data = [[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7]] Is there a way to create a list between the second and third one (preferably at any position) that has the same length as the longest list in this list of lists? For example, in my case create a list between the second and third/last list that has the same length as the last one (since this is the longest list with length 7): data = [[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7]] I'm using this data in a dataframe with pandas. Maybe pandas can help me accomplish my goal?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52684322
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/52684324
has comment: http://stackoverflow.com/comment/92296512
score: 0
has comment: http://stackoverflow.com/comment/92296540
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52684322

http://stackoverflow.com/a/52640471
has comment: http://stackoverflow.com/comment/92213585
has comment: http://stackoverflow.com/comment/92213374
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92213517
has comment: http://stackoverflow.com/comment/92213304
has comment: http://stackoverflow.com/comment/92214048
has body: Use of zip + unpacking: lst = [('client', 'NN'), ('say', 'VBP'), ('management', 'NN'), ('take', 'VB'), ('decission', 'NN'), ('submitted', 'VBN')] var1, var2 = zip(*lst) print(var1) # ('client', 'say', 'management', 'take', 'decission', 'submitted') print(var2) # ('NN', 'VBP', 'NN', 'VB', 'NN', 'VBN')
accepted answer of: http://stackoverflow.com/q/52640425
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52640425
has comment: http://stackoverflow.com/comment/92213764
type: Answer
has comment: http://stackoverflow.com/comment/92213384

http://stackoverflow.com/comment/92310195
type: Comment
comment on: http://stackoverflow.com/q/52691399
has text: In 4th line it should be `for content in data['contents']:` instead of `for content in row['contents']:`
score: 0
type: QuestionComment

http://stackoverflow.com/q/52650995
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52651669
possible better answer: http://stackoverflow.com/a/52651593
has answer: http://stackoverflow.com/a/52651593
type: Question
has answer: http://stackoverflow.com/a/52691282
downvote count: 0
has title: Reading values from python object loaded from yaml file
answer count: 3
tagged with: yaml
has answer: http://stackoverflow.com/a/52651669
favorite count: 0
has body: I have a script that reads a YAML file into a python dictionary. How do I read the values and concatenate some of them to be more meaningful? #script to load the yaml file into a python object import yaml from yaml import load, dump #read data from the config yaml file with open("config.yaml", "r") as stream: try: print(yaml.load(stream)) except yaml.YAMLError as exc: print(exc) Contents of YAML file: os2: host:hostname ip:10.123.3.182 path:/var/log/syslog file:syslog

http://stackoverflow.com/q/52739363
favorite count: 0
has answer: http://stackoverflow.com/a/56926552
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: How can I use the Segno qrcode python library to generate a QR Code on the fly to show it on a web page. For example, exporting it as an SVG: import segno qr = segno.make('Up Jumped the Devil') svgvar = qr.export_as_svg() Is there a better way?
score: 1
has title: How to use Segno to generate a QR code on the fly in python
tagged with: qr-code
has answer: http://stackoverflow.com/a/63306162
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/52710223
favorite count: 0
tagged with: python
tagged with: wolfram-mathematica
has body: With Matematica this integral gives me 3. wolfram alpha With integrate.tplquad I get -3. This is Matematica code. Integrate[1-x, {(0,2),(0,3-1.5*x),(0,6-3*x -2*y)}] I can't see what I am doing wrong with ntegrate.tplquad f = lambda x,y,z: 1-x x1, x2 = 0,2 y1, y2 = lambda x : 0 , lambda x:3-1.5*x z1, z2 = lambda x,y:0, lambda x,y: 6 -3*x -2*y print(integrate.tplquad(f,x1,x2, y1, y2, z1, z2)[0]) -3.0
upvote count: 1
tagged with: scipy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52710373
score: 1
accepted answer: http://stackoverflow.com/a/52710373
type: Question
has title: different result with scipy integrate.tplquad
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92346882

http://stackoverflow.com/comment/92456371
score: 1
has text: `gdf_with_meta = gdf.assign(filename=source_file)`
comment on: http://stackoverflow.com/q/52731238
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52633305
has body: sys.getsizeof() will give you the size of an object in memory. But from your description, it sounds like you're looking for the length of some serialization (into a message) of the dictionary. It looks like you're using JSON, and that makes sense. For example using json.dumps(): json_string = json.dumps(your_dict) The next question is how do you get the length (in octets) of that string. Well len(json_string) will give you the number of characters, but for most encodings, the number of bytes required to transmit those characters will be different.(Docs) So first you need to encode your string to bytes, then use the length of the resulting bytes object: len(json_string.encode(&lt;your encoding&gt;)) Which will give you the number of octets needed to transmit that dictionary. Note: any other requirements of the message, such as headers, delimiters, escaping, formatting, etc will be in addition to this number.
score: 2
accepted answer of: http://stackoverflow.com/q/52633151
has comment: http://stackoverflow.com/comment/92199903
has comment: http://stackoverflow.com/comment/92199909
has comment: http://stackoverflow.com/comment/92199876
has comment: http://stackoverflow.com/comment/92199935
downvote count: 0
answers question: http://stackoverflow.com/q/52633151
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/a/52612391
score: 0
type: Answer
has body: You might want to clarify exactly what you want. From reading your question, it sounds like you're wanting to do the following: find a list of files in a folder and get their file names. Parse those file names into dates and suitably alter to subtract a day do the rename. Suggestions: you could use os.listdir if you don't need recursive folder search. you could use a regex (python's re module) Here's some useful references: https://www.pythonforbeginners.com/basics/python-datetime-time-examples And a related SO question: Working with time, date, timedelta
answers question: http://stackoverflow.com/q/52612062

http://stackoverflow.com/q/52657962
has answer: http://stackoverflow.com/a/52657975
has comment: http://stackoverflow.com/comment/92246382
favorite count: 0
has answer: http://stackoverflow.com/a/52658075
type: UnansweredQuestion
tagged with: python
tagged with: merge
tagged with: extend
tagged with: list
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92246408
tagged with: concatenation
has comment: http://stackoverflow.com/comment/92246436
has comment: http://stackoverflow.com/comment/92246438
has body: So for example this code here: one = [0,1] two = [2,3] three = [one, two] Is that possible?
downvote count: 0
has title: Can a python list be made with two other lists?
answer count: 3
has answer: http://stackoverflow.com/a/52657988

http://stackoverflow.com/comment/92304791
comment on: http://stackoverflow.com/q/52688628
score: 0
type: Comment
has text: @SumRchn: how would you convert a dictionary to an array?
type: QuestionComment

http://stackoverflow.com/comment/92167089
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52616351
score: 0
has text: That's because you've probably double-serialized a JSON list. You shouldn't have to call `list` on the result of `json.load`. Somewhere, you had a serialized JSON list, something like `'["foo", "bar", "baz"]'`, and then you *reserialized* that string, giving you a JSON string, which *happens* to be a serialized JSON list.

http://stackoverflow.com/q/52655995
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52665601
has comment: http://stackoverflow.com/comment/92260871
has title: Deep Q-learning modification
linked to: http://stackoverflow.com/q/6848828
type: Question
accepted answer: http://stackoverflow.com/a/52665601
score: 0
tagged with: reinforcement-learning
tagged with: deep-learning
answer count: 1
has body: @Edit: I'm trying to create an agent to play the game of Tetris, using a convolutional nnet that takes the board state + current piece as input. From what I've read, Deep Q-learning is not very good at this, which I just confirmed. @end Edit Suppose that an agent is learning a policy to play a game, where each game step can be represented as s, a, r, s', done representing state, action, reward, next state, game over In the Deep Q-learning algorithm, the agent is in state s and takes some action a (following an epsilon-greedy policy), observes a reward r and gets to the next state s'. The agent acts like this: # returns an action index get_action(state, epsilon) if random() < epsilon return random_action_index else return argmax(nnet.predict(state)) The parameters are updated by greedily observing the max Q-value in state s', so we have # action taken was 'a' in state 's' leading to 's_' prediction = nnet.predict(s) if done target = reward else target = reward + gamma * max(nnet.predict(s_)) prediction[a] = target The [prediction, target] is feed to some nnet for weight update. So this nnet gets a state s as input, and outputs a vector of q-values with dimension n_actions. This is all clear to me. Now, suppose that my state-actions are so noise, that this approach will simply not work. So, instead of outputting a vector of dimension n_actions, my nnet output is a single value, representing the "state-quality" (how desirable is that state). Now my agent acts like this: # returns an action based on how good the next state is get_action(state, epsilon): actions = [] for each action possible in state: game.deepcopy().apply(action) val = nnet.predict(game.get_state()) action.value = val actions.append(action) if random() < epsilon return randomChoice(actions) else return action with_max_value from actions And my [prediction, target] is like this: # action taken was 'a' in state 's' leading to 's_' prediction = nnet.predict(s) if done target = reward else target = reward +…

http://stackoverflow.com/comment/92167216
has text: I'd say the idiomatic way to do that is not to do it. Why do you need to do that? Why would you want to change another variable's value?
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/52616489

http://stackoverflow.com/comment/92117932
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52590716
has text: When doing the tutorial. You automatically download the data off their website. Its already sliced and made perfect. I'm dealing with real world data, which means I had a very pesky made .xlsl file, that I had to slice and cut up for it to make sense. Now I then extracted the relevant data out into smaller dataframes, but they cannot be read by Tensorflow it seems. So my problem is, how do I go about getting Tensorflow to read my dataframes =)

http://stackoverflow.com/comment/92183305
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52624984
score: 0
has text: Yes I totally agree with you, But again, pip install tensorflow-gpu was run on system with CUDA enable device (My workstation with GTX1070). And then importing tensorflow was success and all my scripts ran on a system with no CUDA device (My laptop with no GPU) without a problem.

http://stackoverflow.com/q/52733105
has comment: http://stackoverflow.com/comment/92391047
has comment: http://stackoverflow.com/comment/92391125
answer count: 1
linked to: http://stackoverflow.com/q/9623114
favorite count: 0
accepted answer: http://stackoverflow.com/a/52733200
has title: Check if a Duplicated list present out of multiple lists
score: -3
tagged with: python
type: AnsweredQuestion
upvote count: 0
tagged with: list
has answer: http://stackoverflow.com/a/52733200
downvote count: 3
type: Question
tagged with: duplicates
has comment: http://stackoverflow.com/comment/92391086
has comment: http://stackoverflow.com/comment/92391077
has body: I have the following Lists: I need to check if it has duplicates we assume (['f', 't'] = ['t', 'f']) (order of elements in the list does not matter) and hence this should return 'duplicate' as it has both the lists ['f', 't'] ['f', 'r'] ['t', 'f'] ['f', 'u'] ['b', 't'] ['b', 'r'] ['b', 'l'] ['b', 'u'] ['r', 't'] ['r', 'u'] ['l', 't'] ['l', 'u'] and I did try to run an iteration to check if any duplicate lists but it fails as each element is compared to itself in the iteration one time. Any leads to the same will be appreciated

http://stackoverflow.com/a/52712100
has body: Using dictionaries (key-to-value maps) will allow you to solve your problem: veg_type = ["Urban", "Urban", "Forest", "OpenForest", "Arboretum"] veg_density = [0.5, 0.6, 0.1, 0, 0.9] type_density = {} #Creates a new dictionary if len(veg_type) == len(veg_density): #pointed out by @lalengua -- veg_type and veg_density need to have the same length for i in range(len(veg_type)): if veg_type[i] not in type_density: #If the veg_type isn't in the dictionary, add it type_density[veg_type[i]] = 0 type_density[veg_type[i]] += veg_density[i] This produces: {'Urban': 1.1, 'Forest': 0.1, 'OpenForest': 0, 'Arboretum': 0.9} With it's values being accessed like so: type_density['Urban'] = #some value some_variable = type_density['Forest'] #double quotes can be used as well A few things about dictionaries: Dictionaries have keys which correspond to certain values Keys are unique in a dictionary -- redefining a key will overwrite it's value Keys can be strings, numbers or objects -- anything that can be hashed Keys need to be in the dictionary in order to apply operations to them To predefine a dictionary (rather than having it empty), use the following: name = {key1 : value1, key2 : value2, key3 : value3, keyN : valueN} You can read more about dictionary objects at the offical python docs.
downvote count: 1
upvote count: 5
has comment: http://stackoverflow.com/comment/92350590
score: 4
answers question: http://stackoverflow.com/q/52712062
has comment: http://stackoverflow.com/comment/92351116
type: Answer

http://stackoverflow.com/q/52611846
has comment: http://stackoverflow.com/comment/92287741
has title: sqlalchemy.pool + psycopg2 timeout issue
favorite count: 0
tagged with: postgresql
has body: I have a web application timeout issue, and I'm suspecting the error is in the database. The query is running too long. How do I increase the allowed-running-time for my setup? I am using a DB pool by using sqlalchemy and psycopg2. My database is a Postgres database. import psycopg2 import sqlalchemy.pool as pool def generate_conn_string(db_name): db_name = db_name.upper() conn_string = "host='{}' port='{}' dbname='{}' user='{}' password='{}' ".format( os.environ.get('DB_HOST_' + db_name), os.environ.get('DB_PORT_' + db_name), os.environ.get('DB_NAME_' + db_name), os.environ.get('DB_USER_' + db_name), os.environ.get('DB_PASSWORD_' + db_name)) return conn_string def get_conn_(): db_name = "mydb" conn_string = Pooling.generate_conn_string(db_name) conn = psycopg2.connect(conn_string) return conn connection_pool = pool.QueuePool(get_conn, max_overflow=30, pool_size=5)
type: Question
linked to: http://stackoverflow.com/q/44936527
tagged with: python
tagged with: psycopg2
has answer: http://stackoverflow.com/a/52684398
answer count: 1
downvote count: 1
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/52684398
upvote count: 12
score: 11
type: AnsweredQuestion

http://stackoverflow.com/a/52732369
answers question: http://stackoverflow.com/q/52732222
score: 3
has comment: http://stackoverflow.com/comment/92391495
has body: You should always use quotes around string literals that start with a digit and consist of a mix of digits and non-digit characters to avoid confusion from the YAML parser: MAC1: "80:41:26:53:24:11" Otherwise, if your string literal consists of a series of one or two-digit numbers delimited by colons and all numbers but the first are between 0 and 59, it would be interpreted as a sexagesimal number and would be converted to the equivalent number of seconds. For example, your MAC-address 80:41:26:53:24:11 would be treated as a sexagesimal number and converted to: (((((80*60)+41)*60+26)*60+53)*60+24)*60+11 which is equal to 62745168251. Since your other MAC-address, 84:19:14:15:86:58, has a number after the first number that is over 59 (86 that is), it is not considered as a sexagesimal number and is therefore treated literally as a string. Relevant source code can be found in the int resolver and the int constructor.
has comment: http://stackoverflow.com/comment/92395314
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/92394787
type: Answer

http://stackoverflow.com/comment/92330515
type: Comment
comment on: http://stackoverflow.com/q/52701649
score: 0
type: QuestionComment
has text: @user2810114 Try with `logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': True, })`

http://stackoverflow.com/q/52638991
answer count: 1
tagged with: shell
score: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92210618
upvote count: 1
tagged with: python
has title: convert JSON data to CSV format
has answer: http://stackoverflow.com/a/52639267
tagged with: http://stackoverflow.com/tag/json
has body: is there any easy way of converting below JSON format to CSV JSON { "item1" : { "status":"Shipped", "Location":"TX", "trackingno":"z123345df234" }, "item2" : { "status":"OrderReceived", "Location":"AZ", "trackingno":"D234235dfawe98" } } Expected CSV item1|Shipped|TX|z123345df234 item2|OrderReceived|AZ|D234235dfawe98
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/1871524
duplicate of: http://stackoverflow.com/q/1871524
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/92170315
comment on: http://stackoverflow.com/q/52618065
score: 0
type: Comment
type: QuestionComment
has text: You are missing the closing brackets )

http://stackoverflow.com/comment/92118388
has text: After self.welcomeWindow.show(), i execute Dialog.close(). However, the welcomewindow stays visible
comment on: http://stackoverflow.com/q/52591246
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52621029
has title: How to search in multiple java files for certain statement?
upvote count: 0
score: -1
answer count: 1
favorite count: 0
has body: I am new to python. In the following code, I am trying to extract all print statements from an application directory which contains many files written in Java and xml and write them in another file (.txt). I have the following code but it doesn't work import glob import os, sys folderpath= os.chdir("/.../.../MyApp") for files in glob.glob('*.java'): with open("/.../.../result.txt", "w") as f: for filename in files: filepath = os.path.join(path, filename) with open(folderpath + filename) as currentFile: text = currentFile.read() if ('print' in text): f.write('Found the word in ' + filename + ' in line: ' + text + '\n')
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52622012
downvote count: 1
type: Question

http://stackoverflow.com/a/52706651
has comment: http://stackoverflow.com/comment/92339806
has comment: http://stackoverflow.com/comment/92339850
type: Answer
has comment: http://stackoverflow.com/comment/92339950
answers question: http://stackoverflow.com/q/52706232
has comment: http://stackoverflow.com/comment/92339670
has comment: http://stackoverflow.com/comment/92341081
has comment: http://stackoverflow.com/comment/92339895
has body: You have to look for the case when self.head is None as Nonetype will have no attribute next. Also iterate till you find the next pointer in the node to be None. So it should be cur.next is not None rather than cur is None which is finding if the Node is None. Logically speaking you cannot append anything to None class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def __len__(self): if not self.head: return 0 cur = self.head count = 0 while cur is not None: count += 1 cur = cur.next return count def append(self, item): if not self.head: self.head=Node(item) return cur = self.head while cur.next is not None: cur = cur.next cur.next = Node(item) Test case1 l=LinkedList() l.append(1) l.__len__() #prints 1 Test case2 l=LinkedList() l.append(2) l.append(3) l.__len__() #2 temp=l.head while(temp): print(temp.data) temp=temp.next Including testcases of OP as well def test_append_empty(): lst = LinkedList() lst.append(1) print(lst.head.data == 1) def test_append_one(): lst = LinkedList() lst.head = Node(1) lst.append(2) print(lst.head.next.data == 2) test_append_empty() #True test_append_one() #True
score: 0

http://stackoverflow.com/comment/92155883
has text: @YolandaHui That entire nested loop can be replaced with a single line, `print(sum(myList))` (If you don't do `sum = 0` of course)
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52610724

http://stackoverflow.com/a/52651180
has comment: http://stackoverflow.com/comment/92235024
has comment: http://stackoverflow.com/comment/92325349
has body: I am not sure but you may do something like this: import unittest class DictEq(unittest.TestCase): def test_dict_eq1(self): dict1 = {'a': df1} dict2 = {'a': df2} key1 = dict1.keys() key2 = dict2.keys() self.assertEqual(key1,key2) for key, val in dict1.items(): df1 = dict1[key] df2 = dict2[key] assert_frame_equal(df1, df2)
has comment: http://stackoverflow.com/comment/92235725
downvote count: 0
has comment: http://stackoverflow.com/comment/92235120
answers question: http://stackoverflow.com/q/52650886
type: Answer
has comment: http://stackoverflow.com/comment/92234885
has comment: http://stackoverflow.com/comment/92235625
score: 1
upvote count: 1

http://stackoverflow.com/comment/92204268
score: 2
comment on: http://stackoverflow.com/q/52635518
has text: [r-and-the-collatz-conjecture-part-2.html](http://blog.revolutionanalytics.com/2014/05/r-and-the-collatz-conjecture-part-2.html)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92392541
type: Comment
type: QuestionComment
has text: Hi @shadowtalker, it' s JSON array of objects.
comment on: http://stackoverflow.com/q/52733830
score: 0

http://stackoverflow.com/a/52760594
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52746683
has body: According to Paging Large Queries: Whenever there are no more rows in the current page, the next page will be fetched transparently. So, if you execute your code like this, you will still the whole result set, but this is paged in a transparent manner. In order to achieve what you need to use callbacks. You can also find some code sample on the link above. I added below the full code for reference. from cassandra.cluster import Cluster from cassandra.query import SimpleStatement from threading import Event class PagedResultHandler(object): def __init__(self, future): self.error = None self.finished_event = Event() self.future = future self.future.add_callbacks( callback=self.handle_page, errback=self.handle_error) def handle_page(self, rows): for row in rows: process_row(row) if self.future.has_more_pages: self.future.start_fetching_next_page() else: self.finished_event.set() def handle_error(self, exc): self.error = exc self.finished_event.set() def process_row(user_row): print user_row.name, user_row.age, user_row.email cluster = Cluster() session = cluster.connect() query = "SELECT * FROM myschema.users" statement = SimpleStatement(query, fetch_size=5) future = session.execute_async(statement) handler = PagedResultHandler(future) handler.finished_event.wait() if handler.error: raise handler.error cluster.shutdown() Moving to next page is done in handle_page when start_fetching_next_page is called. If you replace the if statement with self.finished_event.set() you will see that the iteration stops after the first 5 rows as defined in fetch_size
upvote count: 2

http://stackoverflow.com/comment/92374814
type: QuestionComment
has text: @timgeb Yes, they are.
score: 0
comment on: http://stackoverflow.com/q/52724530
type: Comment

http://stackoverflow.com/q/52736900
accepted answer: http://stackoverflow.com/a/52737002
has answer: http://stackoverflow.com/a/73261493
upvote count: 25
has comment: http://stackoverflow.com/comment/117103643
has comment: http://stackoverflow.com/comment/92398668
downvote count: 2
tagged with: python
has body: When I run the below code, it gives me an error saying that there is attribute error: 'float' object has no attribute 'split' in python. I would like to know why this error comes about. def text_processing(df): """""=== Lower case ===""" '''First step is to transform comments into lower case''' df['content'] = df['content'].apply(lambda x: " ".join(x.lower() for x in x.split() if x not in stop_words)) return df df = text_processing(df) The full traceback for the error: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.2\helpers\pydev\pydevd.py", line 1664, in &lt;module&gt; main() File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.2\helpers\pydev\pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.2\helpers\pydev\pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/L31307/Documents/FYP P3_Lynn_161015H/FYP 10.10.18 (Wed) still working on it/FYP/dataanalysis/category_analysis.py", line 53, in &lt;module&gt; df = text_processing(df) File "C:/Users/L31307/Documents/FYP P3_Lynn_161015H/FYP 10.10.18 (Wed) still working on it/FYP/dataanalysis/category_analysis.py", line 30, in text_processing df['content'] = df['content'].apply(lambda x: " ".join(x.lower() for x in x.split() if x not in stop_words)) File "C:\Users\L31307\AppData\Roaming\Python\Python37\site-packages\pandas\core\series.py", line 3194, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File "pandas/_libs/src\inference.pyx", line 1472, in pandas._libs.lib.map_infer File "C:/Users/L31307/Documents/FYP P3_Lynn_161015H/FYP 10.10.18 (Wed) still working on it/FYP/dataanalysis/category_a…
type: AnsweredQuestion
tagged with: attributeerror
has comment: http://stackoverflow.com/comment/92398659
score: 23
type: Question
has answer: http://stackoverflow.com/a/52737002
possible better answer: http://stackoverflow.com/a/52737048
has answer: http://stackoverflow.com/a/52737048
tagged with: series
has title: How to solve the Attribute error 'float' object has no attribute 'split' in python?
answer count: 3
tagged with: pandas
tagged with: string
favorite count: 0

http://stackoverflow.com/q/52637168
has comment: http://stackoverflow.com/comment/92207566
tagged with: python
accepted answer: http://stackoverflow.com/a/52637312
tagged with: module
type: AnsweredQuestion
score: 0
has body: So I split my code into different files that are in the project directory But when I import those modules into main.py it complains that it can't see files in them import pygame import winsound import random import math #import wGeneration import rGeneration from Camera import camera from KeyHandle import KeyHandle On importing Keyhandle it gives out this error This is what is in the KeyHandle module though import main import pygame def KeyHandle(): for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_UP: main.dire.append(3) if event.key == pygame.K_DOWN: main.dire.append(2) if event.type == pygame.KEYUP: if event.key == pygame.KEYUP: main.dire.remove(3) if event.key == pygame.K_DOWN: main.dire.remove(2) Can anyone tell me what am I doing wrong?
type: Question
has comment: http://stackoverflow.com/comment/92207576
has answer: http://stackoverflow.com/a/52637312
answer count: 1
has title: Python doesn't see files in modules

http://stackoverflow.com/a/52717598
score: 2
has comment: http://stackoverflow.com/comment/92376145
downvote count: 0
answers question: http://stackoverflow.com/q/52711885
has comment: http://stackoverflow.com/comment/92375905
upvote count: 2
has comment: http://stackoverflow.com/comment/92385626
type: Answer
has body: You are receiving the error because the variable is empty. You can set the initial value to 0 to prevent this error using: var.set(0) And also, you don't need to delete the data from the entry, because when an entry is created, it is empty. So remove line: entry.delete(0, tk.END) Here is a code: import tkinter as tk root = tk.Tk() var = tk.IntVar() entry = tk.Entry(textvariable=var) var.set(0) #&lt;-- Set the value to 0 var.get() #&lt;-- Working Edit: You can use the try/except statement. Here is a working of the statements: import tkinter as tk root = tk.Tk() var = tk.IntVar() entry = tk.Entry(textvariable=var) entry.pack() var.set(0) #&lt;-- Set the value to 0 def _get(): try:var.get() except:var.set(0) tk.Button(text="Press",command=_get).pack() root.mainloop() #var.get() #&lt;-- Working When you press the button, if the entry is empty, its value will be set to 0.

http://stackoverflow.com/q/52604952
has comment: http://stackoverflow.com/comment/92147165
answer count: 1
tagged with: user-defined-functions
tagged with: container-classes
downvote count: 0
type: UnansweredQuestion
has body: I am programming on my phone. I've created the class character to hold all the information about the character such as the Hp. After defining the hp, I make a function called getHp() which returns the hp. Later when I call "getHp()" in my "stats()" function it says that "getHp()" is not defined. It does the same for all my functions in my class. Just fyi "stats()" is just a function to gather all my variables (within the class) and print them. #Adventure game import random, time #===========================# class character(): self.xp = 0 def getLvl(self, xp): if xp < 5: level = 1 elif xp < 20: level = 2 elif xp < 60: level = 3 elif xp < 120: level = 4 else: level = 5 return level self.level = getLvl(self, xp) #-----------------------------------------# self.inventory = {"knife": 1 , "bread": 2 , "gold": 10} self.armor = 0 #-----------------------------------------# self.attack = 6 def getAttack(self, attack): return attack #-----------------------------------------# self.dmg = 1 def getDmg(self, dmg): return dmg #-----------------------------------------# self.hp = 10 * level + armor def getHp(self, hp): return hp def updateHp(self, playerHp): self.hp = playerHp #-----------------------------------------# def stats(self): self.getLvl(xp) self.getHp(hp) self.getAttack(attack) self.getDmg(dmg) print("Player: \n") print("Hp: ", hp, "\nLvl: ", level, "\nAttack: ", attack, "\nDmg: ", dmg) print("Inventory: ", self.inventory) #===========================# character.stats()
has answer: http://stackoverflow.com/a/52605275
favorite count: 0
type: Question
score: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92147514
has title: [Closed for the moment]Python class definition is not defined. Error
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/92294664
type: Comment
comment on: http://stackoverflow.com/a/52682338
has text: @cryptonome: I know what a metaclass is and how metaclasses work. The things you said still don't make sense.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52655363
has comment: http://stackoverflow.com/comment/92242190
accepted answer: http://stackoverflow.com/a/52655425
has title: Password validator: password needs to contain EXACTLY one spacial character?
possible better answer: http://stackoverflow.com/a/52655434
has answer: http://stackoverflow.com/a/52655425
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92242143
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92242232
has body: Task: Password validator a. The length of the password needs to be from 8 to 30 characters. b. The password needs to contain at least 2 uppercase characters. c. The password needs to contain at least 2 lowercase characters. d. The password needs to contain at least 1 digit. e. The password needs to contain exactly 1, but not more of the following special characters: @/%&amp;*_- This is my code: special_character_set = "@/%&amp;*_-" is_valid = False import re while True: password = input("please enter a password: ") if len(password) &gt; 30 or len(password)&lt; 8: print("The length of the password needs to be from 8 to 30 characters!") continue elif re.search('[0-9]', password) is None: print("The password needs to contain at least 1 digit!") continue elif re.search ('[A-Z][A-Z]', password) is None: print("The password needs to contain at least 2 uppercase characters!") continue elif re.search('[a-z][a-z]', password) is None: print("The password needs to contain at least 2 lowercase characters!") continue elif re.search('[@/%&amp;*_-]', password) is None: print("The password needs to contain one of the following special characters: @/%&amp;*_-!") continue else: is_valid = True if is_valid: print("valid password") break It works. However, the condition e) has not been completely fulfilled. How can I make the password contain ONLY ONE of the special characters?
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52655434
type: AnsweredQuestion
score: 1
type: Question

http://stackoverflow.com/comment/92238807
comment on: http://stackoverflow.com/a/52637876
has text: Kevin Fang, Thanks for the details, i have been think in a wrong way. Thanks for the info
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52676433
has comment: http://stackoverflow.com/comment/92289088
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/52675556
has comment: http://stackoverflow.com/comment/92292264
downvote count: 0
score: 3
has body: Not so pretty, but this would get the job done, I think. You would get a dictionary which then gets printed by the json parser in a nice, pretty format. import json def get_data(page_content): _dict = {} page_content_list = page_content.splitlines() for line in page_content_list: if ':' not in line: continue key, value = line.split(':') _dict[key.strip()] = value.strip() return _dict page_data = get_data(page_content) json_data = json.dumps(page_data, indent=4) print(json_data) or, instead of those last 3 lines, just do this: print(json.dumps(get_data(page_content), indent=4))

http://stackoverflow.com/a/52687546
type: Answer
has body: For the second point I didn't notice, I was more concentrate in the first one. returning 1 doesn't solve my problem sins I just simplified the real problem with a smaller example. I want a general solution for this pattern. def f(x): if condition(x): exit() else: return g(x) # return something in relation with x I found this pattern which is working now def f_z3(x): global solver solver.add(Not(condition(x)) return g(x) So my first function will be something like def f_z3(a): global solver # sins we have two nested condition we have to add an And solver.add( Not( And( Or(a&lt;=47, a&gt;57), Or(a&lt;=64, a&gt;98) ) ) ) return If( Or(a&lt;=47, a&gt;57), a-55, a - 48 ) I still search a better approach to solve this kind of pattern, something that tell the If condition to be always False.
answers question: http://stackoverflow.com/q/52682777
score: 0
has comment: http://stackoverflow.com/comment/92308805

http://stackoverflow.com/a/52693941
answers question: http://stackoverflow.com/q/52693873
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52693873
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92341166
score: 1
has body: The most obvious answer would be if frame==b"": break But as stated in the docs, there is also a method that gives you the amount of frames; so you might want to use that; enabling you to only iterate through the existing frames. I'm not familiar with the module though.
has comment: http://stackoverflow.com/comment/92341828

http://stackoverflow.com/q/52704777
type: Question
has comment: http://stackoverflow.com/comment/92336314
tagged with: numpy
score: 5
has comment: http://stackoverflow.com/comment/92336627
downvote count: 0
has answer: http://stackoverflow.com/a/52705064
answer count: 3
possible better answer: http://stackoverflow.com/a/52705060
favorite count: 0
has comment: http://stackoverflow.com/comment/92336486
upvote count: 5
tagged with: python
tagged with: vectorization
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52718709
has answer: http://stackoverflow.com/a/52705060
accepted answer: http://stackoverflow.com/a/52705064
has body: Is there any way to make this work without for loops? import import numpy as np import matplotlib.pyplot as plt L = 1 N = 255 dh = 2*L/N dh2 = dh*dh phi_0 = 1 c = int(N/2) r_0 = L/2 arr = np.empty((N, N)) for i in range(N): for j in range(N): arr[i, j] = phi_0 if (i - c)**2 + (j - c)**2 &lt; r_0**2/dh2 else 0 plt.imshow(arr) I've tried calling function(x[None,:], y[:, None]), where: function(i, j): return phi_0 if (i - c)**2 + (j - c)**2 &lt; r_0**2/dh2 else 0 but it requires list .any or .all methods. I'm looking for specifically functionless method (without fromfunction and vectorization). Big thanks!
has title: NumPy - Vectorizing loops involving range iterators

http://stackoverflow.com/a/52626594
has comment: http://stackoverflow.com/comment/92186535
has body: You can totally make a new list (Of Dictionary(Of String, List(Of Integer))) and populate it. You already seems to know the code. Have fun implementing it!
has comment: http://stackoverflow.com/comment/92186572
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52626430

http://stackoverflow.com/q/52664334
tagged with: exchangewebservices
tagged with: office365
has comment: http://stackoverflow.com/comment/92620834
tagged with: office365api
has body: When we delete an item, it can be found in Deleted folder. And if we delete that item from Deleted folder then it goes in recoverable items in outlook.(this is true for mails,contacts and calendars) So I can access the recoverable mails using https://outlook.office.com/api/v2.0/me/MailFolders/RecoverableItemsDeletions/messages and contacts using https://outlook.office.com/api/v2.0/me/contactfolders/RecoverableItemsDeletions/contacts. Now I can't access my calendar event that has been deleted from Deleted folder. I am trying to use this Api - https://outlook.office.com/api/v2.0/me/calendars/RecoverableItemsDeletions/events I can still see my calendar event in recoverable folder but can't access using api.
score: 0
has comment: http://stackoverflow.com/comment/92329393
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: outlook
has title: Api to fetch recoverable contents for calendar in outlook
has comment: http://stackoverflow.com/comment/92321495

http://stackoverflow.com/comment/92263011
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52661552
has text: Thanks for your advice that's really helpful - especially the list advice!
type: AnswerComment

http://stackoverflow.com/comment/92183317
has text: @RohanPooniwala I just installed tensorflow-gpu via pip and got an error when I imported tensorflow. Do you happen to have anaconda with cuda hidden somewhere?
type: AnswerComment
comment on: http://stackoverflow.com/a/52624984
type: Comment
score: 1

http://stackoverflow.com/comment/92357169
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52702859
has text: First get this working with a row by row iteration.
score: 0

http://stackoverflow.com/comment/92380180
has text: I think you want `continue`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52727487
score: 1

http://stackoverflow.com/q/52731889
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/92388890
has title: List being recognized as tuple
has body: My code, explains that this is a list. But somehow, the system is giving me a exception: TypeError: 'tuple' object doesn't support item deletion My code explains this with: x = (insert a tuple elements here) x = list(x) My code is this (I'm progamming a code that will recognize a number expression. This and more in this lib.) def num_expression(*nums): nums = list(nums) if '*' in nums: numsam = nums search = __charposition(numsam,'*') nums2 = 0 nums3 = 0 for i in search: num2 = i - 1 num3 = i + 1 del numsam[i] num4 = numsam[num2]*numsam[num3] syn = i - 1 del numsam[syn] numsam[i] = num4 if '/' in nums: numsam = nums search = __charposition(numsam,'/') nums2 = 0 nums3 = 0 for i in search: num2 = i - 1 num3 = i + 1 del numsam[i] num4 = numsam[num2]/numsam[num3] syn = i - 1 del numsam[syn] numsam[i] = num4 excptd_vari = 1 pos = 0 num = 0 syn1 = '' syn2 = '' syn3 = '' syn4 = '' size = len(nums) for i in nums: if expctd_vari == 1 and isinstance(i, int): syn1 = i expctd_vari = 2 num1syn = True elif expctd_vari == 2 and isinstance(i, str): syn2 = i expctd_vari = 3 elif expctd_vari == 3 and isinstance(i, int): expctd_vari = 2 if num1syn == True: syn3 = i if syn2 == '+': num+= syn1+syn3 if syn2 == '-': num-= syn1+syn3 else: raise SyntaxError num1syn = False else: syn4 = i if syn2 == '+': num+= syn3+syn4 if syn2 == '-': num-= syn3+syn4 else: raise SyntaxError def __charposition(string, char): pos = [] for n in range(len(string)): if string[n] == char: pos.append(n) return pos Observation: I'm fixing divider problem too. It's just add an return in the final.
has comment: http://stackoverflow.com/comment/92389851
downvote count: 3
answer count: 1
accepted answer: http://stackoverflow.com/a/52732531
has comment: http://stackoverflow.com/comment/92412583
has comment: http://stackoverflow.com/comment/92415797
score: -3
has comment: http://stackoverflow.com/comment/92388987
type: AnsweredQuestion
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52732531

http://stackoverflow.com/comment/92244922
score: 0
type: Comment
type: QuestionComment
has text: @ChristianKönig And upvoted the question
comment on: http://stackoverflow.com/q/52639774

http://stackoverflow.com/comment/92133815
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52599378
has text: Your welcome, please mark this as the answer to thanks me for my time!
score: 0

http://stackoverflow.com/q/52677165
tagged with: python
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92283352
type: Question
has answer: http://stackoverflow.com/a/52677209
accepted answer: http://stackoverflow.com/a/52677209
tagged with: dataframe
tagged with: pandas
has body: Is there any way to equalize size of a list in a dataframe column which looks like this: 0 [2116.0, 6999.0, 2116.0, 2166.0, 2503.0] 1 [2113.0, 6999.0, 2314.0] 2 [2111.0, 6999.0, 2111.0, 2362.0, 2503.0] 3 [2100.0, 6999.0, 2362.0, 2113.0] 4 [2111.0, 6999.0, 2111.0, 2503.0] with something like this (Nan at the end of list): 0 [2116.0, 6999.0, 2116.0, 2166.0, 2503.0] 1 [2113.0, 6999.0, 2314.0, NaN, NaN] 2 [2111.0, 6999.0, 2111.0, 2362.0, 2503.0] 3 [2100.0, 6999.0, 2362.0, 2113.0, NaN] 4 [2111.0, 6999.0, 2111.0, 2503.0, NaN]
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92283415
has title: How to pad Pandas dataframe column with different sizes with Nan values
favorite count: 0
score: 6

http://stackoverflow.com/a/52605287
score: 3
upvote count: 3
has body: Just to point this out: statsmodel's least squares fit does by default not include a constant. If we remove the constant from R's fit, we get very similar results to the Python implementation, or the other way around, if we add a constant to the statsmodel-fit, we get similar results to R: Remove the constant in R's lm-call: summary(lm(Temp ~ . - 1, data = train[,3:NCOL(train)])) Call: lm(formula = Temp ~ . - 1, data = train[, 3:NCOL(train)]) Residuals: Min 1Q Median 3Q Max -0.221940 -0.032347 0.002071 0.037048 0.167294 Coefficients: Estimate Std. Error t value Pr(&gt;|t|) MEI 0.036076 0.027983 1.289 0.2079 CO2 0.004640 0.008945 0.519 0.6080 CH4 -0.002328 0.002132 -1.092 0.2843 N2O -0.014115 0.079452 -0.178 0.8603 `CFC-11` -0.031232 0.096693 -0.323 0.7491 `CFC-12` 0.035760 0.103574 0.345 0.7325 TSI -0.003283 0.036861 -0.089 0.9297 Aerosols 69.968040 33.093275 2.114 0.0435 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.07457 on 28 degrees of freedom Multiple R-squared: 0.9724, Adjusted R-squared: 0.9645 F-statistic: 123.1 on 8 and 28 DF, p-value: &lt; 2.2e-16 Let's add a constant to statsmodel's call: X_with_constant = sm.add_constant(X) model = sm.OLS(y, X_with_constant).fit() model.summary() gives us identical results: OLS Regression Results Dep. Variable: Temp R-squared: 0.535 Model: OLS Adj. R-squared: 0.397 Method: Least Squares F-statistic: 3.877 Date: Tue, 02 Oct 2018 Prob (F-statistic): 0.00372 Time: 10:14:03 Log-Likelihood: 46.899 No. Observations: 36 AIC: -75.80 Df Residuals: 27 BIC: -61.55 Df Model: 8 Covariance Type: nonrobust coef std err t P&gt;|t| [0.025 0.975] const -17.8663 563.008 -0.032 0.975 -1173.064 1137.332 MEI 0.0361 0.029 1.265 0.217 -0.022 0.095 CO2 0.0048 0.011 0.451 0.656 -0.017 0.027 CH4 -0.0024 0.002 -0.950 0.351 -0.007 0.003 N2O -0.0130 0.088 -0.148 0.884 -0.194 0.168 CFC-11 -0.0332 0.116 -0.285 0.777 -0.272 0.205 CFC-12 0.0378 0.123 0.307 0.761 -0.215 0.290 TSI 0.0091 0.392 0.023 0.982 -0…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52596724
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52596724
type: Answer

http://stackoverflow.com/comment/92210089
type: QuestionComment
type: Comment
score: 0
has text: do you want to extract zipcode from this string ?`'29.607416999999998 ,-95.114007 Pinebrook KinderCare, 4422, Clear Lake City Boulevard, Houston, Harris County, Texas, 77059, USA 29.74770501 ,-95.39656199 2345, Commonwealth Street, Houston, Harris County, Texas, 77006, USA 29.707028 ,-95.59624701 Hastings Ninth Grade Center, 6750, Cook Road, Houston, Harris County, Texas, 77072, USA 29.59038673 ,-95.47975719 6333, Court Road, Houston, Fort Bend County, Texas, 77053, USA 29.67591366 ,-95.32867835 7084, Crestmont Street, Houston, Harris County, Texas, 77033, USA '`
comment on: http://stackoverflow.com/q/52638228

http://stackoverflow.com/a/52645348
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52645142
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52645142
type: Answer
score: 2
has body: We can't say that the JSON is invalid but you should avoid having similar key names (questions in your example) RFC 7159 explains why unique names (keys) are good: An object whose names are all unique is interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates. JSON parsing libraries have been observed to differ as to whether or not they make the ordering of object members visible to calling software. Implementations whose behavior does not depend on member ordering will be interoperable in the sense that they will not be affected by these differences. You can try converting your JSON into the given format: { "letters": { "part one": { "meem": { "questions": [ { "question": "What sound does 'م' make?", "arabic": "م", "transliteration": "m", "english": "m", "answer": "m", "wronganswer": [ "a", "b", "kh", "ta", "da", "du", "ee", "yeh", "he", "ha", "l", "n", "f" ] }, { "question": "What letters are in the word 'وز'?", "arabic": "موز", "transliteration": "mooz", "english": "banana", "answer": "م و ز", "wronganswer": [ "ه و ز", "ه و ر", "م ف ز", "م و ر", "ه ف ر" ] }, { "question": "What word do the letters 'ه ر م' make", "arabic": "ه ر م", "transliteration": "haram", "english": "pyramid", "answer": "هرم", "wronganswer": [ "مرم", "هزم", "موم", "مرع", "هبم" ] } ] } } } } Then you can do something like this to fetch a random question from the list of questions: import json from random import randint def random_question(): with open('result.json') as fp: data = json.load(fp) questions = data["letters"]["part one"]["meem"]["questions"] random_index = randint(0, len(questions)-1) return ques…

http://stackoverflow.com/a/52657224
score: 2
answers question: http://stackoverflow.com/q/52657192
upvote count: 2
downvote count: 0
type: Answer
has body: You can use double slicing like this for i in x[::-1][1:]: print(i)

ms-access
tags question: http://stackoverflow.com/q/52685016
tag name: ms-access
tags question: http://stackoverflow.com/q/52695632
type: Tag
tags question: http://stackoverflow.com/q/52695025

http://stackoverflow.com/comment/92224474
score: 2
comment on: http://stackoverflow.com/a/52646252
type: AnswerComment
has text: This seems a bit overblown to me for such a simple problem.
type: Comment

http://stackoverflow.com/comment/92158999
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52612040
has text: What is `scene_map`?

ajax
tags question: http://stackoverflow.com/q/52657775
tags question: http://stackoverflow.com/q/52736004
tags question: http://stackoverflow.com/q/52746198
type: Tag
tags question: http://stackoverflow.com/q/52693786
tags question: http://stackoverflow.com/q/52743188
tags question: http://stackoverflow.com/q/52692042
tags question: http://stackoverflow.com/q/52722227
tags question: http://stackoverflow.com/q/52633511
tags question: http://stackoverflow.com/q/52683168
tags question: http://stackoverflow.com/q/52633383
tag name: ajax

http://stackoverflow.com/comment/92295991
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52681536
type: Comment
has text: Ok, if I use socat (a some sort of netcat) it works great as you told. I've also tried the again with a browser but using the Content-Type text/event-stream method inside the python script, but unfortunately the browser now ask me to open or save a file. Why?

http://stackoverflow.com/comment/92152009
has text: I don't have time to sift through all your code, but if you need a hint, it looks like the violation in that last one is in the creation of the bottom walls. From the provided link: "If a cell is the only member of its set, do not create a bottom-wall" You created a bottom wall for the cell in set 22. Find out why.
type: QuestionComment
comment on: http://stackoverflow.com/q/52608414
type: Comment
score: 0

http://stackoverflow.com/comment/92314701
comment on: http://stackoverflow.com/q/52693969
type: QuestionComment
type: Comment
has text: `other_function.__doc__ = ...`, or maybe even `@functools.wraps`. But are you really sure they should use the same doc?
score: 0

http://stackoverflow.com/q/52695632
score: 0
answer count: 1
tagged with: ms-access
tagged with: multiple-columns
tagged with: pull
tagged with: python
type: AnsweredQuestion
has body: I have a ton of variables but lets just say i have one, i am trying to make it so i have an if statement that says if it runs across a certain number in the database take the variable value and add one to it. I have been researching for a little bit now and haven't found any thing i think is valuable. Does anyone know if you can do this in python if so can you please help? thank you. I am thinking it might need to be a for loop because it is a repeating process but i do not know.
has comment: http://stackoverflow.com/comment/92317719
accepted answer: http://stackoverflow.com/a/52695792
type: Question
has comment: http://stackoverflow.com/comment/92317671
tagged with: database
has title: if a database contains a certain value add x amount to a variable (python)
has answer: http://stackoverflow.com/a/52695792

http://stackoverflow.com/comment/92229157
type: AnswerComment
comment on: http://stackoverflow.com/a/52646056
score: 0
type: Comment
has text: with a small change it works `subprocess.call(['cmd', '/c', 'start', "", "C:/Users/akg/Desktop/file 1.png"])`

http://stackoverflow.com/comment/92399454
type: QuestionComment
score: 1
has text: You can create new dataframe out of the existing one :- dfnew=df['foo']
comment on: http://stackoverflow.com/q/52737165
type: Comment

http://stackoverflow.com/q/52647097
accepted answer: http://stackoverflow.com/a/52647251
has comment: http://stackoverflow.com/comment/92226167
has comment: http://stackoverflow.com/comment/92226236
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92226372
favorite count: 0
has answer: http://stackoverflow.com/a/52647251
tagged with: python-3.x
has title: Cannot replace the double space in the array Python
tagged with: python
has comment: http://stackoverflow.com/comment/92226311
has body: Here is what I tried and what I am trying to achieve: &gt;&gt;&gt; d = [[0.4246955,0.42829293,0.43621248,0.42680067], ... [0.42453277,0.42806646,0.43601942,0.42658913], ... [0.42681128,0.43040696,0.43824464,0.42888936], ... [0.42648485,0.4299298,0.43789476,0.42854127], ... [0.42436373,0.4276249,0.43576592,0.4263624]] &gt;&gt;&gt; d [[0.4246955, 0.42829293, 0.43621248, 0.42680067], [0.42453277, 0.42806646, 0.43601942, 0.42658913], [0.42681128, 0.43040696, 0.43824464, 0.42888936], [0.42648485, 0.4299298, 0.43789476, 0.42854127], [0.42436373, 0.4276249, 0.43576592, 0.4263624]] &gt;&gt;&gt; print(d) [[0.4246955, 0.42829293, 0.43621248, 0.42680067], [0.42453277, 0.42806646, 0.43601942, 0.42658913], [0.42681128, 0.43040696, 0.43824464, 0.42888936], [0.42648485, 0.4299298, 0.43789476, 0.42854127], [0.42436373, 0.4276249, 0.43576592, 0.4263624]] &gt;&gt;&gt; s = "" &gt;&gt;&gt; for i in d: ... s = s+str(i).replace("[","").replace("]","").replace(",","").strip()+"\n" ... &gt;&gt;&gt; s '0.4246955 0.42829293 0.43621248 0.42680067\n0.42453277 0.42806646 0.43601942 0.42658913\n0.42681128 0.43040696 0.43824464 0.42888936\n0.42648485 0.4299298 0.43789476 0.42854127\n0.42436373 0.4276249 0.43576592 0.4263624\n' &gt;&gt;&gt; print(s) 0.4246955 0.42829293 0.43621248 0.42680067 0.42453277 0.42806646 0.43601942 0.42658913 0.42681128 0.43040696 0.43824464 0.42888936 0.42648485 0.4299298 0.43789476 0.42854127 0.42436373 0.4276249 0.43576592 0.4263624 &gt;&gt;&gt; s = s.replace(" ","0 ") &gt;&gt;&gt; print(s) 0.4246955 0.42829293 0.43621248 0.42680067 0.42453277 0.42806646 0.43601942 0.42658913 0.42681128 0.43040696 0.43824464 0.42888936 0.42648485 0.4299298 0.43789476 0.42854127 0.42436373 0.4276249 0.43576592 0.4263624 As one can see that the each element is not of the same length. Hence, while converting to string I am getting double spaces, which disturbing my splitting process in another program. I wanted to know how I can replace the double spaces with single space or with 0 and sp…
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52647341
has comment: http://stackoverflow.com/comment/92226365
type: Question
has answer: http://stackoverflow.com/a/52647341
answer count: 2
tagged with: arrays
has comment: http://stackoverflow.com/comment/92226176

http://stackoverflow.com/a/52681809
has body: There is a bug in your code. Here is the rectified code. user_input = 7 x = 1 temp = user_input spaces = " " stars = "" y = temp - 2 t = 0 while x &lt;= temp: stars = "*" * x spaces = spaces * y print(spaces + stars) spaces= " " y -= 1 x += 2 It is not necessary to check y&gt;0 since your first while loop is enough to meet the requirement. Because of that extra while loop you are getting ambiguous values of (x,y).
answers question: http://stackoverflow.com/q/52681460
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/92291839
downvote count: 0
score: 1

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/52655656
type: Tag

http://stackoverflow.com/a/52658812
answers question: http://stackoverflow.com/q/52658557
score: 0
type: Answer
has body: calSum was assigning myList to n, but it was INSIDE the calSum and anything OUTSIDE this def was unable to read it, as it is local variable. Same thing about n from readList. It's local. So "n" in readList and "n" in calSum does not exist outside those functions and can not be used anywhere else. You were able to use "n" from readList, only because you used return, which returned this value to the rest of the program. And in the very same way you have to make in in calSum to make it work. Google for global and local variables in python for more information on topic :) def readList(): n=int(input("Input from readList")) while n!=0: n=int(input("Looped input from readList")) return n def calSum(n): n=myList return n #Added return as student suggested myList = readList() sum = calSum(myList) print(sum)

http://stackoverflow.com/a/52798774
type: Answer
score: 0
has body: I got same error. Did not find any answer online, but ultimately resolved by preceding with az login command to login form Azure CLI (https://learn.microsoft.com/en-us/cli/azure/reference-index?view=azure-cli-latest#az-login). Hope this helps.
answers question: http://stackoverflow.com/q/52604824

http://stackoverflow.com/comment/92167062
type: QuestionComment
score: 2
has text: I'm too lazy to tar a csv file and post a complete and tested solution, but you should take a look at [`io.TextIOWrapper`](https://docs.python.org/3/library/io.html#io.TextIOWrapper).
comment on: http://stackoverflow.com/q/52616363
type: Comment

http://stackoverflow.com/comment/92161814
type: Comment
has text: Also there might be a more efficient way to solve the rest of your problem, if you can post the expected output
comment on: http://stackoverflow.com/a/52602325
type: AnswerComment
score: 0

http://stackoverflow.com/a/52612106
accepted answer of: http://stackoverflow.com/q/52600278
type: Answer
answers question: http://stackoverflow.com/q/52600278
score: 10
upvote count: 10
has body: You should specify a user_agent. The Nominatum service runs on donated servers which have limited capacity, so specifying a user-agent field allows Open Street Map to track more easily who is using their service. See here for a more detailed answer. If you don't they may block your IP address from accessing the service as that would be a violation of their terms of service.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92193745
type: AnswerComment
has text: This works but is a little bit beyond my comprehension/skillset currently. I understand how lambda x: works but confused with the layers of how f is defined. Explanation not required but greatly appreciated!
type: Comment
comment on: http://stackoverflow.com/a/52629906
score: 0

http://stackoverflow.com/a/52696588
score: 1
has body: In my experience time.sleep() does not work well with dynamic loading times. If the page is javascript-heavy you have to use the WebDriverWait clause. Something like this: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get(url) element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "[my-attribute='my-value']"))) Change 10 with whatever timer you want, and By.CSS_SELECTOR and its value with whatever type you want to use as a reference for a lo You can also wrap the WebDriverWait around a Try/Except statement with the TimeoutException exception, which you can get from the submodule selenium.common.exceptions in case you want to set a hard limit. You can probably set it inside a while loop if you truly want it to check forever until the page's loaded, because I couldn't find any reference in the docs about waiting "forever", but you'll have to experiment with it.
downvote count: 0
answers question: http://stackoverflow.com/q/52696433
type: Answer
upvote count: 1

http://stackoverflow.com/comment/92370248
has text: Keep in mind that "edit" means that anybody can fix the question. When only the OP can fix it, then edit is wrong. Then you probably want to close vote the question.
comment on: http://stackoverflow.com/q/52632610
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/92258081
type: Comment
comment on: http://stackoverflow.com/a/52664003
score: 0
type: AnswerComment
has text: @schwobaseggl it might be slower than your solution but hard to be sure without timing on different data sets, your solution (which I also like) also has the `len()` calls and the slower `for` loop etc.

http://stackoverflow.com/comment/92389313
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52731163
type: Comment
has text: All imports are only done once and are cached in `sys.modules` so there's no downside to importing a module inside a function. You can see https://docs.python.org/3/reference/import.html for details.

http://stackoverflow.com/comment/92274947
type: Comment
has text: I find it difficult to understand what you're asking. Little nitpick with the code you shared, that is `MongoClient = MongoClient("mongodb://localhost:27017/")`. `MongoClient` is shadowed with an instance of the client connected to mongo database running on localhost
comment on: http://stackoverflow.com/q/52671209
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92737794
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52687695
type: AnswerComment
has text: The example is a little way out, but it is about the UNION.

http://stackoverflow.com/a/52657013
upvote count: 1
has body: It's very simple with numpy: posvals = data &gt; 0 &gt;&gt; [True, False, True, True, False, True, True, False, False, False] If you explicitly want 1s and 0s: posvals.astype(int) &gt;&gt; [1, 0, 1, 1, 0, 1, 1, 0, 0, 0]
downvote count: 0
answers question: http://stackoverflow.com/q/52656993
score: 1
type: Answer

http://stackoverflow.com/q/52631022
tagged with: for-loop
has comment: http://stackoverflow.com/comment/92195795
upvote count: 0
has title: Python: Help to create a loop?
favorite count: 0
has comment: http://stackoverflow.com/comment/92195744
tagged with: while-loop
type: Question
tagged with: python
score: -2
has body: I have to do this function in a loop. I would like to pass x. x, which indicates how many times the loop should go through. It's about my data getting longer and longer: def get_data(x): ts = round(time.time()) url = 'https://api.bitfinex.com/v2/candles/trade:' timeframe = '1h:' symbol = 'tBTCUSD' period = 120 * 3600 # max. 120 start = '/hist?start=' + str((ts - period) * 1000) end = '&amp;end=' + str(ts * 1000) string = url + timeframe + symbol + start + end response = requests.get(string) data = response.json() time.sleep(1) period2 = x * period start = '/hist?start=' + str((ts - period2 - 3600) * 1000) end = '&amp;end=' + str((ts - period - 3600) * 1000) string = url + timeframe + symbol + start + end response = requests.get(string) data1 = response.json() data.extend(data1) time.sleep(1) return data How can I accomplish this task?
downvote count: 2
tagged with: loops
has answer: http://stackoverflow.com/a/52631266
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/a/52736785
has comment: http://stackoverflow.com/comment/117118541
has comment: http://stackoverflow.com/comment/118952559
has comment: http://stackoverflow.com/comment/118944860
has comment: http://stackoverflow.com/comment/101250169
has body: You can use the imagehash library to compare similar images. from PIL import Image import imagehash hash0 = imagehash.average_hash(Image.open('quora_photo.jpg')) hash1 = imagehash.average_hash(Image.open('twitter_photo.jpeg')) cutoff = 5 # maximum bits that could be different between the hashes. if hash0 - hash1 &lt; cutoff: print('images are similar') else: print('images are not similar') Since the images are not exactly the same, there will be some differences, so therefore we use a cutoff value with an acceptable maximum difference. That difference between the hash objects is the number of bits that are flipped. But imagehash will work even if the images are resized, compressed, different file formats or with adjusted contrast or colors. The hash (or fingerprint, really) is derived from a 8x8 monochrome thumbnail of the image. But even with such a reduced sample, the similarity comparisons give quite accurate results. Adjust the cutoff to find a balance between false positives and false negatives that is acceptable. With 64 bit hashes, a difference of 0 means the hashes are identical. A difference of 32 means that there's no similarity at all. A difference of 64 means that one hash is the exact negative of the other.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/117109432
has comment: http://stackoverflow.com/comment/92413740
has comment: http://stackoverflow.com/comment/92413173
has comment: http://stackoverflow.com/comment/101251212
has comment: http://stackoverflow.com/comment/137361344
has comment: http://stackoverflow.com/comment/101253255
type: Answer
answers question: http://stackoverflow.com/q/52736154
has comment: http://stackoverflow.com/comment/92413244
has comment: http://stackoverflow.com/comment/96454739
accepted answer of: http://stackoverflow.com/q/52736154
upvote count: 77
downvote count: 1
has comment: http://stackoverflow.com/comment/92413499
score: 76

http://stackoverflow.com/comment/92299632
type: Comment
score: 2
has text: @AntonvBR If by "ids" you mean the values returned from [the `id()` builtin function](https://docs.python.org/3/library/functions.html#id): they might be. In the standard Python interpreter (CPython), at least currently, `id()` does give the memory address. Other Python interpreters (or future versions of CPython) might do it differently.
type: AnswerComment
comment on: http://stackoverflow.com/a/52686032

http://stackoverflow.com/q/52619372
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/52619483
tagged with: arrays
tagged with: dataframe
score: -1
has body: I have a fairly lage dataframe, df2 (~50,000 rows x 2,000 columns). The column headings are sample names. Separately, I have a dataframe, df1, with a list of samples I want to include in my analysis as the df1 index. I want to use the list of samples from df1 index to select only the columns from df2 for those selected samples, discarding the rest. I also want to preserve the sample order from the df1 index. Example data: # df1 data1 = {'Sample': ['Sample_A','Sample_D', 'Sample_E'], 'Location': ['Bangladesh', 'Myanmar', 'Thailand'], 'Year':[2012, 2014, 2015]} df1 = pd.DataFrame(data1) df1.set_index('Sample') # df2 data2 = {'Num': ['Value_1','Value_2','Value_3','Value_4','Value_5'], 'Sample_A': [0,1,0,0,1], 'Sample_B':[0,0,1,0,0], 'Sample_C':[1,0,0,0,1], 'Sample_D':[0,0,1,1,0]} df2 = pd.DataFrame(data2) df2.set_index('Num') First I generate the list of samples I want from the index of df1, e.g. samples = df1['Sample'].tolist() 'samples' is then, ['Sample_A', 'Sample_D', 'Sample_E'] And using 'samples', my desired output dataframe, df3, should look like: index Sample_A Sample_D Value_1 0 0 Value_2 1 0 Value_3 0 1 Value_4 0 1 Value_5 1 0 But if I use df3 = df2[samples] Then I get the error message: "['Sample_E'] not in index" So how do I ignore samples that are not found in df2 to avoid this error message? UPDATE The solution that worked - # 1. Define samples to use from df1 samples = df1['Sample'].tolist() # Only include samples that are found in df2 as well final_samples = list(set(list(df2.columns)) &amp; set(samples )) # Make new df with columns corresponding to final_samples df3 = df2.loc[:, final_samples]
answer count: 2
tagged with: pandas
has title: How to select and order columns in a dataframe using an array in Python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52619483
possible better answer: http://stackoverflow.com/a/52619416
tagged with: python
has answer: http://stackoverflow.com/a/52619416
type: AnsweredQuestion

http://stackoverflow.com/q/52608420
has answer: http://stackoverflow.com/a/74429820
upvote count: 1
type: AnsweredQuestion
tagged with: syntax
score: 1
type: Question
has title: How to disable error syntax highlight Sublime Text 3
answer count: 2
has answer: http://stackoverflow.com/a/52616762
downvote count: 0
favorite count: 0
has body: I am using a language I made with a similar syntax to python, and I wanted to use python syntax highlighting for my language as well. The only problem is that my language uses curly brackets rather then : and indents. So some times when I type return for example it highlights the return in red. Is there any way I can disable error highlights? Here is an Example:
tagged with: python
tagged with: sublimetext3
accepted answer: http://stackoverflow.com/a/52616762
possible better answer: http://stackoverflow.com/a/74429820

http://stackoverflow.com/q/52718723
tagged with: python-3.x
tagged with: ddos
type: UnansweredQuestion
tagged with: sockets
tagged with: python
answer count: 0
score: 1
upvote count: 1
has title: Protect socket from DOS and DDOS using python
has body: Here is my socket server and client: import socket import threading import chardet bind_ip = '0.0.0.0' bind_port = 9999 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(1) # max backlog of connections print (('Listening on {}:{}').format(bind_ip, bind_port)) def handle_client_connection(client_socket): request = client_socket.recv(4096 ) result = chardet.detect(request) print(result) print (request.decode(result['encoding'])) client_socket.send('ACK!'.encode(result['encoding'])) client_socket.close() while True: client_sock, address = server.accept() print (('Accepted connection from {}:{}').format(address[0], address[1])) client_handler = threading.Thread( target=handle_client_connection, args=(client_sock,) # without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject ) client_handler.start() The client is this: import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('127.0.0.1', 9999)) client.send(str('test data').encode("utf-16")) response = client.recv(4096) print(response.decode("utf-16")) How to make the socket server secured from DOS or DDos attacks?
type: Question
downvote count: 0
favorite count: 0
tagged with: denial-of-service

http://stackoverflow.com/a/52648506
upvote count: 3
type: Answer
has body: Your approach is correct, however you don't need to use the additional_variables variables argument. If you omit it, your code will run without issues. The purpose of additional_variables to EntitySet.normalize_entity is to include other variables you want in new parent entity you are creating. For example, say you had variables about a hire date, salary, location, etc. You would put those as additional variables because they are static with respect to a worker. In this, case I don't think you have any variables like that. Here is the code and output I see import pandas as pd import featuretools as ft import featuretools.variable_types as vtypes d = {'PURCHASE_ID': [1, 2], 'WORKER_ID': [0, 0], 'ACCOUNT_ID': [1, 2], 'COST': [5, 10], 'PURCHASE_TIME': ['2018-01-01 01:00:00', '2016-01-01 02:00:00']} df = pd.DataFrame(data=d) data_variable_types = {'PURCHASE_ID': vtypes.Id, 'WORKER_ID': vtypes.Id, 'ACCOUNT_ID': vtypes.Id, 'COST': vtypes.Numeric, 'PURCHASE_TIME': vtypes.Datetime} es = ft.EntitySet('Purchase') es = es.entity_from_dataframe(entity_id='purchases', dataframe=df, index='PURCHASE_ID', time_index='PURCHASE_TIME', variable_types=data_variable_types) es.normalize_entity(base_entity_id='purchases', new_entity_id='workers', index='WORKER_ID', make_time_index=False) es.normalize_entity(base_entity_id='purchases', new_entity_id='accounts', index='ACCOUNT_ID', make_time_index=False) fm, features = ft.dfs(entityset=es, target_entity='purchases', agg_primitives=['mean'], trans_primitives=[], verbose=True) features this outputs [&lt;Feature: WORKER_ID&gt;, &lt;Feature: ACCOUNT_ID&gt;, &lt;Feature: COST&gt;, &lt;Feature: workers.MEAN(purchases.COST)&gt;, &lt;Feature: accounts.MEAN(purchases.COST)&gt;] If we change the target entity and increase the depth fm, features = ft.dfs(entityset=es, target_entity='workers', agg_primitives=['mean', 'count'], max_depth=3, trans_primitives=[], verbose=True) features the output is now features for the workers entity [&lt;Feature: COUNT(…
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/52629549
answers question: http://stackoverflow.com/q/52629549
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92270242

http://stackoverflow.com/a/52670160
accepted answer of: http://stackoverflow.com/q/52670097
answers question: http://stackoverflow.com/q/52670097
type: AcceptedAnswer
has body: Flask 1.0.2 sets minimum versions for its dependencies. Your requirements.txt file has pinned those dependencies to incompatible versions. Update your requirements.txt file. Specifically, your pip output: Collecting Jinja2==2.9.6 (from -r requirements.txt (line 3)) [...] Collecting Werkzeug==0.12.2 (from -r requirements.txt (line 5)) tells you what lines to update in that file. The error message tells you what the minimum versions are: ---&gt; flask 1.0.2 has requirement Jinja2&gt;=2.10, but you'll have jinja2 2.9.6 which is incompatible. ---&gt; flask 1.0.2 has requirement Werkzeug&gt;=0.14, but you'll have werkzeug 0.12.2 which is incompatible. so you must, at the very least, change those lines to use those specific minimum version pins. I would suggest you should avoid using exact version pins for every package in your requirements.txt file, and instead only pin your most important top-level packages. Pin Flask, but not the dependencies, and leave it to pip to find you compatible versions of those dependencies; you could just remove the dependencies from the requirements.txt file altogether. Even better, switch to Pipenv instead of a requirements.txt file, use that to specify top-level dependencies, and leave pinning dependency versions to Pipenv. This gives you the best of both worlds; a configuration file to specify your own project dependencies (Pipfile), and a separate file with the pinned versions for the current setup (Pipfile.lock).
type: Answer
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/comment/92339385
type: Comment
comment on: http://stackoverflow.com/q/52706164
type: QuestionComment
score: 2
has text: The problem is that you are using a random module from 2009, which probably does not follow the "standard API" and may not have feature parity with it. I'd use something like [`murmurhash`](https://pypi.org/project/murmurhash/) or [`mmh3`](https://pypi.org/project/mmh3/) instead.

http://stackoverflow.com/comment/92150251
type: Comment
comment on: http://stackoverflow.com/a/52608046
type: AnswerComment
score: 0
has text: As i wrote in the text i have a csv file, with many lines i want to split into multiple files with x (example 100) lines in each.

http://stackoverflow.com/q/52673474
tagged with: package
tagged with: python
tagged with: namespaces
downvote count: 0
tagged with: setuptools
has body: I have written three Python modules, two of them are independent but the last one would depend on the two independent modules. For example, consider the following structure myProject/ subpackage_a/ __init__.py ... subpackage_b/ __init__.py ... mainpackage/ __init__.py ... mainpackage depends on subpackage_a and subpackage_b, where as subpackage_a and subpackage_b can be used independently. In other words, in mainpackage, there are references to subpackage_a and subpackage_b. In a nutshell, I want the user to be able to do from myProject import subpackage_a and start doing subpackage_a.subfunction(args) without calling mainpackage. I also want the user to use from myProject import mainpackage and start using mainpackage.mainfucntion(args), where mainpackage.mainfucntion will call the functions in the subpackages. I learned about namespace packaging. However, I couldn't find anything on namespace packages that involve dependencies. I don't have to use namespace packaging if there's a better solution. Can I get some suggestions on what I should look for?
upvote count: 8
type: Question
linked to: http://stackoverflow.com/q/35668295
has answer: http://stackoverflow.com/a/70365732
has title: How do I handle namespace packages that will serve as dependencies for another package
answer count: 1
favorite count: 0
score: 8
has comment: http://stackoverflow.com/comment/92313164
type: UnansweredQuestion

http://stackoverflow.com/q/52696757
has answer: http://stackoverflow.com/a/52696859
has comment: http://stackoverflow.com/comment/92319889
tagged with: python
tagged with: regex
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52696892
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52696890
has comment: http://stackoverflow.com/comment/92319925
has comment: http://stackoverflow.com/comment/92319939
has comment: http://stackoverflow.com/comment/92320340
answer count: 3
has body: Here is my text (he needs to buy him an) [/-] (.) this rabbit &lt;I&gt; [/] is (..) woke up (...) (be)cause he needs to go home with his father . Desired Output is he needs to buy him an [/-] (.) this rabbit &lt;I&gt; [/] is (..) woke up (...) because he needs to go home with his father .
favorite count: 0
has title: How can i remove only brackets that has only string not special Characters
has comment: http://stackoverflow.com/comment/92320116
score: 0

http://stackoverflow.com/q/52692529
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92312042
upvote count: 1
has answer: http://stackoverflow.com/a/60602594
has title: Image not appearing in template in django 2.1
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/92312511
favorite count: 0
tagged with: django-templates
has comment: http://stackoverflow.com/comment/92319430
has body: full file tree I am making a profile page for my website. I have followed a couple peoples instructions online and I did what they said (i.e. media_url, media_root, changes to my urls.py). I register my superuser through the admin page, and I give it a profile. When trying to get my image, it does not display. Here is my code: Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Pic = models.ImageField(default='default.png', blank=True, upload_to='img') address = models.CharField(max_length=70, default='Bensons', unique=True) email = models.EmailField(max_length=70, unique=True, default='ben@email.com') def __str__(self): return self.address settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=ytl^8!j@t(^c5eile%%x(l3hvkekc$z#_t538+%a)p2uvsr!+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.1.192'] STATIC_URL = '/static/' # Application definition INSTALLED_APPS = [ 'crispy_forms', 'index.apps.IndexConfig', 'django.contrib.admin', 'django.contrib.auth', #yoohoo 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.…
has comment: http://stackoverflow.com/comment/92312396
type: UnansweredQuestion
tagged with: django
tagged with: python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52692693
has comment: http://stackoverflow.com/comment/92312081
tagged with: django-models

http://stackoverflow.com/a/52746882
score: -1
upvote count: 0
has body: Because once you've set a choice for choose1, it never gets set again. The quick way to fix this would be to add an input after the two while loops for choose2, although you may want to look into making your code neater through making functions for the common logic while(choose2=="y"): .... choose1 = input("Enter y for yes or n for no.")
answers question: http://stackoverflow.com/q/52746653
type: Answer
downvote count: 1

http://stackoverflow.com/comment/92318754
score: 0
comment on: http://stackoverflow.com/q/52695805
has text: Here: https://js.tensorflow.org/tutorials/import-saved-model.html and here: https://js.tensorflow.org/tutorials/import-keras.html
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92195853
score: 0
comment on: http://stackoverflow.com/q/52631288
has text: df2 = spark.sql("SELECT field1 AS f1, field2 as f2 from table1") http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/139787862
type: AnswerComment
has text: @kithuto it turns out that `undetected_chromedriver` does not work in headless mode, thus not bypassing the captcha
type: Comment
comment on: http://stackoverflow.com/a/52636871
score: 0

tensor
tags question: http://stackoverflow.com/q/52595477
tags question: http://stackoverflow.com/q/52656692
tags question: http://stackoverflow.com/q/52670060
tags question: http://stackoverflow.com/q/52674760
tag name: tensor
type: Tag
tags question: http://stackoverflow.com/q/52616650

http://stackoverflow.com/comment/92201516
type: Comment
has text: It returns None in all cases
comment on: http://stackoverflow.com/a/52633715
type: AnswerComment
score: 0

http://stackoverflow.com/a/58243606
has comment: http://stackoverflow.com/comment/128480047
has comment: http://stackoverflow.com/comment/102859702
has body: It is impossible to reference finalized object in weakref.finalize. In "Note" section for weakref.finalize it is stated: It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj. Thus, it is also impossible to orginize cleanup with bound method like weakref.finalize(obj, obj.close). In such case you need to call cleanup function yourself. Another option is to inherit from SomeClass and make proper __del__ method.
answers question: http://stackoverflow.com/q/52648418
has comment: http://stackoverflow.com/comment/126849774
has comment: http://stackoverflow.com/comment/102859475
has comment: http://stackoverflow.com/comment/102905235
has comment: http://stackoverflow.com/comment/126851680
accepted answer of: http://stackoverflow.com/q/52648418
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/126830292
downvote count: 0
has comment: http://stackoverflow.com/comment/102901449
has comment: http://stackoverflow.com/comment/102859408
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/131514637
has comment: http://stackoverflow.com/comment/102859455
upvote count: 6
has comment: http://stackoverflow.com/comment/102859413
has comment: http://stackoverflow.com/comment/131514594

rsync
tags question: http://stackoverflow.com/q/52693273
tag name: rsync
type: Tag

http://stackoverflow.com/a/52735335
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52705347
score: 2
downvote count: 0
has body: The problem was that instead of providing an arbitrary unicode key to the pyotp library (as well as to Google Authenticator), a Base32 string was needed as the input, which I assume was later decoded to a byte array and used by the library. So I provided OtpSharp with the byte string representation of an arbitrary unicode string and used an online website to decode the unicode string to a base32 string, and used the base32 string in Google Authenticator. To put it simply, Otpsharp requires a byte array to initialize a totp object, while pyotp needs you to provide it with a base32 string.

http://stackoverflow.com/comment/92405028
type: Comment
has text: Works great. Thanks a lot!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52740183

http://stackoverflow.com/q/52676020
has comment: http://stackoverflow.com/comment/126291095
downvote count: 0
upvote count: 135
has answer: http://stackoverflow.com/a/52676770
has answer: http://stackoverflow.com/a/55889608
has answer: http://stackoverflow.com/a/79202228
has answer: http://stackoverflow.com/a/73371285
score: 135
has answer: http://stackoverflow.com/a/61030487
has answer: http://stackoverflow.com/a/72079432
has answer: http://stackoverflow.com/a/61047641
has answer: http://stackoverflow.com/a/54563085
answer count: 24
possible better answer: http://stackoverflow.com/a/57674734
has answer: http://stackoverflow.com/a/76487180
favorite count: 0
has answer: http://stackoverflow.com/a/57764216
has answer: http://stackoverflow.com/a/70126500
has answer: http://stackoverflow.com/a/57674734
accepted answer: http://stackoverflow.com/a/52676770
has body: I am trying to do a basic colour conversion in python however I can't seem to get past the below error. I have re-installed python, opencv and tried on both python 3.4.3 (latest) and python 2.7 (which is on my Mac). I installed opencv using python's package manager opencv-python. Here is the code that fails: frame = cv2.imread('frames/frame%d.tiff' % count) frame_HSV= cv2.cvtColor(frame,cv2.COLOR_RGB2HSV) This is the error message: cv2.error: OpenCV(3.4.3) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
tagged with: python
has answer: http://stackoverflow.com/a/64895781
has answer: http://stackoverflow.com/a/68788649
has answer: http://stackoverflow.com/a/74423167
has answer: http://stackoverflow.com/a/61450736
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64151752
has answer: http://stackoverflow.com/a/63141738
has answer: http://stackoverflow.com/a/70633830
has comment: http://stackoverflow.com/comment/92285219
has answer: http://stackoverflow.com/a/58280305
has answer: http://stackoverflow.com/a/54759627
has answer: http://stackoverflow.com/a/59012924
has answer: http://stackoverflow.com/a/70654658
type: Question
has title: imread returns None, violating assertion !_src.empty() in function 'cvtColor' error
has answer: http://stackoverflow.com/a/56844609

http://stackoverflow.com/a/56553885
answers question: http://stackoverflow.com/q/52723472
score: 1
has comment: http://stackoverflow.com/comment/99712489
type: Answer
upvote count: 1
has body: The function glutMouseFunc() should be defined before glutMouseWheelFunc() the example now works from your code with the following on Linux: from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from OpenGL.GLUT.freeglut import * def mouse(button, state, x, y): print(button, state, x, y) def on_wheel(wheel, direction, x, y): print(wheel, direction, x, y) glutInit() glutInitWindowSize(100, 100) glutCreateWindow("glutMouseWheelFunc test") glutMouseFunc( mouse ) glutMouseWheelFunc( on_wheel ) glutMainLoop()
downvote count: 0

http://stackoverflow.com/comment/92143067
comment on: http://stackoverflow.com/q/52601558
score: 0
type: Comment
type: QuestionComment
has text: Maybe https://regex101.com/r/BNI35Z/1?

http://stackoverflow.com/a/52632007
type: Answer
score: 2
has body: Try instead: row = pd.Categorical(data_df['id'], categories=reviewer_u) You can get the codes using: row.codes
answers question: http://stackoverflow.com/q/52631868
accepted answer of: http://stackoverflow.com/q/52631868
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/52653371
tagged with: librosa
has body: Let's say I have a few very long audio files (for ex., radio recordings). I need to extract 5 seconds after particular sound (for ex., ad start sound) from each file. Each file may contain 3-5 such sounds, so I should get *(3-5)number of source files result files. I found librosa and scipy python libraries, but not sure if they can help. What should I start with?
type: UnansweredQuestion
tagged with: python
tagged with: audio
has title: How to extract audio after particular sound?
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/52653601
score: 0
answer count: 1

http://stackoverflow.com/comment/92357295
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52715105
type: Comment
has text: Awe, I did it thank you thank you thank you so much @blhsing you safe my life :)

http://stackoverflow.com/q/52647650
tagged with: excel
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52649627
score: 1
has title: How to keep VBA code when copying worksheet with openpyxl?
type: Question
answer count: 2
downvote count: 0
tagged with: vba
linked to: http://stackoverflow.com/q/24701517
has answer: http://stackoverflow.com/a/52649627
possible better answer: http://stackoverflow.com/a/52647821
tagged with: python
has answer: http://stackoverflow.com/a/52647821
favorite count: 0
has body: I have a worksheet with VBA code (on Excel, right-click on the sheet name and View code) that I would like to copy on the same workbook. When using workbook.copy_worksheet() , the VBA code contained in the worksheet is lost. I've had a look at the worksheet.vba_code property but it seems to only contain some sheets properties, not the VBA code.
tagged with: openpyxl
upvote count: 1

http://stackoverflow.com/q/52688518
score: 0
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52688592
has title: How to follow a hyper-refernce in scrapy if the href attribute contains a hash symbol
tagged with: python
tagged with: web-scraping
tagged with: scrapy
has body: In my web-scraping project I have to scrape the football matches data from https://www.national-football-teams.com/country/67/2018/France.html In order to navigate to matches data from the above url I have to follow a hyper-reference that has a hash in the url: Matchesevent The standard scrapy mechanism of following the links: href = response.xpath("//a[contains(@href,'matches')]/@href").extract_first() href = response.urljoin(href) will produce a link that will not lead to the matches data: https://www.national-football-teams.com/matches.html I would appreciate any help. Since I am noobie to web-scraping and anything which has something to do with web-development, a more specific advice and/or a minimal working example is highly acknowledged. For the completeness here is the complete code of my scrapy-spider: import scrapy class NationalFootballTeams(scrapy.Spider): name = "nft" start_urls = ['https://www.national-football-teams.com/continent/1/Europe.html'] def parse(self, response): for country in response.xpath("//div[@class='row country-teams']/div[1]/ul/li/a"): cntry = country.xpath("text()").extract_first().strip() if cntry == 'France': href = country.xpath("@href").extract_first() yield response.follow(href, self.parse_country) def parse_country(self, response): href = response.xpath("//a[contains(@href,'matches')]/@href").extract_first() href = response.urljoin(href) print href yield scrapy.Request(url=href, callback=self.parse_matches) def parse_matches(self, response): print response.xpath("//tr[@class='win']").extract()
type: Question

http://stackoverflow.com/comment/92288398
type: Comment
type: QuestionComment
has text: This is purely a learning exercise. Is it fair to say that what I have done in the code is a Sobel filtering of the grayscale converted image, and with this information other people should be able to reproduce the result independent on the exact implementation of the underpinning algorithm?
comment on: http://stackoverflow.com/q/52678356
score: 0

http://stackoverflow.com/comment/92196092
type: AnswerComment
type: Comment
has text: Digging in the bug/issues I found that we did look at `max_help_position` some 3 years ago.
comment on: http://stackoverflow.com/a/52614708
score: 0

http://stackoverflow.com/a/52724307
answers question: http://stackoverflow.com/q/52723244
upvote count: 4
has comment: http://stackoverflow.com/comment/92405969
accepted answer of: http://stackoverflow.com/q/52723244
downvote count: 0
has body: How about using the Runtime.exec() method? Just do Process process = Runtime.getRuntime().exec("python script.py arg1 arg2"). Runtime is a class from the java.lang package, so you don't need to do any fancy import. More info here. EDIT Ok, not too easy to manage if you have lots of functions. On the other hand if you don't mind a bunch of wrapper files just do a bit of code to build one automatically for each function. Check out this little piece of Python code. Just replace foo with whatever your huge module is called, and you're good to go. from inspect import getmembers, isfunction import foo f_list=[o[0] for o in getmembers(foo) if isfunction(o[1])] for x in f_list: print("Build "+str(x)) with open("helper_"+str(x)+".py","wt") as f: f.write("""import foo import sys arg_list=sys.argv[1::] print(foo.{x}(*arg_list))""".format(x=x))
score: 4
has comment: http://stackoverflow.com/comment/92411315
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/92393279

http://stackoverflow.com/comment/92181461
score: 0
comment on: http://stackoverflow.com/q/52622716
has text: It depends on website. Which one you use?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92252715
has text: I can't use the module ConfigParser as I am working on my project at school and the school doesnt really like you when you ask them to download more modules
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52649997
type: AnswerComment

http://stackoverflow.com/q/52651519
has body: I have override the default User model in my app with AUTH_USER_MODEL. Here is the user model I want to use in my app, which is tied closely to a legacy database: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): name = models.CharField(max_length=128, blank=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) normalized_email = models.EmailField(unique=True) However, django complains that fields such as first_name, last_name, etc. are not provided. Is there a way to remove some of the existing fields in the User model? Or does specifying a custom user model only allow you to add additional fields on top of that? Is there a simple way to delete them, or do I basically have to add those fields (and ignore them) to our existing database in order to be able to use django with it?
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52651562
score: 1
tagged with: django-models
answer count: 1
downvote count: 0
favorite count: 0
has title: Override django user with AUTH_USER_MODEL
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/a/52618225
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52617091
type: Answer
has body: Colorbars are created within an axes. To have full control over where the colorbar resides you may create an axes at the respective position and use the colorbar's cax argument to specify which axes to use to show the colorbar. To create useful axes, a GridSpec may be helpful, where the main plot spans multiple gridcells and the ratios of the cell heights is quite asymmetric. import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec x,y1,y2,y3 = np.random.rand(4,15) gs = GridSpec(2,3, height_ratios=[15,1]) fig = plt.figure() # Axes for plot ax = fig.add_subplot(gs[0,:]) # three colorbar axes cax1 = fig.add_subplot(gs[1,0]) cax2 = fig.add_subplot(gs[1,1]) cax3 = fig.add_subplot(gs[1,2]) # plot sc1 = ax.scatter(x, y1, c=y1, cmap="viridis") sc2 = ax.scatter(x, y2, c=y2, cmap="RdYlGn") sc3 = ax.scatter(x, y3, c=y3, cmap="copper") # colorbars fig.colorbar(sc1, cax=cax1, orientation="horizontal") fig.colorbar(sc2, cax=cax2, orientation="horizontal") fig.colorbar(sc3, cax=cax3, orientation="horizontal") plt.show()
answers question: http://stackoverflow.com/q/52617091
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92200995
upvote count: 1

http://stackoverflow.com/comment/92309715
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52691255
type: Comment
has text: My latest file is "Business Component.xlsx". my python code gives the below path: for /f "delims=" %%a in ('removeLatest.py') do set "var=%%a" echo %var% SET cmd="for /F %%i in ("%var%") do @echo %%~ni" FOR /F "tokens=*" %%a in ('%cmd%') do SET arg1=%%a ECHO "%arg1%" ECHO "%arg1%" But this gives the output as : Business but my requirement is to get the filename without extension i.e "Business Component"

http://stackoverflow.com/comment/92299601
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52685957
has text: @Mehrdad correct :) (provided `B.__init__` uses `super()` of course)
type: AnswerComment

http://stackoverflow.com/a/52700889
has comment: http://stackoverflow.com/comment/92336031
answers question: http://stackoverflow.com/q/52672939
has body: Ok. So, thanks to @G.Anderson, I figured this out. First, the empty data frame should be outside of the loop. Next, the i, as stated by G.Anderson was not getting called out. I used a .loc statement to call what i is. Below is the code. def nhtsa(df): ''' sends VIN to NHTSA for data call ''' df1 = pd.DataFrame() for i in current_trial.index: vin = df.loc[i, 'VIN'] url = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/' post_fields = {'format': 'json', 'data': vin}; r = requests.post(url, data=post_fields); x = r.json() f = pd.DataFrame(x['Results']) g = f'VIN','Make','Manufacturer','ManufacturerId','ManufacturerType', 'Model','ModelYear', 'ABS','VehicleType', 'BodyClass','DisplacementCC','ErrorCode', 'SuggestedVIN' df1 = df1.append(g) return df1
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/92396444
score: 0
type: Comment
type: QuestionComment
has text: @SalazarSid, That's not a valid Python object. Type that in your favourite IDE and it will fail with `SyntaxError`.
comment on: http://stackoverflow.com/q/52735598

http://stackoverflow.com/q/52659981
tagged with: mongodb
has comment: http://stackoverflow.com/comment/92251601
answer count: 6
has answer: http://stackoverflow.com/a/52661238
has answer: http://stackoverflow.com/a/55298279
downvote count: 0
has answer: http://stackoverflow.com/a/61365606
favorite count: 0
has answer: http://stackoverflow.com/a/56207140
type: UnansweredQuestion
has body: I am trying to connect mongodb with django, but i am getting this error ImproperlyConfigured: 'djongo' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3' I have read posts but they are all old and not helping me. I have created mongodb database using studio 3T, name of database is NewDataBase user is gsc-30310 port is 27017 host is localhost Versions I am using are: python3 Django==2.1.1 mongoengine==0.15.3 pymongo==3.7.1 Here is my settings.py file, please tell me how to setup for new version of django and python 3. thanks """ Django settings for RestUserAPI project. Generated by 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os import mongoengine # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3==2yxbjdvt+hkqm#*%s7cs4g(_+cus9pdup%bxd*uk03g^&amp;w%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #RestFrameWork 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib…
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52663654
has answer: http://stackoverflow.com/a/55296707
has title: Connect Mongodb with Django
score: 1
has comment: http://stackoverflow.com/comment/92251209
has comment: http://stackoverflow.com/comment/92251488
upvote count: 1
has comment: http://stackoverflow.com/comment/92251421
type: Question

http://stackoverflow.com/a/52646937
accepted answer of: http://stackoverflow.com/q/52632981
answers question: http://stackoverflow.com/q/52632981
type: Answer
has comment: http://stackoverflow.com/comment/92230993
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92233510
has comment: http://stackoverflow.com/comment/92233278
has comment: http://stackoverflow.com/comment/92230672
has body: based on the above, I've put together an example that actually works: from lxml import etree root = etree.fromstring(""" <key attr.name="ref" attr.type="string" for="edge" id="d14" /> <key attr.name="name" attr.type="string" for="edge" id="d13" /> <key attr.name="geometry" attr.type="string" for="edge" id="d12" /> <key attr.name="length" attr.type="string" for="edge" id="d11" /> <key attr.name="oneway" attr.type="string" for="edge" id="d10" /> <key attr.name="highway" attr.type="string" for="edge" id="d9" /> <key attr.name="bridge" attr.type="string" for="edge" id="d8" /> <key attr.name="osmid" attr.type="string" for="edge" id="d7" /> 435211336 Calle Carretera residential False 52.45 LINESTRING (-4.8413613 39.4799045, -4.8414814 39.4798489, -4.8419449 39.4797838) 483537143 CM-4106 secondary False 104.66499999999999 LINESTRING (-4.8366071 39.4783468, -4.8368979 39.4789602, -4.8371678 39.4791592) """) keys = {} for key in root.findall('graph/key'): keys[key.get('attr.name')] = key.get('id') key_name = keys['name'] key_length = keys['length'] out = {} for edge in root.findall('graph/edge'): data = dict((d.get('key'), d.text) for d in edge.findall('data')) value = (data.get(key_name, 'noName'), data[key_length]) out[(edge.get('source'), edge.get('target'))] = value print(out) note that you get a None for the second edge now. before it was "missing" because you were telling it to be filtered out. instead, my code creates a dictionary based on the xml and then always populates the values in out with tuples containing two elements.
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52616414
has comment: http://stackoverflow.com/comment/92167205
answer count: 2
has body: This is a part of the big json file I have. I am creating folders with the content from yamlPath and then writing to a file with the content from sqlQuery. But in the case of repeating "yamlName+yamlPath", my code is only creating the file with the first result and inserting the sqlQuery content it gets from the for loop. So, in this repeating scenario, I only want to pick up the sqlQuery and create a file based on the latest/max jobEndTimestamp. How can make the code to pick up only the latest jobEndTimestamp and create the file? Expected output: /app/computer/users/ship-notice-data.sql -&gt; select from table.b /app/computer/a/users/boat-notice-data.sql -&gt; select from table.b { "stream": [ { "applicationServiceId": "uhhj", "yamlName": "/users/ship-notice-data.yml", "yamlPath": "/app/computer", "jobStartTimestamp": "2018-09-15 04:12:46", "jobEndTimestamp": "2018-09-15 04:15:29", "sourceHostName": "Teradata", "sourceType": "Teradata", "targetHostName": "DB2", "targetType": "DB2", "sqlQuery": "select from table.a" },{ "applicationServiceId": "uhhj", "yamlName": "/users/ship-notice-data.yml", "yamlPath": "/app/computer", "jobStartTimestamp": "2018-09-15 21:12:46", "jobEndTimestamp": "2018-09-15 21:15:29", "sourceHostName": "Teradata", "sourceType": "Teradata", "targetHostName": "DB2", "targetType": "DB2", "sqlQuery": "select from table.b" },{ "applicationServiceId": "uhhj", "yamlName": "/users/car-notice-data.yaml", "yamlPath": "/app/computer/s", "jobStartTimestamp": "2018-09-15 04:12:46", "jobEndTimestamp": "2018-09-15 06:15:29", "sourceHostName": "Teradata", "sourceType": "Teradata", "targetHostName": "DB2", "targetType": "DB2", "sqlQuery": "select from table.b" },{ "applicationServiceId": "uhhj", "yamlName": "/users/boat-notice-data.yaml", "yamlPath": "/app/computer/a", "jobStartTimestamp": "2018-09-15 04:12:46", "jobEndTimestamp": "2018-09-15 06:15:29", "sourceHostName": "Teradata", "sourceType": "Teradata", "targetHostName": "DB2", "targetType": "DB2", "sqlQue…
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92170554
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52631726
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92196665
has answer: http://stackoverflow.com/a/52617142
has title: How to create and write to a file based on the latest timestamp condition from a json file in Python?
has comment: http://stackoverflow.com/comment/92167155
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92167139

http://stackoverflow.com/a/52653013
has body: You may use [0] in front of findall: &gt;&gt;&gt; h = [] &gt;&gt;&gt; for i in a: ... res = re.findall(r'/(\w+)', i) ... if res: ... h.append(res[0]) ... &gt;&gt;&gt; print (h) ['RegEx1', 'RegEx2', 'RegEx3']
score: 0
upvote count: 1
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/92237845
has comment: http://stackoverflow.com/comment/92257021
accepted answer of: http://stackoverflow.com/q/52652945
answers question: http://stackoverflow.com/q/52652945
has comment: http://stackoverflow.com/comment/92252552
type: AcceptedAnswer

http://stackoverflow.com/q/52703014
has comment: http://stackoverflow.com/comment/92335546
has title: Capture frame from 10-bit video using Python
answer count: 0
tagged with: image-processing
has comment: http://stackoverflow.com/comment/92385238
has comment: http://stackoverflow.com/comment/92387666
type: Question
has body: I want to capture a frame from 10-bit video. I tried some solutions to that, like OpenCV but it seems to cause strong banding in dark areas on saved image, and FFMPEG but quality is inferior to OpenCV and it seems to handle YUV colorspace incorrectly when saving the image (black areas lose much detail, and picture is overall brighter). I'm disregarding frame accuracy at this point, what i care most about is proper handling of colors. I wanted to try VapourSynth, but i can't get it to work properly on my Ubuntu (compilation fails when enabling imwrt plugin). What other solutions i can try for that problem? One thing i can think of is dithering dark areas with OpenCV to get rid of banding, but i honestly don't know how to do that, and when i tried some already-made alghoritms(like this one ) but it didn't work at all, getting stuck at one of set_pixel functions. EDIT: diffrence between ffmpeg, OpenCV, and mpv 8 bit screenshots: https://diff.pics/zugzxgSvGI3D Looks like OpenCV has trouble converting 10 bit to 8 bit image, causing strong debanding, but there is much more details in dark areas. 8 bit screenshot taken with MPV looks probably best, and that's what i'm aiming for. Only thing wrong with OpenCV one in that case would be strong banding.
has comment: http://stackoverflow.com/comment/92384429
score: 0
has comment: http://stackoverflow.com/comment/92345978
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92334941
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/92335781

http://stackoverflow.com/comment/92410341
has text: @JRibkr My friend it is not the exact duplicate. It needs some data manipulation before dropping duplicates. Thanks for your efforts though
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52740946

http://stackoverflow.com/q/52667760
has comment: http://stackoverflow.com/comment/92279349
tagged with: python
tagged with: tesseract
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/92265633
has comment: http://stackoverflow.com/comment/92288830
has comment: http://stackoverflow.com/comment/92265551
answer count: 0
has title: Optical Character Recognition Python Code ignoring all characters completely for some images
type: UnansweredQuestion
tagged with: image
has comment: http://stackoverflow.com/comment/92265664
has comment: http://stackoverflow.com/comment/92281210
has body: I am currently working on a simple task where I have to read characters from simple images. Used tesseract in python to write following code which works on all simple and complex images having English text but fails on a particular image, can anyone tell me why the following python code can not read characters from the following image , as you can see with 6 black sections having 6 characters in each box, character colour is white. from PIL import Image import pytesseract import argparse import cv2 import os ap = argparse.ArgumentParser() ap.add_argument("-i","--image",required=True,help="path to input image to be OCR'd") ap.add_argument("-p","-- preprocess",type=str,default="thresh",help="type of preprocessing to be done") args=vars(ap.parse_args()) image = cv2.imread(args["image"]) gray2 = cv2.BackgroundSubtractor() gray2 = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) gray2 = cv2.threshold(gray2, 100, 255, cv2.THRESH_BINARY_INV)[1] rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3)) sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) if args["preprocess"] == "thresh": gray2 = cv2.threshold(gray2, 2, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] elif args["preprocess"] == "blur": gray2 = cv2.medianBlur(gray2,3) filename = "{}.png".format(os.getpid()) cv2.imwrite(filename,gray2) text = pytesseract.image_to_string(Image.open(filename)) print(text) If this image is used, it gives perfect result 0123456789 ABCDEFGHIJKL MNOPQRSTUV WXYZ When I am trying to use the following image , Processed Image which does not give result the code completely ignores all characters in the image. The only difference is the first image does not have boxes like the second image where each black box contains 6 characters Can someone please help and tell me what am I missing why this code fails for the second image, Thanks. Here are the original images : Image1 Image2
has comment: http://stackoverflow.com/comment/92265524
tagged with: ocr
has comment: http://stackoverflow.com/comment/92265354
type: Question

http://stackoverflow.com/a/52741120
answers question: http://stackoverflow.com/q/52740729
type: Answer
has body: This error is usually raised when the file read using pandas is either corrupted or not in a readable state. Modifying code as below should work: import pandas as pd import os path = ('./Sketch_grammar/weighted/') files = os.listdir(path) for file in files: if file.endswith('.csv'): df = pd.read_csv(path+file) df = df.drop('Hits', axis=1) df = df.drop('Score', axis=1) df = df.drop('Score.1', axis=1) filename = os.path.splitext(file) (f, ext) = filename df.to_csv(path+'weighted_out/'+f+'_out.csv', index=False)
accepted answer of: http://stackoverflow.com/q/52740729
score: 2
has comment: http://stackoverflow.com/comment/92408063
has comment: http://stackoverflow.com/comment/92409935
upvote count: 2
has comment: http://stackoverflow.com/comment/92407687
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92223584
type: Comment
comment on: http://stackoverflow.com/q/52645557
score: 3
has text: That's not all of your code. What you've posted won't run. But it looks like you're trying to hash the contents of the Entry before the user has a chance to enter a string into it.
type: QuestionComment

http://stackoverflow.com/q/52633758
tagged with: parsing
has title: Recover list format when passing an argument
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1894269
downvote count: 2
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/1894269
tagged with: list
has comment: http://stackoverflow.com/comment/92201079
score: -1
type: Question
has body: I am passing as argument to a python program a list of two strings (in particular to stream geo located tweets from python-twitter). The format is as example: my_python_program.py -l ['-9.215752,36.99','3.73,42.139225'] But when I "argparse" to get that argument I see it is passed as "string" : "['-9.215752,36.99','3.73,42.139225']" I could recover the original format looking for the "[" "," and "]" character and getting the string between them. But I guess there should be a more "pythonic" way of doing that?
has comment: http://stackoverflow.com/comment/92200758
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/52633813
answer count: 1

coding-style
tags question: http://stackoverflow.com/q/52611557
type: Tag
tag name: coding-style

http://stackoverflow.com/q/52743899
score: 1
has answer: http://stackoverflow.com/a/52743947
tagged with: django-tests
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52743947
tagged with: python
has body: I am using function in views to query db (postgresql), calculate values and return list of lists. When I call it from views.py I get what is expected. When I call it from test.py I get empty list (not error, not None). To investigate I have created list of lists in views function manually and it was returned just fine (so there is no issue with import or length of returned value). It seems that if I call function imported from views that makes a db query and it is called from TestCase object then the db query is not done. Why? from django.test import TestCase from &lt;my app&gt;.views import calc import datetime from pytz import timezone class CalcTestCase(TestCase): maxDiff = None def test_calc_image(self): start_time = datetime.datetime(2018, 9, 1, 0, 0, 0, 0, tzinfo=timezone('UTC') ) finish_time = datetime.datetime(2018, 10, 1, 0, 0, 0, 0, tzinfo=timezone('UTC') ) instance_type = "test" output = calc(instance_type, start_time, finish_time) test_output = [[test, values, in],[list, of, lists]] self.assertEqual(output, test_output)
type: AnsweredQuestion
tagged with: django
upvote count: 1
has title: Is there a limitation on running db query in imported function in django tests?
type: Question

http://stackoverflow.com/comment/92337235
has text: Add your error as text here rather than an external link.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52705105

http://stackoverflow.com/q/52685564
score: 1
favorite count: 0
type: Question
has body: I just installed Hydrogen module into Atom so I can get user input into Python. How can I run the code using hydrogen without going line by line? The only reason I installed this program so I can input data using the input() python command. I am going line by line but as soon as I instantiate one of my python classes, it says classname NOT FOUND. How can I make hydrogen read the class name which is in the same file but not in the main() module?
tagged with: python
has comment: http://stackoverflow.com/comment/92320013
upvote count: 1
has answer: http://stackoverflow.com/a/57931147
has title: Python Atom Hydrogen, stepping through code line by line, or all at once
answer count: 1
has comment: http://stackoverflow.com/comment/92337345
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92337526
tagged with: class
tagged with: hydrogen
tagged with: atom-editor
has comment: http://stackoverflow.com/comment/92308362
downvote count: 0

http://stackoverflow.com/comment/92220282
comment on: http://stackoverflow.com/q/52643870
has text: Why don't you directly use pandas data frame's read_csv method?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52652407
upvote count: 1
tagged with: recursion
has answer: http://stackoverflow.com/a/52652618
score: 1
type: Question
has title: Recursion upside down triangle
has answer: http://stackoverflow.com/a/52652600
downvote count: 0
has comment: http://stackoverflow.com/comment/92236644
favorite count: 0
has answer: http://stackoverflow.com/a/52652535
has body: I'm supposed to create a recursive statement that if first calls triangle(n) it returns '******\n *****\n ****\n ***\n **\n *' This above is called for triangle(6) and if I print(triangle(6)) it returns below. ****** ***** **** *** ** * Then I must create another code recursive_triangle(x, n) that returns a string with the LAST x lines of a right triangle of base and height n. For example if I did recursive_triangle(3, 6) it returns ' ***\n **\n *' and if i print it should returns *** ** * So far my code is #### DO NOT modify the triangle(n) function in any way! def triangle(n): return recursive_triangle(n, n) ################### def recursive_triangle(k, n=0): ''' Takes two integers k and n &gt;&gt;&gt; recursive_triangle(2,4) ' **\\n *' &gt;&gt;&gt; print(recursive_triangle(2,4)) ** * &gt;&gt;&gt; triangle(4) '****\\n ***\\n **\\n *' &gt;&gt;&gt; print(triangle(4)) **** *** ** * ''' # --- YOUR CODE STARTS HERE if n == 1: return "*" else: for i in range(1, n+1): return ("*" *n) + "\n" + (' ' * i) + triangle (n - 1) for print(triangle(4)) this is what i got **** *** ** * How do I modify the code to get the output above?
has answer: http://stackoverflow.com/a/52652719
tagged with: python
answer count: 4
type: UnansweredQuestion

http://stackoverflow.com/comment/92276592
score: 0
type: Comment
type: QuestionComment
has text: y(n) is the con volution of x and h and I can get the result typing this: y=convolve(x,h, mode="full"). But, Im also asked to do the convolution using those two defined functions
comment on: http://stackoverflow.com/q/52673075

http://stackoverflow.com/a/52699231
downvote count: 0
answers question: http://stackoverflow.com/q/52698947
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92325024
has body: You may print title for every figure (plt.show() necessary in this case): import matplotlib.pyplot as plt x=range(5);y=range(5) for i in range(2): plt.figure() plt.plot(x,y) plt.title("Title"+str(i)) print("Title"+str(i)) plt.show()

http://stackoverflow.com/comment/92275132
score: 0
has text: Need your pygame.py file as well please.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52672529

http://stackoverflow.com/comment/92273039
comment on: http://stackoverflow.com/q/52670115
type: Comment
type: QuestionComment
has text: It's 16. (Updated above w/ full list of vars).
score: 0

http://stackoverflow.com/a/52728206
has body: When you do astype(str), the dtype is always going to be object, which is a dtype that includes mixed columns. Therefore, one thing you can do is convert it to object using astype(str), as you were doing, but then replace the nan with actual NaN (which is inherently a float), allowing you to access it with methods such as isnull: df.astype(str).replace('nan',np.nan) Example: df = pd.DataFrame({'col1':['x',2,np.nan,'z']}) &gt;&gt;&gt; df col1 0 x 1 2 2 NaN 3 z # Note the mixed str, int and null values: &gt;&gt;&gt; df.values array([['x'], [2], [nan], ['z']], dtype=object) df2 = df.astype(str).replace('nan',np.nan) # Note that now you have only strings and null values: &gt;&gt;&gt; df2.values array([['x'], ['2'], [nan], ['z']], dtype=object)
downvote count: 0
score: 9
upvote count: 9
answers question: http://stackoverflow.com/q/52728139
type: Answer

http://stackoverflow.com/a/52791809
has body: Try this change in your wsgi.py: cherrypy.tree.mount(App1Handler(), '/app1', {}) cherrypy.tree.mount(App2Handler(), '/app2', {}) application = cherrypy.tree Then launch with something like: gunicorn wsgi:application
type: Answer
answers question: http://stackoverflow.com/q/52596867
score: 0

http://stackoverflow.com/comment/92311168
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52691468
has text: I tried in jupyter notebook (I was on jupyter lab), I don't get the same error and I can get the filename (which is what I had asked), but I cannot get the full path.

http://stackoverflow.com/q/52665167
has answer: http://stackoverflow.com/a/52665549
type: UnansweredQuestion
tagged with: cpython
tagged with: python
has comment: http://stackoverflow.com/comment/92260604
tagged with: list
downvote count: 2
has comment: http://stackoverflow.com/comment/92260414
has comment: http://stackoverflow.com/comment/92260512
upvote count: 1
tagged with: loops
has title: Why "changing list dynamically" behave differently in two level of nested loop?
has comment: http://stackoverflow.com/comment/92260278
type: Question
has comment: http://stackoverflow.com/comment/92260041
has body: My Question is: Why it works for the inner loop, but not the outer one? NOT how to write something to do this job... I know it is not a safe solution to change list dynamically in loop. Code 1: list_a = [1,2,3] list_b = [11,12,13] for i in list_a: for j in list_b: print(i, j) Result 1: 1 11 1 12 1 13 2 11 2 12 2 13 3 11 3 12 3 13 Code 1 is a two-level nested loop for printing combination of two list, and it works as expected. I want to change the list dynamically during the loop. By changing the list that trigger the looping, I expect the looping behavior is also changed dynamically. Code 2: list_a = [1,2,3] list_b = [11,12,13] for i in list_a: list_a = [100, 200] for j in list_b: print(i, j) Code 3: list_a = [1,2,3] list_b = [11,12,13] for i in list_a: for j in list_b: list_a = [100, 200] print(i, j) Result 2/3: 1 11 1 12 1 13 2 11 2 12 2 13 3 11 3 12 3 13 Code 2 and Code 3 is for changing the first list. Although list_a is updated in the first step of the loop, the looping behavior of outer for loop dose not change. Code 4: list_a = [1,2,3] list_b = [11,12,13] for i in list_a: for j in list_b: list_b = [100, 200] print(i, j) Result 4: 1 11 1 12 1 13 2 100 2 200 3 100 3 200 Code 4 is for changing the second list. list_b is updated in the first step of the loop, and the looping behavior of the inner one is affected.
score: -1
has comment: http://stackoverflow.com/comment/92260390
answer count: 2
has answer: http://stackoverflow.com/a/52667650
linked to: http://stackoverflow.com/q/1637807
has comment: http://stackoverflow.com/comment/92260194
has comment: http://stackoverflow.com/comment/92260580
favorite count: 0

http://stackoverflow.com/comment/92248817
score: 1
comment on: http://stackoverflow.com/a/52649438
type: AnswerComment
has text: and if install pandas, numpy is required package, so also installed with pandas
type: Comment

http://stackoverflow.com/q/52735515
has comment: http://stackoverflow.com/comment/92395903
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52735670
tagged with: python
has comment: http://stackoverflow.com/comment/92395840
has comment: http://stackoverflow.com/comment/92396201
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92396070
has answer: http://stackoverflow.com/a/52735703
has comment: http://stackoverflow.com/comment/92396278
has comment: http://stackoverflow.com/comment/92395940
has comment: http://stackoverflow.com/comment/92396024
score: 0
has comment: http://stackoverflow.com/comment/92395875
has title: What does it mean *I next to a number in python?
has body: These numbers come from computing the arcsine, and I guess the *I is something to do with floating point precision in python. But cannot find anywhere what does it mean exactly. Also, is there a straight forward way just keep the first number (i.e. before the - sign)? I mean without processing it as a string but rather some direct call to a method.
has comment: http://stackoverflow.com/comment/92395889
tagged with: precision
favorite count: 0
has comment: http://stackoverflow.com/comment/92396158

http://stackoverflow.com/comment/126830292
type: Comment
has text: Why doesn't it work to use `weakref.proxy`? The object will still be garbage-collected since we're not increasing the number of strong references to it.
comment on: http://stackoverflow.com/a/58243606
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92346296
comment on: http://stackoverflow.com/a/52706254
has text: thanks, i already try AutoThrottle extension, but still get error " ValueError: invalid hostname: 2018-10-09 04:54:13 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.islam.gov.my/en/e-hadith?start=33> (referer: None) "
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92395459
type: QuestionComment
has text: Do all the lists have the same length?
score: 0
comment on: http://stackoverflow.com/q/52735310
type: Comment

http://stackoverflow.com/comment/92468102
type: Comment
score: 0
has text: Hi Wen, Thanks a lot for your advice, I appreciate much. I have slightly different splitting as follow: let's say I want to split a string at unique sprint. How can i do it. for example, my string contains abcdf 0:2 dfrgh, I want to split at 0:2. (i.e. I have two string abcdf and dfrgh. However, the splitter 0:2 is different for every row. It could be 3:0, 1:2,3:3 and so many combination.How can I do it?
comment on: http://stackoverflow.com/a/52732339
type: AnswerComment

http://stackoverflow.com/a/52674611
has body: I think you're overcomplicating it. Consider changing it to something like the following: n = 1 A = [1,2,3] B = A.copy() for _ in range(n): # Cycle through by concatenating the last element and all other elements together B = [B[-1]]+B[0:-1] print(B) In case of n=1, you get [3, 1, 2], and n=2 gives you [2, 3, 1] Note that what you are trying to do is implemented in numpy.roll (I suppose you're asking about the process, not the result, but just in case) import numpy as np &gt;&gt;&gt; np.roll(A,1) array([3, 1, 2]) &gt;&gt;&gt; np.roll(A,2) array([2, 3, 1])
type: Answer
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/52674598
has comment: http://stackoverflow.com/comment/92303137
has comment: http://stackoverflow.com/comment/92284828
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52674598

http://stackoverflow.com/q/52684331
has title: GridSearchCV freezes on windows with any n_jobs
tagged with: svm
answer count: 2
accepted answer: http://stackoverflow.com/a/52686503
has answer: http://stackoverflow.com/a/68267834
has body: I'm currently having trouble with GridSearchCV method from the scikit learn library. I've been struggling with it for a week now, and can't seem to work it out yet. It keeps freezing when calling it to optimize a linear SVM on the C parameter. Weird thing, it happens not only when assigning it n_jobs=-1, but also with 1 n_jobs, so I don't thing multiprocessing is specially the issue. Besides, it works fine when I feed it an X array of shape (2448, 1024), but completely freezes when I feed it with an array of shape (5202, 1024). Data I'm feeding it with: float64 numpy arrays of shapes varying from (2448, 1024), which works fine, to (7956, 1024) Things I've already tried: Using multithreading, as suggested in https://stackoverflow.com/a/47929603/9699979 Reducing the number of n_jobs to 1 Assigning a low number of pre_dispatch jobs. It started computing the first few verbose lines, indicating the C it was fitting, then froze. Adding an if __name__ == '__main__' block, as suggested in https://github.com/scikit-learn/scikit-learn/issues/2889#issuecomment-37311446 Running the code from the terminal rather than from a Jupyter Notebook, where I've been working I'm not able to run the following code, as suggested in https://github.com/dmlc/xgboost/issues/2163#issuecomment-314524070 since I'm running my code on Windows. from multiprocessing import pool, get_context forkserver = get_context('forkserver') p = forkserver.Pool() Things to note: I'm fitting it with f1 function, rather than the default accuracy one, which could be an issue, as seen in these threads: https://github.com/scikit-learn/scikit-learn/issues/5115#issue-100597083 https://github.com/scikit-learn/scikit-learn/issues/2889#issue-28205288 Here are some code snippets: from sklearn.externals.joblib import parallel_backend scaler = StandardScaler() X = scaler.fit_transform(fv_train.data) #traininig samples y = fv_train.axes[0] #class labels X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size = 0.1…
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/52686503
tagged with: windows
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33042527
upvote count: 3
possible better answer: http://stackoverflow.com/a/68267834
tagged with: machine-learning
type: Question
score: 3

http://stackoverflow.com/comment/113561499
type: Comment
has text: Can confirm this was the problem for me - had to ensure the full path was specified
type: AnswerComment
comment on: http://stackoverflow.com/a/52676770
score: 0

http://stackoverflow.com/q/52682772
tagged with: deployment
has comment: http://stackoverflow.com/comment/92311519
has body: After a successful deploy of a Django project I've made a few attempts to run this app on a dyno, however, it drops some errors. It's running with no issues locally tho. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 2018-10-06T19:08:44.455276+00:00 app[api]: Starting process with command `python manage.py migrate` by user tamerlanium@gmail.com 2018-10-06T19:08:51.519039+00:00 heroku[run.5633]: State changed from starting to up 2018-10-06T19:08:51.515345+00:00 heroku[run.5633]: Awaiting client 2018-10-06T19:08:51.578011+00:00 heroku[run.5633]: Starting process with command `python manage.py migrate` 2018-10-06T19:08:57.062762+00:00 heroku[run.5633]: State changed from up to complete 2018-10-06T19:08:57.046603+00:00 heroku[run.5633]: Process exited with status 1 2018-10-06T19:09:21.974583+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=tarlansblog.herokuapp.com request_id=b037e1d6-8a68-4992-8c4e-21462664ff0e fwd="176.107.221.177" dyno= connect= service= status=503 bytes= protocol=https 2018-10-06T19:09:23.424575+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=tarlansblog.herokuapp.com request_id=05d085e7-cf21-47a8-9752-1da68c0fa940 fwd="176.107.221.177" dyno= connect= service= status=503 bytes= protocol=https 2018-10-06T19:10:05.844413+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=tarlansblog.herokuapp.com request_id=9c64e68d-ba6c-422e-983c-9f9b30aac866 fwd="176.107.221.177" dyno= connect= service= status=503 bytes= protocol=https 2018-10-06T19:10:06.995437+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=tarlansblog.herokuapp.com request_id=9c9f6e8e-0233-4b3f-96c6-71882e4e17fe fwd="176.107.221.177" dyno= connect= service= status=503 bytes= protocol=https 2018-10-06T19:14:25.639377+…
tagged with: django
has answer: http://stackoverflow.com/a/52689578
type: Question
tagged with: heroku
has comment: http://stackoverflow.com/comment/92340291
score: 0
has title: Django Heroku app doesn't run after successful deploy
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52616187
tagged with: python
has comment: http://stackoverflow.com/comment/100170276
answer count: 0
downvote count: 0
type: Question
has title: Why does wfastcgi error out on sys.stdin.detach().read(8)?
tagged with: azure-web-app-service
score: 5
has body: I deployed a website using Azure Web Apps service, which is going to be mainly used as an API. The problem is that wfastcgi every so often throws out an error and the website goes down. The problem is that starting it back up takes a while, because the API is a prediction model and it needs to load some data. The site runs on the Azure Web App python extension (tried both 3.6.4 and 3.5.4, both give the same error). Used packages: click==6.7 Flask==1.0.2 itsdangerous==0.24 Jinja2==2.9.6 MarkupSafe==1.0 Werkzeug==0.12.2 pandas==0.23.3 keras==2.2.0 scikit-learn==0.19.1 tensorflow==1.8.0 Error code: 2018-10-02 16:20:59.497482: Unhandled exception in wfastcgi.py: Traceback (most recent call last): File "D:\home\python354x64\wfastcgi.py", line 774, in main record = read_fastcgi_record(fcgi_stream) File "D:\home\python354x64\wfastcgi.py", line 158, in read_fastcgi_record data = stream.read(8) # read record OSError: [Errno 22] Invalid argument 2018-10-02 16:20:59.513123: Running on_exit tasks 2018-10-02 16:20:59.513123: wfastcgi.py 3.0.0 closed As far as I can tell, it errors out on this command: sys.stdin.detach().read(8) Any ideas what might be causing this? Thank you!
has comment: http://stackoverflow.com/comment/100093882
tagged with: flask
tagged with: wfastcgi
tagged with: azure
has comment: http://stackoverflow.com/comment/100122710
favorite count: 0
upvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/100107115

jupyter-notebook
tags question: http://stackoverflow.com/q/52642696
tags question: http://stackoverflow.com/q/52744393
tags question: http://stackoverflow.com/q/52610492
tags question: http://stackoverflow.com/q/52619107
tags question: http://stackoverflow.com/q/52625796
tags question: http://stackoverflow.com/q/52609582
tags question: http://stackoverflow.com/q/52597178
tags question: http://stackoverflow.com/q/52652887
tags question: http://stackoverflow.com/q/52612487
tags question: http://stackoverflow.com/q/52700226
tags question: http://stackoverflow.com/q/52739311
tags question: http://stackoverflow.com/q/52676660
tags question: http://stackoverflow.com/q/52656013
tags question: http://stackoverflow.com/q/52656330
tags question: http://stackoverflow.com/q/52700284
tags question: http://stackoverflow.com/q/52677085
tags question: http://stackoverflow.com/q/52592829
tags question: http://stackoverflow.com/q/52690293
tags question: http://stackoverflow.com/q/52691468
type: Tag
tags question: http://stackoverflow.com/q/52728981
tags question: http://stackoverflow.com/q/52648036
tags question: http://stackoverflow.com/q/52590291
tags question: http://stackoverflow.com/q/52740275
tags question: http://stackoverflow.com/q/52686649
tags question: http://stackoverflow.com/q/52635866
tags question: http://stackoverflow.com/q/52598709
tags question: http://stackoverflow.com/q/52730839
tags question: http://stackoverflow.com/q/52681365
tags question: http://stackoverflow.com/q/52693101
tags question: http://stackoverflow.com/q/52630601
tags question: http://stackoverflow.com/q/52706238
tags question: http://stackoverflow.com/q/52729412
tags question: http://stackoverflow.com/q/52735313
tags question: http://stackoverflow.com/q/52710762
tags question: http://stackoverflow.com/q/52741983
tags question: http://stackoverflow.com/q/52708470
tags question: http://stackoverflow.com/q/52604512
tags question: http://stackoverflow.com/q/52589682
tags question: http://stackoverflow.com/q/52726475
tags question: http://stackoverflow.com/q/52649802
tags question: http://stackoverflow.com/q/52745750
tags question: http://stackoverflow.com/q/52630340
tags question: http://stackoverflow.com/q/52709092
tags question: http://stackoverflow.com/q/52695195
tags question: http://stackoverflow.com/q/52639445
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/52726209
tags question: http://stackoverflow.com/q/52706659
tags question: http://stackoverflow.com/q/52622358
tags question: http://stackoverflow.com/q/52611495
tags question: http://stackoverflow.com/q/52734739
tags question: http://stackoverflow.com/q/52602484
tags question: http://stackoverflow.com/q/52699818
tags question: http://stackoverflow.com/q/52606313
tags question: http://stackoverflow.com/q/52705746

http://stackoverflow.com/q/52658793
has answer: http://stackoverflow.com/a/52659187
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52659088
tagged with: python
has answer: http://stackoverflow.com/a/52658913
downvote count: 0
has comment: http://stackoverflow.com/comment/92248973
score: 1
has body: In an online course, part of the exercise is to create a matrix. We were given the data below: KobeBryant_FT = [696,667,623,483,439,483,381,525,18,196] JoeJohnson_FT = [261,235,316,299,220,195,158,132,159,141] LeBronJames_FT = [601,489,549,594,593,503,387,403,439,375] CarmeloAnthony_FT = [573,459,464,371,508,507,295,425,459,189] DwightHoward_FT = [356,390,529,504,483,546,281,355,349,143] ChrisBosh_FT = [474,463,472,504,470,384,229,241,223,179] ChrisPaul_FT = [394,292,332,455,161,337,260,286,295,289] KevinDurant_FT = [209,209,391,452,756,594,431,679,703,146] DerrickRose_FT = [146,146,146,197,259,476,194,0,27,152] DwayneWade_FT = [629,432,354,590,534,494,235,308,189,284] in order to create a matrix, this would be the code: FT = np.array([KobeBryant_FT, JoeJohnson_FT, LeBronJames_FT, CarmeloAnthony_FT, DwightHoward_FT, ChrisBosh_FT, ChrisPaul_FT, KevinDurant_FT, DerrickRose_FT, DwayneWade_FT]) I was wondering if there's a way to use a 'for' loop to emulate the output of the above code without having to manually type in KobeBryant_FT, JoeJohnson_FT, LeBronJames_FT, etc,etc.
type: Question
tagged with: for-loop
tagged with: arrays
has title: How do I iterate this list to create a matrix?
answer count: 3
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/92387853
has text: Anything preinstalled with ArcGIS works fine.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52731358
type: Comment

http://stackoverflow.com/q/52722980
tagged with: python
has answer: http://stackoverflow.com/a/52723331
has comment: http://stackoverflow.com/comment/92371561
score: 1
has comment: http://stackoverflow.com/comment/92371932
upvote count: 1
type: Question
has body: I have a list of lists of the form: [['about70-130 characters long string', '332'], ['someotherrandomstring','2'], ['about70-130 characters long string', 32], ['someotherrandomstring', '3333']] TO DO: I eventually want to sum the sizes of all the repeated strings like so: [['about70-130 characters long string',364], ['someotherrandomstring',3335]] I wrote a brute-force code to solve this but it's taking me a lot of time because the list has about 2 million lists. The very non-efficient code I wrote is: final = {} for element in both_list: size = int(element[1]) if element[0] not in final.keys(): final[element[0]] = size else: final[element[0]] += size I'm pretty sure there's a more time-efficient code but I can't seem to come up with any ideas. Any help and pointers in the right direction would be much appreciated. Thank you.
has comment: http://stackoverflow.com/comment/92371935
has comment: http://stackoverflow.com/comment/92371575
has answer: http://stackoverflow.com/a/52725100
answer count: 2
downvote count: 0
has title: Counting frequencies(efficiently) of strings in a large text file when their pre-counts are given
tagged with: string
favorite count: 0
linked to: http://stackoverflow.com/q/28859095
has comment: http://stackoverflow.com/comment/92372152
has comment: http://stackoverflow.com/comment/92371705
type: UnansweredQuestion

http://stackoverflow.com/comment/92181365
comment on: http://stackoverflow.com/a/52623976
score: 0
type: AnswerComment
type: Comment
has text: A simple to use answer indeed (I always think too complicated), but wouldn't this give trouble because dictionaries are in no particular order? So it compares only the first entry with the first entry?

http://stackoverflow.com/a/52619692
answers question: http://stackoverflow.com/q/52619582
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52619582
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: When you run sudo like that it's HOME is still your (non-root) home. So any directory it creates, like the cache directly, will be owned by root. You just have to: sudo rm -rf /home/user/.cache/pip/http To remove the cache directory. Run it again as non-root and you won't see the error.
score: 1
has comment: http://stackoverflow.com/comment/92173365

http://stackoverflow.com/q/52631660
downvote count: 1
type: Question
score: -1
has title: Python/Flask How to use the URL as a variable that links to a dictionary
accepted answer: http://stackoverflow.com/a/52633143
upvote count: 0
answer count: 1
tagged with: url
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/92197588
tagged with: python
tagged with: dictionary
has body: I'm new to Flask so I'll do my best to explain myself. I am creating a quiz app using Python/Flask. Basically I would like my HTML template to show a question based on the question number found in the URL. I have my questions and answers stored in a dictionary of tuples like so: [{question 1, answer 1}, {question 2, answer 2}, {question 3, answer 3}]... I want my structure to look like this: @app.route('/<username>/<question_number>', methods=["GET", "POST"]) def ask_questions(question_number): questions = get_all_questions() return render_template("riddle1.html", question=questions, question_number=1) Note the get_all_questions() function returns the dictionary of questions/answers. HTML: Welcome, {{ username }} to RiddleMeThis! {{ question[i][0] }} Answer: Enter The idea is that if the URL for is 1, it pulls the question from the dictionary of tuples which would be [0][0]. For question 2, [1][0], for question 3 [2][0] and so on. Upon answering the page would redirect to a page that compares the user answer to the answer in the tuple. If correct, it is redirected to the last page but with the now equalling 2, if incorrect it is simply taken back to the last page. I have taken a few spins at this and am really struggling to work out how to first plug the number into the URL and then also link that number to the dictionary - completely lost!! Is anyone able to point me in a direction? Thanks in advance.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52633143

http://stackoverflow.com/a/52722050
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52721709
has comment: http://stackoverflow.com/comment/92373446
has body: The problem is with url you are requesting. Same url is requested everytime because you are not updating the url as per start you are calculating. Try changing url like this: 'http://www.schulliste.eu/type/gymnasien/?bundesland=&amp;start={}'.format(start)
has comment: http://stackoverflow.com/comment/92400826

http://stackoverflow.com/comment/92162892
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52613719
score: 0
has text: okay, I will do that next time thanks!

http://stackoverflow.com/a/52649212
answers question: http://stackoverflow.com/q/52648862
has comment: http://stackoverflow.com/comment/92231748
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Maybe a good way would be calculating similarities, and return the highest match probability? First of all you need to do some data cleaning like removing special characters, convert all strings to lowercase then search using similarity st1 = 'apple information technology' st2 = 'apple international information technology' from difflib import SequenceMatcher SequenceMatcher(None, st1, st2).ratio()
score: 1
accepted answer of: http://stackoverflow.com/q/52648862
upvote count: 1

http://stackoverflow.com/comment/92250055
comment on: http://stackoverflow.com/a/52656714
type: AnswerComment
score: 0
has text: @PatJ Thanks, I didn't realize `Bytes.blit` was a thing. It should be more concise and efficient this way.I updated my answer.
type: Comment

http://stackoverflow.com/comment/92336792
has text: you need to use requests
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52702421
score: 0

http://stackoverflow.com/a/52590821
has comment: http://stackoverflow.com/comment/92125454
has comment: http://stackoverflow.com/comment/92127048
has comment: http://stackoverflow.com/comment/92138275
upvote count: 1
answers question: http://stackoverflow.com/q/52590564
has body: The less complex way of doing it would be to try to replace each word of the sentence using regular expressions and try to replace the word by another one using a replacement function, defaulting to the current word if not found: LANGUAGE_TO_ISO = { "en": "en", "eng": "en", "english": "en", "es": "es", "spanish": "es", } book_title = "The Dark Tower - english" import re print(re.sub(r"\b(\w+)\b",lambda m : LANGUAGE_TO_ISO.get(m.group(1),m.group(1)),book_title)) prints: The Dark Tower - en
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/92299714
has text: I discovered now what `splashkit` is and indeed the documentation doesn't say anything. I deduced what the problem was by reasoning (didn't install it). To say it all I don't think it's a good idea to use something like splashkit to learn programming with python...
comment on: http://stackoverflow.com/a/52686137
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52695726
tagged with: dataframe
has answer: http://stackoverflow.com/a/52695804
upvote count: 2
has title: Pandas dataframes equality test
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/92320210
has answer: http://stackoverflow.com/a/52695876
favorite count: 0
has body: How do I write a function that checks two input dataframes are of equal as long as rows in both dataframes are equal? So it disregards index positions and column orders. I can't use df.equals() since it will enforce data types to be equal, which is not what I need. from io import StringIO canonical_in_csv = """,c,a,b 2,hat,x,1 0,rat,y,4 3,cat,x,2 1,bat,x,2""" with StringIO(canonical_in_csv) as fp: df1 = pd.read_csv(fp, index_col=0) canonical_soln_csv = """,a,b,c 0,x,1,hat 1,x,2,bat 2,x,2,cat 3,y,4,rat""" with StringIO(canonical_soln_csv) as fp: df2 = pd.read_csv(fp, index_col=0) df1: c a b 2 hat x 1 0 rat y 4 3 cat x 2 1 bat x 2 df2: a b c 0 x 1 hat 1 x 2 bat 2 x 2 cat 3 y 4 rat My attempt: temp1 = (df == df2).all() temp2 = temp1.all() temp2 ValueError: Can only compare identically-labeled DataFrame objects
tagged with: python
possible better answer: http://stackoverflow.com/a/52695804
type: AnsweredQuestion
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92317876
type: Question
has answer: http://stackoverflow.com/a/52695745
accepted answer: http://stackoverflow.com/a/52695745

http://stackoverflow.com/comment/92276925
type: AnswerComment
score: 0
type: Comment
has text: You're probably right (as your answer clearly shows). I had tried to pass the hue parameter to barplot as well, bit I left it in the FacetGrid creation, and that didn't work either. In any case, I always find FacetGrid cumbersome to use. The new catplot is much easier to use.
comment on: http://stackoverflow.com/a/52672163

github
tags question: http://stackoverflow.com/q/52688278
tags question: http://stackoverflow.com/q/52741983
tags question: http://stackoverflow.com/q/52711036
tag name: github
type: Tag

http://stackoverflow.com/q/52705496
tagged with: spyder
has answer: http://stackoverflow.com/a/54198516
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Failling importing EcoInvent 3.3
type: Question
tagged with: database
has body: I am having trouble to import ecoinvent 3.3 in brightway (Spyder (Python 3.6, Last version of BW2, Windows 64). I am following the seminar2017, everythings works fine until the LCI sub chapter where I am actually stacked because I cannot import ecoinvent 3.3, I have access to the ecoinvent (even 3.5) but I just want to follow the seminar since I cannot fix the 2.2 unlinked exchanges problem. I have downloaded and imported the file ecoinvent 3.3_cutoff_ecoSpold02 and placed it in a folder that I am pointing to following the code provided by the developers/or the seminar: fpei33 = r'C:\Users\gaylordb\Documents\Golf\OiErgasiesMou\ei33' if 'ecoinvent 3.3 cutoff' in bw.databases: print("Database has already been imported") else: ei33 = bw.SingleOutputEcospold2Importer(fpei33, 'ecoinvent 3.3 cutoff') ei33.apply_strategies() ei33.statistics() The results is: Extracting XML data from 0 datasets Extracted 0 datasets in 0.18 seconds Applying strategy: normalize_units Applying strategy: update_ecoinvent_locations Applying strategy: remove_zero_amount_coproducts Applying strategy: remove_zero_amount_inputs_with_no_activity Applying strategy: remove_unnamed_parameters Applying strategy: es2_assign_only_product_with_amount_as_reference_product Applying strategy: assign_single_product_as_activity Applying strategy: create_composite_code Applying strategy: drop_unspecified_subcategories Applying strategy: fix_ecoinvent_flows_pre35 Applying strategy: drop_temporary_outdated_biosphere_flows Applying strategy: link_biosphere_by_flow_uuid Applying strategy: link_internal_technosphere_by_composite_code Applying strategy: delete_exchanges_missing_activity Applying strategy: delete_ghost_exchanges Applying strategy: remove_uncertainty_from_negative_loss_exchanges Applying strategy: fix_unreasonably_high_lognormal_uncertainties Applying strategy: set_lognormal_loc_value Applying strategy: convert_activity_parameters_to_list Applied 19 strategies in 0.02 seconds 0 datasets 0 exchanges 0 unl…
score: 0

http://stackoverflow.com/a/52655951
has body: @OleksandrDashkov gave a link to a very helpful guide to be able to send millions of requests fairly efficiently with aiohttp and asyncio I will attempt to condense that information to something that should help you with your problem. I highly recommend that you look at the asyncio documentation and other blog posts, so you can have a good understanding of what it is before programming with it (Or read over the code and try to understand what it's doing). We'll start with how a basic fetch works in aiohttp. It's quite similar to requests. import asyncio import aiohttp async def main(): async with aiohttp.ClientSession() as session: async with session.get(url) as response: dostuffwithresponse() # To mimic your code. loop = asyncio.get_event_loop() loop.run_until_complete(main()) # If you're on Python 3.7 :o asyncio.run(main()) Fairly straightforward. If you used requests' session object, it should be almost identical other than the async syntax. Now, we want to get a lot of URLs. We also don't want to recreate a session object every time. async def fetch(session, url): async with session.get(url) as response: dostuffwithresponse() async def main(): async with aiohttp.ClientSession() as session: for file in list_files: for link in open(file).readlines(): await fetch(session, url) Now we are fetching all the URLs. It's still the same behavior, still synchronous because we're waiting for fetch() to complete before going to the next link. async def fetch(session, url): ... async def main(): tasks = [] async with aiohttp.ClientSession() as session: for file in list_files: for link in open(file).readlines(): task = asyncio.ensure_future(fetch(session, url)) tasks.append(fut) results = await asyncio.gather(*tasks) # results is a list of everything that returned from fetch(). # do whatever you need to do with the results of your fetch function Here I would suggest that you try to understand what asyncio.ensure_future() is and asyncio.gather() does. Python 3.7 have a new reva…
answers question: http://stackoverflow.com/q/52617523
type: Answer
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/comment/92302764
type: Comment
comment on: http://stackoverflow.com/a/52650092
score: 1
type: AnswerComment
has text: @ShlomiSchwartz As I see in the figure, there are three LSTM layers so I think what I have suggested in my answer is correct.

http://stackoverflow.com/a/52599567
answers question: http://stackoverflow.com/q/52599469
has body: discord.Client uses __getattr__ to handle attribute lookup for the user attribute dynamically. __getattr__ is fundamentally incompatible with the kind of static analysis PyCharm uses for autocompletion. I'd probably just live with PyCharm not being able to find this attribute. If you want to do something about it anyway, writing type stubs might help (or they might go out of sync with the implementation and cause more problems), or you could see if discord.py would accept a pull request to use properties instead of __getattr__/__setattr__ for the attribute forwarding they're doing here.
accepted answer of: http://stackoverflow.com/q/52599469
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/52670512
has comment: http://stackoverflow.com/comment/92271144
has comment: http://stackoverflow.com/comment/92271229
score: 0
has body: You should be able to get away with using a context manager, but I think you're pulling the end of the certificate using this way, so you should instead download the file through the api pip install --upgrade google-cloud-storage Then # Initialise a client storage_client = storage.Client("[Your project name here]") # Create a bucket object for our bucket bucket = storage_client.get_bucket(bucket_name) # Create a blob object from the filepath blob = bucket.blob("folder_one/foldertwo/filename.extension") # Download the file to a destination blob.download_to_filename(path_to_gcs_file) with open(path_to_gcs_file, "rb" as f: train_df = = pickle.load(f) Much was taken from this answer: Downloading a file from google cloud storage inside a folder
has comment: http://stackoverflow.com/comment/92270773
answers question: http://stackoverflow.com/q/52670408
has comment: http://stackoverflow.com/comment/92270801
has comment: http://stackoverflow.com/comment/92270971
has comment: http://stackoverflow.com/comment/92271477
has comment: http://stackoverflow.com/comment/92271320
type: Answer

http://stackoverflow.com/comment/92162638
score: 1
has text: Hey @PeterDolan thanks for the comment and time. I've updated the question to reflect the expected output if I encounter a cluster of values.
type: QuestionComment
comment on: http://stackoverflow.com/q/52613747
type: Comment

http://stackoverflow.com/comment/92250302
type: QuestionComment
comment on: http://stackoverflow.com/q/52659659
has text: Is there an actual reason to use so many threads, though? You should probably try with 1 SQS reading thread that puts messages in a `queue.Queue()`, then 1 to N threads that read from that queue and do the `# some calculation` bit for a single message.
score: 0
type: Comment

http://stackoverflow.com/comment/92344220
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52708921
has text: Edit your question and include both the code and the error.
score: 0

http://stackoverflow.com/a/62127105
has body: You need to enter into the environment where you have Python3.7 installed. Once inside pip uninstall ibm_db once ibm_db is uninstalled conda install -c conda-forge ibm_db This will download and install the packages from Anaconda site navigate to site-packages- open terminal cd /opt/anaconda3/lib/python3.7/site-packages change name for the lib install_name_tool -change libdb2.dylib /opt/anaconda3/lib/python3.7/site-packages/clidriver/lib/libdb2.dylib ibm_db.cpython-37m-darwin.so ln -s clidriver/lib/libdb2.dylib libdb2.dylib Restart terminal and run import ibm_db voila!!!
score: 1
answers question: http://stackoverflow.com/q/52597237
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/52629265
has comment: http://stackoverflow.com/comment/112297014
has answer: http://stackoverflow.com/a/52629475
accepted answer: http://stackoverflow.com/a/52629475
tagged with: python
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/39458193
score: 40
type: Question
upvote count: 41
has title: Static typing in python3: list vs List
downvote count: 1
answer count: 1
tagged with: python-typing
favorite count: 0
duplicate of: http://stackoverflow.com/q/39458193
has body: What is the difference between using list and List when defining for example the argument of a function in python3? For example, what is the difference between def do_something(vars: list): and def do_something(vars: List): The documentation says: class typing.List(list, MutableSequence[T]) Generic version of list. Useful for annotating return types. but I'm not entirely sure what the above means. I have similar questions for: dict vs Dict, set vs Set, etc.

http://stackoverflow.com/q/52589462
has comment: http://stackoverflow.com/comment/92113776
has comment: http://stackoverflow.com/comment/92121592
has comment: http://stackoverflow.com/comment/92114446
has comment: http://stackoverflow.com/comment/92113835
has comment: http://stackoverflow.com/comment/92114125
has answer: http://stackoverflow.com/a/52613414
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92113669
has body: I have a lists of lists of length 42, and each list has about 16 items in it. I have noticed that copying the list to excel using xlwings only works for up to 25 lists and anything after that doesn't work, or works sometimes and sometimes doesn't. I have the complete list and code below if anyone would like to reproduce the issue. import xlwings as xw data = [['1st', '(6)', '29.9', '407m', '22/05/2017', 'GRAC', 'M', '23.76', '23.76', '23.13', '8.62', '0.50', 'Supreme Flash', '1111', '', '$6.60'], ['8th', '(5)', '29.8', '407m', '29/05/2017', 'GRAC', '5', '24.64', '23.52', '23.15', '9.02', '16.00', 'Vision Time', '1788', '', '$17.80'], ['5th', '(3)', '30.3', '305m', '12/06/2017', 'GRAC', '5', '18.25', '17.84', '17.81', '3.30', '5.75', 'Red Red Wine', '7835', '', '$21.60'], ['2nd', '(2)', '30.1', '407m', '07/07/2017', 'GRAC', 'MX', '23.62', '23.57', '22.89', '8.60', '0.75', 'Tictac Cloud', '3222', '', '$24.10'], ['4th', '(4)', '29.9', '407m', '14/07/2017', 'GRAC', '5', '23.58', '23.44', '22.98', '8.67', '2.00', 'Kooringa Theo', '2434', '', '$7.00'], ['8th', '(4)', '29.9', '407m', '24/07/2017', 'GRAC', '5', '24.44', '23.75', '23.03', '8.88', '9.75', 'Myraki', '3458', '', '$10.20'], ['1st', '(1)', '30.4', '407m', '07/08/2017', 'GRAC', '5', '23.41', '23.41', '23.12', '8.52', '3.00', 'Myraki', '11', '', '$8.10'], ['1st', '(7)', '30.4', '407m', '14/08/2017', 'GRAF', '5', '23.53', '23.53', '23.18', '8.62', '0.75', 'Gee Tee Bee', '11', '', '$26.40'], ['4th', '(6)', '30.6', '420m', '22/08/2017', 'LISM', '5', '24.58', '23.97', '23.88', '', '8.75', 'Bazaar Mckenzie', '5444', '', '$12.20'], ['5th', '(8)', '31.7', '407m', '23/10/2017', 'GRAC', '5', '23.86', '23.55', '23.27', '8.71', '4.25', 'Hidden Sniper', '1755', '', '$8.50'], ['3rd', '(8)', '31.3', '407m', '30/10/2017', 'GRAC', '5', '23.68', '23.40', '23.13', '8.63', '4.00', 'Hidden Sniper', '1763', '', '$10.20'], ['1st', '(8)', '30.4', '420m', '14/11/2017', 'LISC', '5', '24.19', '24.19', '23.93', '9.82', '1.50', 'Pavlova Cloud…
has comment: http://stackoverflow.com/comment/92114157
has comment: http://stackoverflow.com/comment/92120290
has comment: http://stackoverflow.com/comment/92120761
type: UnansweredQuestion
has title: How to use Python xlwings to copy a large list of lists to Excel
tagged with: python
has answer: http://stackoverflow.com/a/52606855
tagged with: xlwings
tagged with: list
has comment: http://stackoverflow.com/comment/92113733
type: Question

http://stackoverflow.com/comment/92383535
comment on: http://stackoverflow.com/a/52728556
score: 0
type: AnswerComment
type: Comment
has text: Thanks, I tried it but ended up with: `TypeError: catching classes that do not inherit from BaseException is not allowed` I am using python 3.5.4

http://stackoverflow.com/a/52682754
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52682678
score: 3
has body: You could use another dictionary to map the values to the lists of corresponding keys. Then just select the values that map to more than one key, e.g.: from collections import defaultdict sample_dict = {'1': ['a','b','c'], '2': ['d','e','f'], '3': ['g','h','a']} d = defaultdict(list) # automatically initialize every value to a list() for k, v in sample_dict.items(): for x in v: d[x].append(k) for k, v in d.items(): if len(v) &gt; 1: print([v, k]) Output: [['1', '3'], 'a']
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52682678

http://stackoverflow.com/comment/92207964
type: AnswerComment
comment on: http://stackoverflow.com/a/52637426
score: 0
type: Comment
has text: `httpie` installs a command line tool which can be used to send http requests from the command line.

geoalchemy2
tag name: geoalchemy2
tags question: http://stackoverflow.com/q/52723239
type: Tag

http://stackoverflow.com/q/52659777
score: 0
answer count: 1
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52660518
tagged with: python
type: AnsweredQuestion
has body: When the grid is uniform, I believe one must not see the vertical lines which in my opinion indicates "gap" in data points. The following code replicates my issue.The plot is shown here. import numpy as np x = np.arange(0,100,1) y = np.arange(0,100,1) xmesh,ymesh = np.meshgrid(x,y) plt.scatter(xmesh,ymesh,s=0.5) # or plt.plot(xmesh,ymesh,'k.',ms=1)
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/92250788
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52660518
has title: When trying to visualise "regular" grid points generated by numpy.meshgrid() I am seeing white vertical lines. Why is that the case?
tagged with: scatter-plot

http://stackoverflow.com/a/52695212
score: 1
upvote count: 1
downvote count: 0
has body: Here are several ways it could be done # options 1 and 2 use numpy import numpy as np # 1 # use numpy isin and numpy searchsorted functions mask = np.isin(df_a.A, df_b.A) df_a.B.values[mask] = \ df_b.B.values[np.searchsorted(df_b.A.values, df_a.A.values[mask])] # ----------------------------------------------------------------- # using pandas merge for next 3 methods: merged = df_a.merge(df_b, on='A', how='outer', suffixes=('_dfa', '_dfb')) # 2 # use numpy where to fill in with df_a["B"] values df_a['B'] = np.where(merged['B_dfb'].isnull(), merged['B_dfa'], merged['B_dfb']).astype(int) # 3 # same as above but use pandas series where to fill values df_a['B'] = merged.B_dfa.where(merged['B_dfb'].isnull(), merged['B_dfb']).astype(int) # 4 # use series fillna df_a['B'] = merged['B_dfb'].fillna(merged['B_dfa']).astype(int) #---------------------------------------------------------------- # for next 2 methods, make "A" column indexed # dataframes from df_a, df_b a = df_a.set_index('A') b = df_b.set_index('A') # 5 # using pandas dataframe update a.update(b) df_a['B'] = a['B'].values.astype(int) # 6 # using pandas auto-align by index and pandas series where # using pandas auto-align to index, # add dataframe b "B" values to dataframe a (df_a indexed with column "A") a['C'] = b['B'] # using pandas series where, fill in values from a["B"] and # assign to df_a["B"] df_a['B'] = a['C'].where(~a['C'].isnull(), a['B']).values.astype(int) # or use pandas series fillna df_a['B'] = a['C'].fillna(a['B']).values.astype(int) # -------------------------------------------------------------------- # 7 # slightly modified version of accepted answer avoiding setting index df_a['B'] = df_a['A'].map(dict(df_b.values)).fillna(df_a['B']).astype(int)
type: Answer
answers question: http://stackoverflow.com/q/52689825

http://stackoverflow.com/comment/92168388
type: Comment
comment on: http://stackoverflow.com/a/52606689
score: 0
type: AnswerComment
has text: I have added info to the answer. Please provide schema info from parquet-tools to be sure. https://github.com/apache/parquet-mr/tree/master/parquet-tools#parquet-tools

http://stackoverflow.com/q/52657859
has comment: http://stackoverflow.com/comment/92258353
tagged with: python
has body: So I have a dataset with this structure Input Input: 2 inputs [x, y] Range: -99999 - 99999 Output Output: 4 output [0,0,0,1] (Onehot encoding) Range: 0 - 1 What I want to create is a simple Quadrant like this. And I want to see how single layer perceptron is actually do it. I Got this code from here plot_x = np.array([np.min(x[:, 0] - 10), np.max(x[:, 1]) + 10]) #This is for 2 weights plot_y = - 1 / W[1] * (W[0] * plot_x + b) # comes from, w0*x + w1*y + b = 0 then y = (-1/w1) (w0*x + b) plt.scatter(x[:, 0], x[:, 1], c=y, s=100, cmap='viridis') plt.plot(plot_x, plot_y, color='k', linewidth=2) plt.xlim([-99999, 99999]) plt.ylim([-99999, 99999]) plt.show() My question is, how do I calculate plot_y from these weights? I'm (very) new in matplotlib and this is my first time trying to make a visualization. From my understanding, plot_y will create a line to split the classification.
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92302523
tagged with: plot
tagged with: math
tagged with: matplotlib
type: Question
has title: How to plot a line with more than 2 weight?

http://stackoverflow.com/comment/92301678
comment on: http://stackoverflow.com/a/52685054
type: Comment
has text: @DmitryVerhoturov That's right but makes no practical difference for this answer. References are reference-counted, https://docs.python.org/3/c-api/structures.html#c.PyVarObject
score: 5
type: AnswerComment

http://stackoverflow.com/comment/92326370
score: 0
type: AnswerComment
has text: sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 10061] No connection could be made because the target machine actively refused it)") (Background on this error at: http://sqlalche.me/e/e3q8)
comment on: http://stackoverflow.com/a/52699333
type: Comment

http://stackoverflow.com/q/52742302
tagged with: google-app-engine
tagged with: python
tagged with: gettext
tagged with: internationalization
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52803222
type: Question
has title: Python gettext i18n have different version of the same language
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52803222
has body: I have translated my service running on GAE in various language. The code below works. However, I want to be able to specify also the country. Specifically, I want to be able to use 2 Portuguese translations: pt_PR and pt_BR. (I have already created the 2 folder with the .mo files) i18n.get_i18n().set_locale(language) localedir = '/'.join((os.path.dirname(__file__), '..', 'locale')) try: transl = gettext.translation('strings', localedir = localedir, languages = [language]) except IOError: return transl.install() I'm using webapp2 as framework.
favorite count: 0
upvote count: 2

http://stackoverflow.com/comment/92317756
comment on: http://stackoverflow.com/q/52694936
has text: @pygo It would not match for 'New Jersy' if master zip record has 'New Jersey'. My data is coming from a user form, and may contain misspellings.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92125614
type: QuestionComment
comment on: http://stackoverflow.com/q/52595386
score: 0
has text: How is `collections.Counter.most_common` relevant here?
type: Comment

http://stackoverflow.com/q/52668426
tagged with: http://stackoverflow.com/tag/c
has answer: http://stackoverflow.com/a/52702597
answer count: 2
possible better answer: http://stackoverflow.com/a/52668918
has answer: http://stackoverflow.com/a/52668918
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92267403
tagged with: python
accepted answer: http://stackoverflow.com/a/52702597
type: AnsweredQuestion
score: 3
has title: Python C API check if int64 is unsigned
upvote count: 3
has comment: http://stackoverflow.com/comment/92322047
has body: I'm writing a Python3 script with some computationally heavy sections in C, using the Python C API. When dealing with int64s, I can't figure out how to ensure that an input number is an unsigned int64; that is , if it's smaller than 0. As the official documentation suggests, I'm using PyArg_ParseTuple() with the formatter K - which does not check for overflow. Here is my C code: static PyObject* from_uint64(PyObject* self, PyObject*){ uint64_t input; PyObject* output; if (!PyArg_ParseTuple(args, "K", &amp;input)){ return PyErr_Format(PyExc_ValueError, "Wrong input: expected unsigned 64-bit integer."); } return NULL; } However, calling the function with a negative argument throws no error, and the input number is casted to unsigned. E.g., from_uint64(-1) will result in input=2^64-2. As expected, since there's no overflow check. What would be the correct way of determining whether the input number is negative, possibly before parsing it?
type: Question
has comment: http://stackoverflow.com/comment/92267447

http://stackoverflow.com/comment/92273695
type: AnswerComment
has text: @RufusVS Thanks for pointing that out. I partially understood the question.
score: 0
comment on: http://stackoverflow.com/a/52671776
type: Comment

http://stackoverflow.com/a/52633307
upvote count: 9
downvote count: 0
type: Answer
has body: There is no general way to make lines of different thickness or color on individual sides of cells (Rectangles) in matplotlib. In the case of the question, the solution is however quite easily obtained via ax.axhline() (as commented by @GAnderson) due to the table filling the entire bounding box of the axes. You would first need to set the data range of the axes to range between -1 and the number of rows in the table. Then you can just plot an axhline at the position of choice. There are only two line changed (which I marked with a comment) and it seems you can completely get rid of the get_table function. import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib import six df = pd.DataFrame() df['date'] = ['2016-04-01', '2016-04-02', '2016-04-03', '2016-04-04'] df['calories'] = [2200, 2100, 1500, 1800] df['sleep hours'] = [2200, 2100, 1500, 1500] df['gym'] = [True, False, False, True] def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14, header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w', bbox=[0, 0, 1, 1], header_columns=0, ax=None, **kwargs): if ax is None: size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height]) fig, ax = plt.subplots(figsize=size) ax.axis('off') ax.axis([0,1,data.shape[0],-1]) ## &lt;---------- Change here mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs) mpl_table.auto_set_font_size(False) mpl_table.set_fontsize(font_size) for k, cell in six.iteritems(mpl_table._cells): cell.set_edgecolor(edge_color) if k[0] == 0 or k[1] &lt; header_columns: cell.set_text_props(weight='bold', color='w') cell.set_facecolor(header_color) else: cell.set_facecolor(row_colors[k[0]%len(row_colors) ]) return ax def set_row_edge_color(ax, row, color): ax.axhline(y=row, color=color) ## &lt;---------- Change here ax = render_mpl_table(df, header_columns=0, col_width=2.0) set_row_edge_color(ax, 2, 'k') plt.show()
answers question: http://stackoverflow.com/q/52632356
score: 9
accepted answer of: http://stackoverflow.com/q/52632356
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/108376572
has comment: http://stackoverflow.com/comment/108374031

http://stackoverflow.com/comment/92374478
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52724487
type: QuestionComment
has text: Can you show your view also?

http://stackoverflow.com/comment/93606232
comment on: http://stackoverflow.com/a/53364613
score: 0
type: AnswerComment
has text: Welcome to StackOverflow. Please read https://stackoverflow.com/help/how-to-answer and consider editing your answer
type: Comment

http://stackoverflow.com/comment/92272093
comment on: http://stackoverflow.com/q/52671142
score: 1
has text: Just one remark: there is no `n7` in your string. There is `\n7`. Thta is different. `\n` is one character - the newline.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92418534
score: 1
comment on: http://stackoverflow.com/q/52746519
has text: @PatrickArtner nitpick: neither `zip` nor `map` return a generator, although, they return iterators.
type: QuestionComment
type: Comment

pyparsing
tags question: http://stackoverflow.com/q/52734264
tag name: pyparsing
tags question: http://stackoverflow.com/q/52712042
tags question: http://stackoverflow.com/q/52643462
type: Tag

http://stackoverflow.com/q/52622964
answer count: 0
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92179748
has body: I am using below script to connect to an API. I am sure the details are fine (as when I use these details with Postman, it works). I am getting errors when I run this code. I am trying to connect to OpsGenie Heartbeat. The strange this is it works every time from the Postman but never from the code. import http.client headers = {"Content-type": "application/json", "Authorization": "Value"} def connect(): url = "&lt;completeurl&gt;" conn = http.client.HTTPConnection(url) conn.request("GET", "&lt;apiurl&gt;", {}, headers) print(http.client.responses) conn.close() connect() Errors: /home/fahad/PycharmProjects/Lambda2OpsGenie/venv/bin/python /home/fahad/PycharmProjects/Lambda2OpsGenie/lambda_function.py {&lt;HTTPStatus.PRECONDITION_REQUIRED: 428&gt;: 'Precondition Required', &lt;HTTPStatus.TOO_MANY_REQUESTS: 429&gt;: 'Too Many Requests', &lt;HTTPStatus.BAD_REQUEST: 400&gt;: 'Bad Request', &lt;HTTPStatus.UNAUTHORIZED: 401&gt;: 'Unauthorized', &lt;HTTPStatus.PAYMENT_REQUIRED: 402&gt;: 'Payment Required', &lt;HTTPStatus.FORBIDDEN: 403&gt;: 'Forbidden', &lt;HTTPStatus.NOT_FOUND: 404&gt;: 'Not Found', &lt;HTTPStatus.METHOD_NOT_ALLOWED: 405&gt;: 'Method Not Allowed', &lt;HTTPStatus.NOT_ACCEPTABLE: 406&gt;: 'Not Acceptable', &lt;HTTPStatus.PROXY_AUTHENTICATION_REQUIRED: 407&gt;: 'Proxy Authentication Required', &lt;HTTPStatus.REQUEST_TIMEOUT: 408&gt;: 'Request Timeout', &lt;HTTPStatus.CONFLICT: 409&gt;: 'Conflict', &lt;HTTPStatus.GONE: 410&gt;: 'Gone', &lt;HTTPStatus.LENGTH_REQUIRED: 411&gt;: 'Length Required', &lt;HTTPStatus.PRECONDITION_FAILED: 412&gt;: 'Precondition Failed', &lt;HTTPStatus.REQUEST_ENTITY_TOO_LARGE: 413&gt;: 'Request Entity Too Large', &lt;HTTPStatus.REQUEST_URI_TOO_LONG: 414&gt;: 'Request-URI Too Long', &lt;HTTPStatus.UNSUPPORTED_MEDIA_TYPE: 415&gt;: 'Unsupported Media Type', &lt;HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE: 416&gt;: 'Requested Range Not Satisfiable', &lt;HTTPStatus.EXPECTATION_FAILED: 417&gt;: 'Expectation Failed', &lt;HTTPStatus.UNPROCESSAB…
tagged with: opsgenie
tagged with: python
has comment: http://stackoverflow.com/comment/92180195
favorite count: 0
tagged with: python-3.x
upvote count: 1
type: UnansweredQuestion
has title: Too Many Requests
tagged with: api

http://stackoverflow.com/comment/126762738
comment on: http://stackoverflow.com/q/52665078
type: Comment
type: QuestionComment
has text: You ever figure out how to do this?
score: 0

http://stackoverflow.com/comment/92373483
score: 1
comment on: http://stackoverflow.com/q/52722888
type: QuestionComment
type: Comment
has text: I'm saying that the most logical solution seems to be doing all the formatting before you write, thus avoiding using the `formatters` keyword in `to_html`. I'm describing what piRSquared already posted below so just refer to his example.

http://stackoverflow.com/a/52676071
upvote count: 2
has body: Seems, that you need to check if contentHref is not empty, not photoNode. photoNode anyway will contain information, so it will not be empty. Try something like this: for photoNode in photoNodes: contentHref = photoNode.xpath('.//a/@href').extract_first() if contentHref: # photoHref = photoNode.xpath('.//a/img/@src').extract_first() yield Request(contentHref, callback=self.parse_page, priority = i, dont_filter=True) i -= 1 j += 1 else: pass
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52675948
type: Answer
answers question: http://stackoverflow.com/q/52675948
score: 2

http://stackoverflow.com/q/52674515
type: Question
has comment: http://stackoverflow.com/comment/92278809
has answer: http://stackoverflow.com/a/52692340
score: 0
accepted answer: http://stackoverflow.com/a/52692340
has comment: http://stackoverflow.com/comment/92311224
answer count: 1
has body: I want to show a correlation heatmap in bokeh. I'm inializing an empty Figure: p2 = figure(x_range=[], y_range=[], plot_width=1200,plot_height=1200) After the data source is selected and loaded (on button click), i do p2.x_range.factors = corr["TABLE1"].unique().tolist() p2.y_range.factors = corr["TABLE2"].unique().tolist() source_heat_map.data = corr.to_dict('list') p2.rect( x="TABLE1", y="TABLE2", width=1, height=1, source=source_heat_map, line_color=None, fill_color=bokeh_transform('value', mapper) ) and the heatmap appears, but the x_range.factors and y_range.factors stay blank. If i initialize the Figure p2 with: test = pd.read_csv("Heatmap.csv") source_heat_map.data = test.to_dict('list') name_a = test.columns[0] name_b = test.columns[1] p2 = figure(x_range=b, y_range=a, plot_width=1200,plot_height=1200) p2.rect( x=name_b, y=name_a, width=1, height=1, source=source_heat_map, line_color=None, fill_color=bokeh_transform('value', mapper) ) and then choose another data source and click the button, it works and the x_range.factors and y_range.factors get updated. What do i have to do to update the empty FactorRanges? EDIT: Here's a minimum working example. If you change if True: to if False: and initialize p2 = figure(x_range=[], y_range=[], plot_width=1200,plot_height=1200) the x_range.factors and y_range.factors as empty lists, it won't work anymore. from bokeh.io import curdoc from bokeh.layouts import column,row, widgetbox, Spacer from bokeh.models import ColumnDataSource, Paragraph, LinearColorMapper, ColorBar, BasicTicker, TapTool, CustomJS,BoxSelectTool, Rect, FactorRange from bokeh.models.widgets import Slider, TextInput, Div, Button, Dropdown, TableColumn, DataTable, CheckboxButtonGroup from bokeh.models.annotations import Title from bokeh.plotting import figure,show from bokeh.client import push_session from bokeh.transform import transform as bokeh_transform from bokeh import events from math import pi import pandas as pd def compute_corr(): global match…
has comment: http://stackoverflow.com/comment/92310687
tagged with: python
type: AnsweredQuestion
has title: Bokeh: update empty FactorRange in rect
tagged with: bokeh

http://stackoverflow.com/comment/92515526
score: 0
type: Comment
type: QuestionComment
has text: I'm not sure to follow you... How shall I correct it? I mean my code was perfectly working until something changed beyond my control... And I have no idea how to fix it
comment on: http://stackoverflow.com/q/52729686

http://stackoverflow.com/q/52600369
has answer: http://stackoverflow.com/a/52600704
has comment: http://stackoverflow.com/comment/92135163
score: 0
has title: Python, elif error when running within a input
has answer: http://stackoverflow.com/a/52600426
has body: Every time I run this code, I get an error on the elif in the middle and I have tried fixing this by adjusting the spacing, etc. print("Do you want to find the area of a triangle or trapezoid?") shape = input() if shape = "Triangle" or "triangle": height = float(input("Please enter the height of the triangle: ")) base = float(input("Please enter the base length of the triangle: ")) area = 0.5 * height * base print("The area of a triangle with height", height, "and base", base, "is", area, ".") elif shape = "Trapezoid" or "trapezoid": height_1 = float(input("Please enter the Height of the trapezoid: ")) base_1 = float(input('Please enter the base one value: ')) base_2 = float(input('Please enter the base two value: ')) area_1 = ((base_1 + base_2) / 2) * height_1 #This line is the math for figuring the area of the triangle print("The area of the Trapezoid height", height_1, "and bases", base_1, "and", base_2, "is", area_1, ".") else: print("Wrong shape or misspelled shape. Please check it again!")
favorite count: 0
has comment: http://stackoverflow.com/comment/92135168
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52600421
answer count: 4
has answer: http://stackoverflow.com/a/52600436
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/92416877
type: Comment
comment on: http://stackoverflow.com/a/52745767
score: 0
type: AnswerComment
has text: I use the below command for loading it in to pyspark test=hiveContext.read.option("multiline","true").json(sc.wholeTextFiles('file:/xxx/xxxx.json').values())

http://stackoverflow.com/q/52649911
has title: Oauth1.0: How to generate HMAC-SHA1 Oauth_signature without using Access token and token secret in python?
tagged with: oauth
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/57225844
tagged with: oauth-2.0
upvote count: 1
has body: I am trying to access a resource for which I have to implement Oauth1 authorization. When I am using from postman with the option to add empty parameters to signature its working fine but when I am trying to implement the same thing with Python its throwing error. This is my python code So please tell me what are the changes i have to make import requests import json from requests_oauthlib import OAuth1Session from requests_oauthlib import OAuth1 import urllib import random import time from hashlib import sha1 import hmac def sign_request(epocTime,nounce): key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' url = "GET&amp;https://XXXXXXXXXXXXXXXXXXXXX/api/XXXXXXXXXXXXX&amp;oauth_consumer_key=XXXXXXX&amp;oauth_nonce=12345&amp;oauth_signature_method=HMAC-SHA1&amp;oauth_timestamp={}&amp;oauth_version=1.0".format(epoch_time) raw = urllib.quote(url) hashed = hmac.new(key, raw, sha1) print hashed return hashed.digest().encode("base64") def test(): nounce = "12345" epoch_time = int(time.time()) url = "https://XXXXXXXXXXXXXX/api/XXXXXXXXXXXXXXXXXXXXXX" strr = sign_request(epoch_time,nounce) print strr querystring = {"oauth_consumer_key":"1XXXXXXXXXXXXXXXXX","oauth_token":"", "oauth_signature_method":"HMAC-SHA1","oauth_timestamp":epocTime, "oauth_nonce":nounce,"oauth_version":"1.0", "oauth_signature":strr} response = requests.request("GET", url, params=querystring) print response.text test()
has comment: http://stackoverflow.com/comment/109438092
type: Question
tagged with: python-2.7
answer count: 1
downvote count: 0
score: 1
tagged with: postman
linked to: http://stackoverflow.com/q/8338661
favorite count: 0

http://stackoverflow.com/q/52714921
has answer: http://stackoverflow.com/a/52715015
tagged with: webdriver
has body: Get email Tried the code below but element cannot be found: driver.find_element_by_class_name('gprospect_linkedin_button').click()
has answer: http://stackoverflow.com/a/52716137
score: 0
has title: Selenium web driver: How do I click on the button?
has answer: http://stackoverflow.com/a/52715761
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92357867
answer count: 4
has comment: http://stackoverflow.com/comment/92356616
tagged with: selenium-webdriver
tagged with: selenium
has comment: http://stackoverflow.com/comment/92357974
type: Question
has answer: http://stackoverflow.com/a/52776490
has comment: http://stackoverflow.com/comment/92355598
has comment: http://stackoverflow.com/comment/92356802

http://stackoverflow.com/q/52605094
has answer: http://stackoverflow.com/a/52606755
score: 7
has comment: http://stackoverflow.com/comment/92169734
has comment: http://stackoverflow.com/comment/92144561
has body: I'm using Python3 argparse for complicated command-line interface. Lots of arguments, some of them are "verbose" to avoid misunderstandings. parser = argparse.ArgumentParser(description='Command-line interface') parser.add_argument('--long-param-one', help='Long param one description', dest='lond_param_one', required=True) parser.add_argument('--long-param-two', help='Long param two description', dest='lond_param_two', required=True) When param name is long enough and destination variable long as well, it causes ugly formatting when you calling script with --help Command-line interface optional arguments: -h, --help show this help message and exit --long-param-one LONG_PARAM_ONE Long param one description --long-param-two LONG_PARAM_TWO Long param two description I mean, parameter and value are on the one string, description is on other, even though there's plenty of space in console to the right so that put it in one line. Like the fisrt param --help does. When you have 30-40 params, command-line help readability is really worsen
has comment: http://stackoverflow.com/comment/92192080
type: Question
has answer: http://stackoverflow.com/a/52614708
has answer: http://stackoverflow.com/a/78451505
downvote count: 0
has comment: http://stackoverflow.com/comment/92176875
has title: Python argparse: Increase space between parameter and description
answer count: 3
tagged with: argparse
has comment: http://stackoverflow.com/comment/92144970
has comment: http://stackoverflow.com/comment/92144592
linked to: http://stackoverflow.com/q/5462873
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/32888815
type: UnansweredQuestion
tagged with: python
upvote count: 7

http://stackoverflow.com/comment/92319085
comment on: http://stackoverflow.com/q/52696136
score: 0
type: Comment
type: QuestionComment
has text: you should post the code you are using now.

http://stackoverflow.com/comment/92419564
score: 0
type: AnswerComment
type: Comment
has text: So should the left list be scrolled or the accumulation of check buttons on the right?
comment on: http://stackoverflow.com/a/52728207

http://stackoverflow.com/comment/92148339
has text: Have a read through https://stackoverflow.com/questions/4555932/public-or-private-attribute-in-python-what-is-the-best-way and its answers.
score: 0
comment on: http://stackoverflow.com/q/52606882
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92283182
score: 0
comment on: http://stackoverflow.com/a/52676961
type: Comment
has text: I've edited my question above to reflect what I've tried. There are no differences in the HTML from comparing the two `div[class=order-review]` elements
type: AnswerComment

wxpython
tags question: http://stackoverflow.com/q/52602679
tags question: http://stackoverflow.com/q/52695914
type: Tag
tag name: wxpython
tags question: http://stackoverflow.com/q/52652754
tags question: http://stackoverflow.com/q/52615812
tags question: http://stackoverflow.com/q/52629069
tags question: http://stackoverflow.com/q/52677161
tags question: http://stackoverflow.com/q/52721338

http://stackoverflow.com/q/52720733
downvote count: 0
has body: I have label data that same of the values are np.nan. I want to convert the data to OneHot vector using LabelBinarizer, and the np.nan will convert to zero-array. But I get an error. I success to convert the data with get_dummies from pandas model. I can't use the get_dummies function because the train and the test data coming with different files and different time. I want to use sklearn model, for save it, and us the model latter. Code for example: In[11]: df = pd.DataFrame({'CITY':['London','NYC','Manchester',np.nan],'Country':['UK','US','UK','AUS']}) In[12]: df Out[12]: CITY Country 0 London UK 1 NYC US 2 Manchester UK 3 NaN AUS In[13]: pd.get_dummies(df['CITY']) Out[13]: London Manchester NYC 0 1 0 0 1 0 0 1 2 0 1 0 3 0 0 0 In[14]: from sklearn.preprocessing import LabelBinarizer lb = LabelBinarizer() In[15]: lb.fit_transform(df['CITY']) Traceback (most recent call last): File "/home/oshrib/.conda/envs/on_target/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-16-d0afb38b2695&gt;", line 1, in &lt;module&gt; lb.fit_transform(df['CITY']) File "/home/oshrib/.conda/envs/on_target/lib/python3.5/site-packages/sklearn/preprocessing/label.py", line 307, in fit_transform return self.fit(y).transform(y) File "/home/oshrib/.conda/envs/on_target/lib/python3.5/site-packages/sklearn/preprocessing/label.py", line 276, in fit self.y_type_ = type_of_target(y) File "/home/oshrib/.conda/envs/on_target/lib/python3.5/site-packages/sklearn/utils/multiclass.py", line 288, in type_of_target if (len(np.unique(y)) &gt; 2) or (y.ndim &gt;= 2 and len(y[0]) &gt; 1): File "/home/oshrib/.conda/envs/on_target/lib/python3.5/site-packages/numpy/lib/arraysetops.py", line 223, in unique return _unique1d(ar, return_index, return_inverse, return_counts) File "/home/oshrib/.conda/envs/on_target/lib/python3.5/site-packages/numpy/lib/arraysetops.py", line 283, in _unique1d ar.sort() TypeError…
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/92367452
tagged with: one-hot-encoding
type: UnansweredQuestion
tagged with: python
has title: How to convert label data with None values to OneHot using LabelBinarizer sklearn
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92366851
has comment: http://stackoverflow.com/comment/92375070
has comment: http://stackoverflow.com/comment/92549644
has comment: http://stackoverflow.com/comment/92366784
tagged with: pandas

http://stackoverflow.com/a/52718874
score: 2
accepted answer of: http://stackoverflow.com/q/52715864
upvote count: 2
has body: Finally I found an answer which made me happy: import sys print('\n'.join( [modu.__file__ for modu in sys.modules.values() if '__file__' in dir(modu) and modu.__file__ is not None] )) which contains both the system python scripts as well as my user scripts.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92432099
answers question: http://stackoverflow.com/q/52715864
type: Answer
has comment: http://stackoverflow.com/comment/92393021

http://stackoverflow.com/comment/92339682
type: Comment
has text: Yea, the visual for the graph right now is on the back burner until I get the output of `nx.shortest_path` working how I want. I think I'm going to use `nx.write_dot(G)` eventually to display both edges.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52706675

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/52741519
tags question: http://stackoverflow.com/q/52617401
tags question: http://stackoverflow.com/q/52672166
tags question: http://stackoverflow.com/q/52617726
tags question: http://stackoverflow.com/q/52617558
tags question: http://stackoverflow.com/q/52620563
tags question: http://stackoverflow.com/q/52739526
tags question: http://stackoverflow.com/q/52631315
type: Tag

http://stackoverflow.com/q/52672046
type: Question
has comment: http://stackoverflow.com/comment/92274187
score: 1
accepted answer: http://stackoverflow.com/a/52684087
tagged with: google-app-engine-python
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/92274007
has title: ImportError: cannot import name certificate_transparency after installing Pusher
has body: I created a virtualenv with virtualenv env, and then (after sourcing env/bin/activate) installed pusher with pip. However, whenever I try to run my module, I get this error: Traceback (most recent call last): File "/home/proc-daemon/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/home/proc-daemon/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/home/proc-daemon/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/home/proc-daemon/supachat/supachat.py", line 31, in &lt;module&gt; ssl=True File "/home/proc-daemon/supachat/env/lib/python2.7/site-packages/pusher/pusher.py", line 52, in __init__ json_encoder, json_decoder, backend, **backend_options) File "/home/proc-daemon/supachat/env/lib/python2.7/site-packages/pusher/pusher_client.py", line 34, in __init__ json_encoder, json_decoder, backend, **backend_options) File "/home/proc-daemon/supachat/env/lib/python2.7/site-packages/pusher/client.py", line 20, in __init__ from .requests import RequestsBackend File "/home/proc-daemon/supachat/env/lib/python2.7/site-packages/pusher/requests.py", line 17, in &lt;module&gt; import urllib3.contrib.pyopenssl File "/home/proc-daemon/supachat/env/lib/python2.7/site-packages/urllib3/contrib/pyopenssl.py", line 46, in &lt;module&gt; import OpenSSL.SSL File "/home/proc-daemon/supachat/env/lib/python2.7/site-packages/OpenSSL/__init__.py", line 8, in &lt;module&gt; from OpenSSL import crypto, SSL File "/home/proc-daemon/supachat/env/lib/python2.7/site-packages/OpenSSL/crypto.py", line 12, in &lt;module&gt; from cryptography import x509 File "/home/proc-daemon/supachat/env/lib/python2.7/site-packages/cryptography/x509/__init__.py", line 7, in &lt;module&gt; from cryptography.x509 import certificate_transparency ImportError: cannot import name certificate_tra…
type: AnsweredQuestion
tagged with: pusher
has answer: http://stackoverflow.com/a/52684087
downvote count: 0
favorite count: 0
tagged with: python-2.7

http://stackoverflow.com/comment/92351123
comment on: http://stackoverflow.com/a/52712214
has text: Amazing. Thank you.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/52707402
has answer: http://stackoverflow.com/a/52707774
has title: Update and show pictures in a loop with PyQt5
has comment: http://stackoverflow.com/comment/92343499
upvote count: 3
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92341161
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/52707774
tagged with: pyqt5
has body: I have a simple script that periodically takes a screenshot of my screen and saves it on a shared folder. I am now looking to build a script that takes this screenshot and displays it on another PC, updating the displayed picture when the other script runs. I have found this code online which works fine and displays the first pic it finds at the location: import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel from PyQt5.QtGui import QIcon, QPixmap class App(QWidget): def __init__(self): super().__init__() self.title = 'My Screen' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) label = QLabel(self) pixmap = QPixmap('D:\\screen.png') label.setPixmap(pixmap) self.resize(pixmap.width(),pixmap.height()) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) I have tried to modify it like this to make it update every 60 seconds: import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel from PyQt5.QtGui import QIcon, QPixmap class App(QWidget): def __init__(self): super().__init__() self.title = 'My Screen' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() while True: self.update_image() time.sleep(60) def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) label = QLabel(self) pixmap = QPixmap('D:\\screen.png') label.setPixmap(pixmap) self.resize(pixmap.width(),pixmap.height()) self.show() def update_image(self): label = QLabel(self) pixmap = QPixmap('D:\\screen.png') label.setPixmap(pixmap) self.resize(pixmap.width(),pixmap.height()) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) But it's obviously a stupid solution and it doesn't work. Do any of you have an idea of how to do it? Thank you!
type: Question

http://stackoverflow.com/comment/92565403
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52658617
has text: (1) The difference is probably a combination of completely new locales plus alternate-sort variants. (2) I already addressed Unicode-only locales in the answer, with an example of "hi-IN". Codepage 0 is `CP_ACP`, a special value that means the ANSI codepage of the current system locale, which cannot be set to a Unicode-only locale.
type: Comment

http://stackoverflow.com/comment/92265737
comment on: http://stackoverflow.com/a/52667990
score: 0
has text: Don't you think it will be more sound to do a regex pattern for an email and search for that all through the page?
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92408527
type: AnswerComment
comment on: http://stackoverflow.com/a/52740828
has text: @Safron_"...I am looking for a direct solution that doesn't need to change the order of axes of a (potentially huge) array."_ `moveaxis` returns a *view* - not a new array and therefore it does not matter how large is your array. This answer at least explains why you cannot create a 3D "matrix".
score: 0
type: Comment

http://stackoverflow.com/q/52606020
has comment: http://stackoverflow.com/comment/92172159
type: Question
tagged with: google-cloud-sdk
score: 3
upvote count: 3
answer count: 1
has title: Installing Cloud SDK and Python separately
favorite count: 0
tagged with: google-app-engine
tagged with: python
has answer: http://stackoverflow.com/a/52633101
downvote count: 0
type: UnansweredQuestion
has body: I want to install the Google Could SDK on a Windows 10 machine, but to install Python separately rather than using the bundled Python. The instructions Google gives say you can do this, but they don't say if the pre-installed python needs to be x86, x86-64, or if it matters. What are the actual requirements? Thanks, ++PLS

http://stackoverflow.com/comment/92310998
comment on: http://stackoverflow.com/q/52687197
has text: It would be helpful in the future to explain *why* the possible duplicate does not answer your question.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52740678
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52733830
has body: Here an approach we can use to overcome this order-sync issue: First, the order of directories in GitHub repo is by default alphabetically, so if we sort the order for the array of services in JSON objects we will be able to get the same index for both sources. Even to make sure we can sort both of these sources alphabetically. Here's the code: First sort the services array of JSON object as: data['services'] = sorted(data["services"], key=lambda d: d["name"]) By considering the example in the question, it will give us: services = [ {"nodeservice": { "A": "B" } }, {"pyservice":{ "X": "Y" } } ] Then we will sort the list of directories from GitHub repo like this: Repo.clone_from(data['repo_url'], out_dir) list_dir = os.listdir(out_dir) print(list_dir) services = [] for svc in range(0, len(data['services'])): services.append(list_dir[svc]) services.sort() print(services) It will give us: ['nodeservice', 'pyservice'] according to the example above in the question. So, In both cases we have the nodeservice first the pyservice, mean the same order.

http://stackoverflow.com/q/52616845
accepted answer: http://stackoverflow.com/a/52616962
type: AnsweredQuestion
type: Question
has body: I know we can use the following code to create a decile column for based on a column of given data set considering there are tie in the data (see How to qcut with non unique bin edges?): import numpy as np import pandas as pd # create a sample np.random.seed([3,1415]) df = pd.DataFrame(np.random.rand(100, 3), columns=list('ABC')) # sort by column C df = df.sort_values(['C'] , ascending = False ) # create decile by column C df['decile'] = pd.qcut(df['C'].rank(method='first'), 10, labels=np.arange(10, 0, -1)) Is there an easy way to save the cut point from df then use the same cut point to cut a new data set? For example: np.random.seed([1]) df_new = pd.DataFrame(np.random.rand(100, 1), columns=list('C'))
has comment: http://stackoverflow.com/comment/92168110
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92167910
answer count: 1
linked to: http://stackoverflow.com/q/20158597
has title: How to use decile cut from one data to cut another data?
tagged with: python
has answer: http://stackoverflow.com/a/52616962

http://stackoverflow.com/q/52737863
has comment: http://stackoverflow.com/comment/92400377
linked to: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/92400380
type: Question
has title: Iterate a n-array and store values in variables
duplicate of: http://stackoverflow.com/q/1373164
tagged with: numpy
answer count: 1
has body: I have a n-array like this: [[167. 207. 277. 480. 1.] [294. 210. 385. 471. 2.] [448. 212. 532. 474. 0.]] I want to store there row values in 4 variables say a,b,c,d as I want them to write in a file row by row by iterating over the n-array, as I have a lot of these arrays and want them to store in a file.
score: 0
has answer: http://stackoverflow.com/a/52738194
tagged with: python
has comment: http://stackoverflow.com/comment/92400639
type: UnansweredQuestion

http://stackoverflow.com/a/54880615
upvote count: 7
answers question: http://stackoverflow.com/q/52724789
has comment: http://stackoverflow.com/comment/130747828
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/126293314
type: Answer
has comment: http://stackoverflow.com/comment/137079154
score: 7
has body: If you really need to kill the running task, using terminate=True in revoke() method is the proper way and your best option. The problem is that doing this has no guaranteed effect or, better said, can have negative side effects. To understand why, it's necessary to know how revoking works and what terminate=True does. When you call revoke(), you are sending broadcast message to your workers via the broker. That means that before the time you realize you want/need to to kill the task, sending the revoke message and receiving the control command by the worker, the worker might have already finished the task, grabbed another task from the queue and started working on it. When it finally receives the command, it just kills the worker process, which, by that time, might already be working on different task. If you know beforehand you might need to abort your tasks and can adjust the tasks code, you can take a look at abortable tasks.
has comment: http://stackoverflow.com/comment/101403433
accepted answer of: http://stackoverflow.com/q/52724789

http://stackoverflow.com/a/52717025
type: Answer
has body: I think what you are trying to do is replace the ambiguous IUPAC amino acid codes (plus some additional letters that you have somehow gained?) with 'X'. Better to use str.translate() (in Python 3) to do all your replacements at once. Also, since you're using Biopython to read the file, you can also write the output file easily with Biopython. from Bio import SeqIO from Bio.Seq import Seq letters = ["B", "Z", "J", "U", "O"] trans_tab = str.maketrans(''.join(letters), 'X'*len(letters)) def yield_seqs(in_file): for record in SeqIO.parse(in_file, 'fasta'): record.seq = Seq(str(record.seq).translate(trans_tab)) yield record SeqIO.write(yield_seqs('input.fasta'), 'output.fasta', 'fasta') Example: $ cat input.fasta &gt;1 MBZJ $ python3 myscript.py $ cat output.fasta &gt;1 MXXX
accepted answer of: http://stackoverflow.com/q/52716889
score: 4
answers question: http://stackoverflow.com/q/52716889
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52616959
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52617032
accepted answer: http://stackoverflow.com/a/52617032
type: Question
tagged with: dataframe
has title: How to change a value in a dataframe/series in python
tagged with: replace
score: 0
tagged with: pandas
answer count: 1
tagged with: series
has body: I was trying to look up the tickers for Nasdaq 100 companies and got it from wikipedia nasdaq100 = pd.read_html('https://de.wikipedia.org/wiki/NASDAQ-100')[4][0][1:] print(nasdaq100) Which gives me: 1 ATVI 2 ADBE 3 ALXN 4 ALGN 5 GOOG, GOOGL ... ... 100 XLNX However, I would like to get only GOOG. How do I replace "GOOG, GOOGL" with just "GOOG"? This occurs multiple times throughout the list and I would like to get the text before the comma only. for ticker in nasdaq100: if ',' not in ticker: continue else: nasdaq100[ticker] = nasdaq100[ticker].split(',')[0] With the last line I want to update the series in this particular position with only the part that comes before the comma (","). But this is where I get an error: KeyError: 'GOOG, GOOGL' Any help out there?
tagged with: python

distance
tags question: http://stackoverflow.com/q/52722423
tag name: distance
tags question: http://stackoverflow.com/q/52627087
tags question: http://stackoverflow.com/q/52720016
type: Tag
tags question: http://stackoverflow.com/q/52649815
tags question: http://stackoverflow.com/q/52649191

http://stackoverflow.com/a/52651875
has comment: http://stackoverflow.com/comment/92270955
type: Answer
answers question: http://stackoverflow.com/q/52651677
has body: Lets improve your loop.. The first for loop seems legit so you can keep that, just remove count for s in data.song_answer: questions = list(s) print(s) The second for loop can be replaced like this: for question in questions: print('good') questions.remove(question) We dont need to use range in python you can remove whe iterating. I didnt test this but if questions is a valid list it should work.
score: 0

http://stackoverflow.com/comment/92179095
type: QuestionComment
comment on: http://stackoverflow.com/q/52622716
has text: What exact answer you want to get? You cannot find Login button with your current selector. Modify selector or add Implicit/Explicit wait. Also note that `except NoSuchElementException: assert 0` is the worst Exception handling I ever see :) Do not used it. Never
score: 0
type: Comment

http://stackoverflow.com/q/52644597
tagged with: pandas
tagged with: python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
has title: split dataframe by vector in pandas
has body: I have a dataframe with 500 columns and x rows. Now i have a vector t_1 and a vector t_2. Vector t_1 means the start of an event and can contain 1 or more values and t_2 is the end of an event. Both of them indicate the location of a row in the dataframe. example: t1=[4202 6453] t2=[6203 6492] I want to split the dataframe now into to parts and save it as two different dataframes. Row 4202 to 6203 is dataframe1 and row 6453 to 6492 is dataframe 2. This would be the whole Dataframe: A B C D 1 5 2 3 4 .. . . . . 4202 3 4 2 1 4203 2 1 2 2 .. . . . . 6203 1 2 3 1 .. . . . . 6453 5 1 4 3 .. . . . . 6492 1 2 3 4 and this should be the output: Dataframe 1: A B C D 4202 3 4 2 1 .. . . . . 6203 1 2 3 1 and Dataframe 2: A B C D 6453 5 1 4 3 .. . . . . 6492 1 2 3 4 Thank you, R
has answer: http://stackoverflow.com/a/52644886
score: 1
tagged with: dataframe
type: Question
tagged with: split
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52676653
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52676829
accepted answer: http://stackoverflow.com/a/52952912
has body: I have the following data: data = [[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7]] dataFrame = pandas.DataFrame(data).transpose() Output: 0 1 2 0 1.0 1.0 1.0 1 2.0 2.0 2.0 2 3.0 3.0 3.0 3 NaN 4.0 4.0 4 NaN 5.0 5.0 5 NaN NaN 6.0 6 NaN NaN 7.0 Is it possible to create a 4th column AT THE SAME TIME the others columns are created in data, which has the same length as the longest column of this dataframe (3rd one)? The data of this column doesn't matter. Assume it's 8. So this is the desired output can be: 0 1 2 3 0 1.0 1.0 1.0 8.0 1 2.0 2.0 2.0 8.0 2 3.0 3.0 3.0 8.0 3 NaN 4.0 4.0 8.0 4 NaN 5.0 5.0 8.0 5 NaN NaN 6.0 8.0 6 NaN NaN 7.0 8.0 In my script the dataframe keeps changing every time. This means the longest columns keeps changing with it. Thanks for reading
has comment: http://stackoverflow.com/comment/92740381
answer count: 7
tagged with: python
possible better answer: http://stackoverflow.com/a/52915423
upvote count: 6
has answer: http://stackoverflow.com/a/52915298
downvote count: 6
has answer: http://stackoverflow.com/a/52915423
tagged with: python-3.x
score: 0
has answer: http://stackoverflow.com/a/52923305
has answer: http://stackoverflow.com/a/52970046
has comment: http://stackoverflow.com/comment/92740360
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92282506
has answer: http://stackoverflow.com/a/52934723
has comment: http://stackoverflow.com/comment/92282701
tagged with: dataframe
has answer: http://stackoverflow.com/a/52952912
has comment: http://stackoverflow.com/comment/92826262
has title: Create a column that has the same length of the longest column in the data at the same time
has comment: http://stackoverflow.com/comment/92740696

http://stackoverflow.com/q/52724172
answer count: 2
tagged with: list-comprehension
score: 0
tagged with: dictionary-comprehension
has comment: http://stackoverflow.com/comment/92374067
duplicate of: http://stackoverflow.com/q/1747817
tagged with: python
tagged with: dictionary
has title: assigning values to dictionary keys with list comprehension
type: AnsweredQuestion
has body: This is mostly a question of good/pythonic style. I have a dictionary which has lists for values, i.e. my_dict = {"a": a_list, "b": b_list, "c": c_list} and so on. I also have an empty dictionary with the same keys, in which I want to store the mean of these lists against their key. If instead of using a second dictionary, I used a nested list, I could do mean_lists = [[key, sum(l)/len(l)] for key, l in my_dict.items() if l] giving an output [["a", a_mean], ["b", b_mean], ["c", c_mean]] which seems neat to me. Is there a way to do this nicely outputting as a dictionary, or is something like this: mean_dict = {key: [] for key in my_dict} for key, l in my_dict.items(): if l: mean_dict[key] = sum(l)/len(l) the best I can do?
possible better answer: http://stackoverflow.com/a/52724203
linked to: http://stackoverflow.com/q/1747817
has answer: http://stackoverflow.com/a/52724199
accepted answer: http://stackoverflow.com/a/52724199
has answer: http://stackoverflow.com/a/52724203
type: Question

http://stackoverflow.com/q/52616829
has answer: http://stackoverflow.com/a/52617109
has body: I want to take a column indexed 'length' and make it my second column. It currently exists as the 5th column. I have tried: colnames = big_df.columns.tolist() # make index "length" the second column in the big_df colnames = colnames[0] + colnames[4] + colnames[:-1] big_df = big_df[colnames] I see the following error: TypeError: must be str, not list I'm not sure how to interpret this error because it actually should be a list, right? Also, is there a general method to move any column by label to a specified position? My columns only have one level, i.e. no MultiIndex involved.
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/92167862
linked to: http://stackoverflow.com/q/56462088
score: 5
accepted answer: http://stackoverflow.com/a/52617109
linked to: http://stackoverflow.com/q/51486063
tagged with: indexing
type: AnsweredQuestion
upvote count: 5
tagged with: dataframe
linked to: http://stackoverflow.com/q/13148429
type: Question
tagged with: numpy
has title: How to move a column in a pandas dataframe
duplicate of: http://stackoverflow.com/q/13148429
has comment: http://stackoverflow.com/comment/92168935
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92231359
type: Comment
comment on: http://stackoverflow.com/a/52648331
has text: I just tried the last one and got this: ValueError: DataFrame constructor not properly called!
type: AnswerComment
score: 0

http://stackoverflow.com/q/52687197
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92304236
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/52692063
type: Question
has comment: http://stackoverflow.com/comment/92310998
linked to: http://stackoverflow.com/q/51574060
linked to: http://stackoverflow.com/q/50342300
answer count: 1
has body: I'm not a beginner, but I'm also not advanced dev of python code. I'm been trying to animate points movement in scatter plot and to put annotation on every point. All I have done is animation of one point with no annotation. I've searched similar solutions, but it's so confusing. Any help is welcome. This is what I've done. from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import matplotlib.animation as animation frame_count = 0 points = reading_file("some_data") # this method is not of intrest def make_one_point(i): global frame_count, points ex = [1] ey = [1] ez = [1] point = points[i] frame = point[frame_count] ex[0] = frame[0] ey[0] = frame[1] ez[0] = frame[2] frame_count += 1 return ex, ey, ez def update(i): global frame_count, points if frame_count &lt; len(points[i]): return make_one_point(i) else: frame_count = 0 return make_one_point(i) fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') ax1.set_xlim3d(-500, 2000) ax1.set_ylim3d(-500, 2000) ax1.set_zlim3d(0, 2000) x = [1] y = [1] z = [1] scat = ax1.scatter(x,y,z) def animate(i): scat._offsets3d = update(0) ani = animation.FuncAnimation(fig, animate, frames=len(points[10]), interval=100, repeat=True) plt.show() How to animate more points at the same time, and put annontation on every one of them? There are 50 points, and I'm not so consern about efficiency, just to make it work. This code output is moving one point animation
tagged with: scatter3d
score: 0
has title: Animate Points Movement in Scatter plot (matplotlib python)
has comment: http://stackoverflow.com/comment/92304858
has answer: http://stackoverflow.com/a/52692063
tagged with: annotations
has comment: http://stackoverflow.com/comment/92323110
tagged with: animation

http://stackoverflow.com/comment/92261585
score: 0
has text: is read_people supposed to return something...? because it doesn't seem to
type: Comment
comment on: http://stackoverflow.com/q/52665924
type: QuestionComment

http://stackoverflow.com/comment/92273813
type: QuestionComment
comment on: http://stackoverflow.com/q/52672016
has text: What is not working with your attempt?
score: 2
type: Comment

http://stackoverflow.com/comment/92316740
has text: It appears to be getting tripped by the definition of the variable df_mean, but then it is giving several other functions that are having issues with that variable declaration and I don't know what any of those are.
score: 0
comment on: http://stackoverflow.com/q/52694986
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52743577
has comment: http://stackoverflow.com/comment/92414097
answers question: http://stackoverflow.com/q/52743065
has comment: http://stackoverflow.com/comment/92412743
score: 4
upvote count: 4
has body: You can use the autoscale property of Axes objects: Per the documentation: Axes.autoscale(enable=True, axis='both', tight=None) Autoscale the axis view to the data (toggle). Convenience method for simple axis view autoscaling. It turns autoscaling on or off, and then, if autoscaling for either axis is on, it performs the autoscaling on the specified axis or axes. Parameters: enable : bool or None, optional True (default) turns autoscaling on, False turns it off. None leaves the autoscaling state unchanged. axis : {'both', 'x', 'y'}, optional which axis to operate on; default is 'both' tight: bool or None, optional If True, set view limits to data limits; if False, let the locator and margins expand the view limits; if None, use tight scaling if the only artist is an image, otherwise treat tight as False. The tight setting is retained for future autoscaling until it is explicitly changed. fig, ax = plt.subplots() ax.plot(np.random.normal(size=(100,)),np.random.normal(size=(100,)),'bo') ax.autoscale(tight=True) xlim = ax.get_xlim() plt.plot(xlim, xlim, 'k--')
downvote count: 0
has comment: http://stackoverflow.com/comment/98791590
type: Answer
has comment: http://stackoverflow.com/comment/92412806

http://stackoverflow.com/a/52638098
downvote count: 0
score: 1
has body: If this function is in module.py, a file at your project root, then to call read_config() from another Python module at the project root you can do something like this: import module root_dir, ednotes_name, ednotes_output = module.read_config()
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52638031

http://stackoverflow.com/comment/92354591
score: 0
has text: I tried this solution also a few days ago, and after trying again now it didn't provide the correct results.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52704580

http://stackoverflow.com/q/52718289
has comment: http://stackoverflow.com/comment/92362125
has comment: http://stackoverflow.com/comment/92362102
has answer: http://stackoverflow.com/a/52718370
upvote count: 1
has comment: http://stackoverflow.com/comment/92362072
downvote count: 1
has comment: http://stackoverflow.com/comment/92362075
type: Question
has comment: http://stackoverflow.com/comment/92362609
tagged with: for-loop
has answer: http://stackoverflow.com/a/52718549
score: 0
answer count: 3
has body: I have a code snippet in python, I tried running it but I am not able to understand the ouput that is being produced. Here is my code: s = {"chris" :["1", "22", "333", "4444"] } First For loop and it's output: for i in range(len(s["chris"])): #10 print(s["chris"][i]) Output: 1 22 333 4444 Second For loop and it's output: for i in range (len(s["chris"])): #7 print(len(s["chris"][i])) Output: 1 2 3 4 It would be a big help if someone could help me understand both the for loop codes and also help me underdstand the outputs produced. Thanks.
has comment: http://stackoverflow.com/comment/92362100
favorite count: 0
has title: How to use len(dictionary) inside a for loop in python?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92362249
has comment: http://stackoverflow.com/comment/92362173
tagged with: python
has answer: http://stackoverflow.com/a/52718505

http://stackoverflow.com/comment/132066458
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/74785224
has text: Users find it difficult to understand code only answers with no explanation. Please consider adding some description explaining how it solves the problem.
type: Comment

http://stackoverflow.com/q/52634921
tagged with: python
has body: Maybe this is just how Tkinter works but Im unsure. Currently I have the Main window with three frames laid out next to each other. Frame ContainerFrame is a master, then characterFrame and planetFrame are placed inside the ContainerFrame. The issue is or what I would like to happen is that the frames would fill up a set area of the window regardless of whether or not their is data/ widgets in them. Here is what I envision it to look like https://i.sstatic.net/RrWWz.jpg from tkinter import * from tkinter import ttk MainWindow = Tk() def mainWindow(): MainWindow.option_add('*tearOff', False) MainWindow.title("Interface") MainWindow.geometry('800x600') menubar = Menu(MainWindow) MainWindow.config(menu = menubar) File = Menu(menubar) About = Menu(menubar) menubar.add_cascade(menu = File, label = "File") menubar.add_cascade(menu = About, label = "About") def frameContainer(): containerFrame = Frame(MainWindow) containerFrame.pack(anchor = "nw", side = "left", fill = "both", expand = False) scroller = Scrollbar(orient = "vertical") characterFrame = Frame(containerFrame, borderwidth="2", relief="sunken") characterFrame.pack(anchor = "nw", side = "left", expand = True) planetFrame = Frame(containerFrame ,borderwidth="2", relief="sunken") planetFrame.pack(anchor = "nw", side = "right", expand = True) scroller = Scrollbar(orient = "vertical") scroller.pack(anchor = "e", side = "right", fill = "y", expand = False) characterLable = Button(characterFrame, text ="Characters") characterLable.pack() Label(characterFrame, text ="Test1").pack() Label(characterFrame, text ="Test2").pack() Label(planetFrame, text ="Test1").pack() Label(planetFrame, text ="Test2").pack() mainWindow() frameContainer() MainWindow.mainloop()
tagged with: tkinter
has comment: http://stackoverflow.com/comment/92205811
score: 0
has comment: http://stackoverflow.com/comment/92205794
has answer: http://stackoverflow.com/a/52637810
has comment: http://stackoverflow.com/comment/92205548
accepted answer: http://stackoverflow.com/a/52637810
has comment: http://stackoverflow.com/comment/92207497
has title: Frame not expanding
has comment: http://stackoverflow.com/comment/92203455
answer count: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/52600789
answers question: http://stackoverflow.com/q/52600652
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/92135961
has body: You probably want to plot imshow(np.tile(File1.T, (20,20)), extent=[-20,20,-20,20]) See numpy.tile documentation.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52600652

http://stackoverflow.com/a/52715105
score: 0
has comment: http://stackoverflow.com/comment/92356865
has comment: http://stackoverflow.com/comment/92357295
has comment: http://stackoverflow.com/comment/92362414
answers question: http://stackoverflow.com/q/52714919
type: Answer
has body: Assuming the binary number is stored in variable key and your lookup file is opened as file object f: open('messagetype.txt', 'r') as f: for l in f: k, v = l.split(maxsplit=1) if k == key: print(v) Given your sample input, this will output: Blocking 39
has comment: http://stackoverflow.com/comment/92355975

http://stackoverflow.com/q/52592658
accepted answer: http://stackoverflow.com/a/52592816
has comment: http://stackoverflow.com/comment/92120113
type: Question
has title: local variable 'form1' referenced before assignment
has answer: http://stackoverflow.com/a/52592816
has comment: http://stackoverflow.com/comment/92120305
has comment: http://stackoverflow.com/comment/92120013
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/92120396
downvote count: 0
has comment: http://stackoverflow.com/comment/92120063
favorite count: 0
has comment: http://stackoverflow.com/comment/92120139
tagged with: django
tagged with: python
has body: enter image description herei want to allow users to update their profile informations but my problem is that when i submit the form it shows me this error and i can't see where the error is !! @login_required def update_profile(request): if request.method == 'POST': user_u = UpdateUser(request.POST) profile_u = UpdateProfile(request.POST) if user_u.is_valid() and profile_u.is_valid(): request.user.username = user_u.cleaned_data['username'] request.user.first_name = user_u.cleaned_data['first_name'] request.user.last_name = user_u.cleaned_data['last_name'] request.user.email = user_u.cleaned_data['email'] request.user.save() prf = Profile.objects.get(user=request.user) prf.Zip_code = profile_u.cleaned_data['Zip_code'] prf.Phone = profile_u.cleaned_data['Phone'] prf.save() return redirect(reverse('profile')) else: data1 = {'username': request.user.username, 'email': request.user.email, 'first_name': request.user.first_name, 'last_name': request.user.last_name} profile = Profile.objects.get(user=request.user) data2 = {'Phone': profile.Phone, 'Zip_code': profile.Zip_code} form1 = UpdateUser(initial=data1) form2 = UpdateProfile(initial=data2) return render(request, 'store/updateprofile.html', {'form1': form1, 'form2': form2})
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/52698283
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/61532524
tagged with: python-2.7
has answer: http://stackoverflow.com/a/57607284
downvote count: 0
score: 16
favorite count: 0
type: Question
tagged with: urllib3
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/66777134
has answer: http://stackoverflow.com/a/52698390
linked to: http://stackoverflow.com/q/3287038
has body: I set my cronjob to call my script at particular time(ex- 2 4 5 10 * python3 mayank/exp/test.py). When my test.py is called I'm activating the virtualenv within my test.py script as follows. activate = "/home/myserver/schedule_py3/bin/activate_this.py" exec(open(activate).read()) After activating the virtual environment(which has python3 in it and the packages needed to run the script), I'm trying to import requests it is showing me error as:- File "schedule_module/Schedule/notification_task.py", line 2, in <module> import requests File "/usr/lib/python2.7/site-packages/requests/__init__.py", line 43, in <module> import urllib3 File "/usr/lib/python2.7/site-packages/urllib3/__init__.py", line 10, in <module> from .connectionpool import ( File "/usr/lib/python2.7/site-packages/urllib3/connectionpool.py", line 31, in <module> from .connection import ( File "/usr/lib/python2.7/site-packages/urllib3/connection.py", line 45, in <module> from .util.ssl_ import ( File "/usr/lib/python2.7/site-packages/urllib3/util/__init__.py", line 4, in <module> from .request import make_headers File "/usr/lib/python2.7/site-packages/urllib3/util/request.py", line 5, in <module> from ..exceptions import UnrewindableBodyError ImportError: cannot import name UnrewindableBodyError As I can see that it is taking python2.7. Can anyone tell me where I'm wrong? Note- I had installed all the packages using pip3 inside my virtual environment.
tagged with: python-requests
upvote count: 16
has answer: http://stackoverflow.com/a/52698412
has title: Python urllib3 error - ImportError: cannot import name UnrewindableBodyError

http://stackoverflow.com/comment/92193061
type: Comment
type: QuestionComment
has text: you can find just by the first class, also I think it is find_all
comment on: http://stackoverflow.com/q/52629595
score: 0

http://stackoverflow.com/q/52636019
tagged with: python
tagged with: line
upvote count: 3
possible better answer: http://stackoverflow.com/a/52636080
has answer: http://stackoverflow.com/a/52636080
accepted answer: http://stackoverflow.com/a/52636293
has body: I have a text file that has a lot of debug information in it, prior to the data I need. I'm using python3 to attempt to rewrite the output so the file starts with a specific JSON tag. I attempted to use this solution Remove string and all lines before string from file but I'm getting an empty output file so I assume it's not finding the JSON tag. Here is my code: tag = '"meta": [' tag_found = False with open('file.in',encoding="utf8") as in_file: with open('file.out','w',encoding="utf8") as out_file: for line in in_file: if tag_found: if line.strip() == tag: tag_found = True else: out_file.write(line)
linked to: http://stackoverflow.com/q/13693213
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52636293
has title: How to remove all lines from text file up until specific string?

http://stackoverflow.com/comment/92281097
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52675869
has text: I used (\[\*\s\w*\]) and (\[\/\])
score: 0

http://stackoverflow.com/q/52676189
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/15233340
has answer: http://stackoverflow.com/a/52677504
accepted answer: http://stackoverflow.com/a/52676232
has comment: http://stackoverflow.com/comment/92281699
score: 0
has answer: http://stackoverflow.com/a/52676232
tagged with: python-3.x
linked to: http://stackoverflow.com/q/25584124
possible better answer: http://stackoverflow.com/a/52677504
tagged with: python
has body: Sorry I'm new to Python 3 and I already kept looking for an answer here in SO but I can't find the specific answer to my question rather I may not asking the right question. I have a file named test5.txt where I have written the file names of the files that I want to open/read using Python namely, (test2.txt, test3.txt and test4.txt) these txt documents have random words on it. Here is my code: with open("test5.txt") as x: my_file = x.readlines() for each_record in my_file: with open(each_record) as y: read_files = y.read() print(read_files) But sadly I'm getting error: "OSError: [Errno 22] Invalid argument: 'test2.txt\n'"
type: AnsweredQuestion
has title: Open files using For-loop (Python 3)

http://stackoverflow.com/comment/92236182
has text: Again no luck.I am getting the same data frame @G. Anderson
type: Comment
comment on: http://stackoverflow.com/a/52651442
score: 0
type: AnswerComment

http://stackoverflow.com/q/52619958
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92175055
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/100287690
tagged with: uwsgi
type: Question
has title: Rest-Framework return 404 Not Found by nginx
tagged with: nginx
has comment: http://stackoverflow.com/comment/92175161
has body: I have being trying to resolve this issue but it seems as a beginner I am not able to. I have created a project following the tutorial on Django-Rest-Framework and it works perfectly when i run Djnago server. However when I wanted to deploy it using uwsgi and nginx, following many tutorials nginx would display Admin Page but it returns 404 Not Found when i try to access Rest-Framework. My project's structure Project--------| Project------| appInfo------| model-----| views-----| serializer| urls------| _uwsg,ini----| nginx.conf---| static-------| admin----| rest_framework| media--------| manage.py----| uwsgi_params-| Here is my uwsgi.ini # _uwsgi.ini file [uwsgi] locates chdir = /Users/userName/Desktop/Project/API/Project/ module = project.wsgi # the virtualenv (full path) home = /Users/userName/Desktop/Project/venv master = true env DJANGO_SETTINGS_MODULE=Project.settings # maximum number of worker processes processes = 10 # the socket (use the full path to be safe) socket = /tmp/project.sock # ... with appropriate permissions - may be needed chmod-socket = 664 # clear environment on exit vacuum = true # create a pidfile pidfile = /tmp/project.pid # background the process &amp; log daemonize = uwsgi.log And this is my nginx. # the upstream component nginx needs to connect to upstream mysite { # server 127.0.0.1:8001; server unix:///tmp/project.sock; # for a file socket, more effective } # configuration of the server server { # the port your site will be served on listen 80; server_name localhost; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /Users/userName/Desktop/Project/API/Project/media; } location ^~/static { alias /Users/userName/Desktop/Project/API/Project/static; } location /static/rest_framework/{ alias Project/lib/python3.6/site-packages/rest_framework/static/rest_framework; } location / { uwsgi_pass mysite; include /Users/userName/Desktop/Project/API/Project/uwsgi_params; } } This is th…
tagged with: django-rest-framework
upvote count: 2
has comment: http://stackoverflow.com/comment/92173767

http://stackoverflow.com/q/52735085
tagged with: alpine-linux
tagged with: uwsgi
type: Question
tagged with: docker-compose
has title: Understanding Docker Compose Nginx-Proxy with Docker-Alpine-Python-Flask
score: 0
answer count: 1
tagged with: jwilder-nginx-proxy
type: UnansweredQuestion
has body: I have some problem when using Docker. My problem is understanding reverse proxy when using docker-compose and this library https://github.com/jwilder/nginx-proxy so i have 1 Dockerfile like, here : FROM alpine:latest COPY requirements.txt /tmp/requirements.txt RUN apk add --no-cache \ g++ \ gcc \ freetds \ ca-certificates \ build-base \ libc-dev \ python3 \ python3-dev \ unixodbc-dev \ bash \ nginx \ uwsgi \ uwsgi-python3 \ supervisor && \ python3 -m ensurepip && \ rm -r /usr/lib/python*/ensurepip && \ pip3 install --no-cache-dir --upgrade --force-reinstall pip setuptools && \ pip3 install -r /tmp/requirements.txt && \ rm /etc/nginx/conf.d/default.conf && \ rm -r /root/.cache # Copy ODBC Driver COPY odbc.ini /etc/ COPY odbcinst.ini /etc/ # Copy the Nginx global conf COPY nginx.conf /etc/nginx/ # Copy the Flask Nginx site conf COPY flask-site-nginx.conf /etc/nginx/conf.d/ # Copy the base uWSGI ini file to enable default dynamic uwsgi process number COPY uwsgi.ini /etc/uwsgi/ # Custom Supervisord config COPY supervisord.conf /etc/supervisord.conf # Add demo app COPY ./app /app # EXPOSE 80 WORKDIR /app CMD ["/usr/bin/supervisord"] when i am run docker build -t name/name . #success docker run -d --name=container_name -p 80 name/name:latest #success and i am run curl -i localhost/page #success ------------ and my problem is understanding when using nginx-proxy ------------------ within port assigned 1 Create docker network name reverse-proxy and run jwilder/nginx-proxy docker network create --driver bridge reverse-proxy docker run -d -p 81:80 -p 444:443 \ --name reverse-proxy \ --net=reverse-proxy \ -v /var/run/docker.sock:/tmp/docker.sock:ro \ jwilder/nginx-proxy here my docker-compose.yml version: "3" services: atk-request: build: ./_atkrequest #path which Dockerfile is exists container_name: api-atkrequest restart: always networks: - reverse-proxy # ports: # - 80:80 #host:container expose: - 80 environment: - VIRTUAL_HOST=atkrequest.api.dev #nginx-proxy host - VIRTUA…
tagged with: python
has answer: http://stackoverflow.com/a/55388113

http://stackoverflow.com/comment/92198688
type: QuestionComment
has text: df=df.fillna('N/A')
comment on: http://stackoverflow.com/q/52632687
score: 0
type: Comment

http://stackoverflow.com/q/52685872
favorite count: 0
tagged with: python
has title: Capturing apostrophe using regex
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52685893
upvote count: 1
possible better answer: http://stackoverflow.com/a/52685917
type: Question
has answer: http://stackoverflow.com/a/52685917
linked to: http://stackoverflow.com/q/17486765
has body: I am using Python's re module to capture all modifiers of word color in Am. English (AmE) and Br. English (BrE). I successfully captured almost all words, with the exception of words that end with apostrophe. E.g. colors' This problem is from Watt's Beginning Reg Exp book. Here's sample text: Red is a color. His collar is too tight or too colouuuurful. These are bright colours. These are bright colors. Calorific is a scientific term. “Your life is very colorful,” she said. color (U.S. English, singular noun) colour (British English, singular noun) colors (U.S. English, plural noun) colours (British English, plural noun) color’s (U.S. English, possessive singular) colour’s (British English, possessive singular) colors’ (U.S. English, possessive plural) colours’ (British English, possessive plural) Here's my regex: \bcolou?r(?:[a-zA-Z’s]+)?\b Explanation: \b # Start at word boundary colou?r #u is optional for AmE (?: #non-capturing group [a-zA-Z’s]+ #color could be followed by modifier (e.g.ful, or apostrophe) )? #End non-capturing group; these letters are optional \b # End at word boundary The issue is that colors’ and colours’ are matched until s. Apostrophe is ignored. Can someone please explain what is wrong with my code? I researched this on SO Regex Apostrophe how to match?, and the problems there are about escaping ' and ". Here's Regex101 Thanks in advance.
accepted answer: http://stackoverflow.com/a/52685893
answer count: 2
downvote count: 0
score: 1

http://stackoverflow.com/a/52651432
has comment: http://stackoverflow.com/comment/92234919
has comment: http://stackoverflow.com/comment/92235068
has comment: http://stackoverflow.com/comment/92234654
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92234782
has comment: http://stackoverflow.com/comment/92234835
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52651205
upvote count: 2
has body: How about a model method to create the link? The Django docs mention the following about using model methods, which is applicable to your use case This is a valuable technique for keeping business logic in one place – the model. Meaning you don't need to dig though your templates and template tags to see how an Item's report link is generated -- you can see it all in models.py Something along the following could be a place to start class Item(models.Model): entities = models.ManyToManyField(Entity, related_name='entities') report = models.ForeginKey(Report) def get_report_link(self): link_text = self.report.report_link if self.entities.count() &gt; 0: link_text + "?entity={}".format(','.join([entity.id for entity in self.entities.all()])) return link_text and then in your template: change item.report.report_link|urlize to item.get_report_link
answers question: http://stackoverflow.com/q/52651205

http://stackoverflow.com/comment/92208169
comment on: http://stackoverflow.com/q/52637561
type: Comment
type: QuestionComment
score: 2
has text: Possibly helpful or related [Difference between /usr/bin and /usr/local/bin \[duplicate\]](https://unix.stackexchange.com/questions/259231/difference-between-usr-bin-and-usr-local-bin)

http://stackoverflow.com/q/52697473
tagged with: tkinter
tagged with: python
has comment: http://stackoverflow.com/comment/92326504
type: AnsweredQuestion
type: Question
has body: I am new in python and It is my first code.. my GOAL is to make editable table I used two classes my main class's goal is to print multiple names into a table: from tkinter import * from tabels import * class Improved(): def __init__(self, data): self.data = data self.root = Tk() self.entry = [] self.Grid_buttom() self.text() self.root.mainloop() def Grid_buttom(self): x = ['Name', 'Last name', 'Numbers'] for i in range(3): Label(self.root, text=x[i], borderwidth=1, bg='white', relief='solid', fg='Black', font="Times 13 bold", height=1, width=11).grid(column=i, row=0) for i, item in enumerate(self.data): Button(self.root, text=(self.data[i][0]), command=lambda: self.Command(i), height = 1, width = 15).grid(column=0, row=i+1) def text(self): '''text infront of bottoms''' for i, item in enumerate(self.data): Label(self.root, text=self.data[i][1],borderwidth=1,bg='white',relief='solid',fg='Black', font="Times 13 bold", height = 1, width = 11 ).grid(column=1, row=i+1) Label(self.root, text=self.data[i][2], borderwidth=1, bg='white', relief='solid', fg='Black', font="Times 13 bold", height=1, width=11).grid(column=2, row=i+1) def Command(self,i): self.data[i]=inside_Tables(self.data[i]) x = [['alireza', '2', '3'], ['amir', '5', '6'], ['hossein', '8', '9'], ['hamidreza', 'aghamiri', '09126993613'], ['hamidreza', 'aghamiri', '09126993613']] # dar daste aval size colomn ha ham neveshte shode y = Improved(x) my second class is going to edit each column of our main table by clicking on it from tkinter import * class inside_Tables(): def __init__(self, data): self.data=data self.root=Tk() self.entry=[] self.Grid() self.Buttom() self.root.mainloop() def Grid(self): '''it defines grids Of our TK ..include our rows and columns''' k = 0 for i in range(len(self.data)): v = StringVar(self.root, value=self.data[i]) self.entry.append(Entry(self.root, textvariable=v)) self.entry[k].grid(row=1, column=i) k = k + 1 def Buttom(self): Button(self.root, text="Save", command=lambda: self.Com…
has title: Pass an input with button Tikinter python 3
score: 0
has answer: http://stackoverflow.com/a/52703527
accepted answer: http://stackoverflow.com/a/52703527
answer count: 1
has comment: http://stackoverflow.com/comment/92333676
tagged with: python-3.x

http://stackoverflow.com/comment/92318950
score: 0
comment on: http://stackoverflow.com/q/52696213
type: Comment
type: QuestionComment
has text: @jazz I am using sqlalchemy core. docs is reference to the model table name

http://stackoverflow.com/comment/92426796
type: Comment
has text: I saw this http://holoviews.org/user_guide/Plotting_with_Bokeh.html for hovering and legends enable/disable thing, but how do i do this for above type of dataframe in which multiple columns dataframe is converted into single column dataframe separated by a row of NAN?
type: AnswerComment
comment on: http://stackoverflow.com/a/52750981
score: 0

http://stackoverflow.com/comment/92238833
has text: Looks like there was a bugfix in 0.28.1 that solves that. Is there a reason why you need to pin to these old versions though? The latest is `google-cloud-pubsub==0.38.0`
comment on: http://stackoverflow.com/a/52636721
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92232235
comment on: http://stackoverflow.com/a/52648903
has text: @girijesh96: in Fig.3 The decay of auto-correlations at lags 1, 2, 3 etc is very slow, meaning that each January, say, has the same value as previous January, plus/minus a small change. This is essentially a random walk process, a form of non-stationarity, which you account for by setting d or D to 1. Setting the seasonal orders to (2, 0, 0) would also be OK, but less reflective of what's happening in the time series, I think.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52658139
has comment: http://stackoverflow.com/comment/92246721
downvote count: 2
upvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/92247740
tagged with: pandas
answer count: 1
tagged with: preprocessor
tagged with: data-science
favorite count: 0
has body: In my code I am applying pd.concat(sort=false). But since the package has been updated it the sort keyword argument is no longer available. What are the other options to do the same.?
has answer: http://stackoverflow.com/a/52658415
type: UnansweredQuestion
tagged with: python
has title: Pandas Concatenation no longer has sort keyword argument

http://stackoverflow.com/comment/92144248
score: 0
comment on: http://stackoverflow.com/a/52604947
type: AnswerComment
type: Comment
has text: Thank you it worked :). Can you please explain what was the issue with not providing `'host'` in `app.run` ?

http://stackoverflow.com/comment/92148399
type: QuestionComment
has text: Your code gives an entirely different result for me, starts with error due to `dict` then gives many empty dict prints and only a few with a link. Can't help you further without more effort on your side sorry.
type: Comment
comment on: http://stackoverflow.com/q/52605370
score: 0

http://stackoverflow.com/q/52603503
has comment: http://stackoverflow.com/comment/92142669
tagged with: python
answer count: 4
has title: remove all possible unwanted characters from python string at once
has answer: http://stackoverflow.com/a/52604736
tagged with: python-newspaper
has comment: http://stackoverflow.com/comment/92141495
downvote count: 3
has body: I'm using python module newspaper3k and extracting article summary using its web url. As, from newspaper import Article article = Article('https://www.abcd....vnn.com/dhdhd') article.download() article.parse() article.nlp() text = article.summary print (text) Gives, Often hailed as Hollywood\xe2\x80\x99s long standing, commercially successful filmmaker, Spielberg\xe2\x80\x99s lifetime gross, if you include his productions, reaches a mammoth\xc2\xa0$17.2 billion\xc2\xa0\xc2\xad\xe2\x80\x93 unadjusted for inflation. \r\rThe original\xc2\xa0Jurassic Park\xc2\xa0($983.8 million worldwide), which released in 1993, remains Spielberg\xe2\x80\x99s highest grossing film. Ready Player One,\xc2\xa0currently advancing at a running total of $476.1 million, has become Spielberg\xe2\x80\x99s seventh highest grossing film of his career.It will eventually supplant Aamir\xe2\x80\x99s 2017 blockbuster\xc2\xa0Dangal\xc2\xa0(1.29 billion yuan) if it achieves the Maoyan\xe2\x80\x99s lifetime forecast of 1.31 billion yuan ($208 million) in the PRC. All I want to remove all unwanted characters like \xe2\x80\x99s. I'm avoiding to use multiple replace function. All I want something like:- Often hailed as Hollywood long standing, commercially successful filmmaker, Spielberg lifetime gross, if you include his productions, reaches a mammoth $17.2 billion unadjusted for inflation. The original Jurassic Park ($983.8 million worldwide), which released in 1993, remains Spielberg highest grossing film. Ready Player One,currently advancing at a running total of $476.1 million, has become Spielberg seventh highest grossing film of his career. It will eventually supplant Aamir 2017 blockbuster Dangal (1.29 billion yuan) if it achieves the Maoyan lifetime forecast of 1.31 billion yuan ($208 million) in the PRC
upvote count: 1
linked to: http://stackoverflow.com/q/37782066
type: Question
linked to: http://stackoverflow.com/q/57997338
has answer: http://stackoverflow.com/a/52604226
score: -2
has comment: http://stackoverflow.com/comment/92141379
has answer: http://stackoverflow.com/a/52603680
tagged with: string
tagged with: unicode
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52603767
type: UnansweredQuestion

http://stackoverflow.com/q/52697834
has comment: http://stackoverflow.com/comment/92322281
has title: Why I can't manually call `next` on `file` iterator?
linked to: http://stackoverflow.com/q/18547878
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92322308
answer count: 0
tagged with: file
duplicate of: http://stackoverflow.com/q/1073396
duplicate of: http://stackoverflow.com/q/18547878
type: Question
tagged with: iterator
has comment: http://stackoverflow.com/comment/92322347
has body: This is my Python code. If the line has : I'm want to skip this line and the next line. I'm trying to use file.next since file is an iterator. Why is it not working? file=open("example.txt","r") //output of ls -R currentDirectory="" for line in file: if ":" in line: currentDirectory=line[:-1] file.next() # Error in this line continue A=line.split() print(A) print(len(A)) print('insert into files set name=${name}, inode=${inode}, isDir=${isDir},size=${size}' .format(inode=A[0],name=A[9],isDir="d" in A[1],size=A[5])) The error: Traceback (most recent call last): File "ls-to-sql.py", line 7, in &lt;module&gt; file.next() AttributeError: '_io.TextIOWrapper' object has no attribute 'next I'm sure there are many other ways to implement the same logic. The question is: why this is not working. And if there is another iteration way to solve it.
score: 0

http://stackoverflow.com/comment/92128244
comment on: http://stackoverflow.com/q/52596765
score: 1
has text: Use [`eval()`](https://docs.python.org/3/library/functions.html#eval)?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92283546
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52672727
type: QuestionComment
has text: Question has nothing to do with `machine-learning` or `kaggle` - kindly do not spam the tags (removed).

http://stackoverflow.com/a/52678335
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52678094
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52678094
has body: You already set the index in rename() (which removes the Release Date column), so when you try to set the index in finalDF() again pandas cannot find the Release Date column and throws an exception. Note: df = df.set_index('Release Date', inplace=True) sets the index in-place, so df will be None after the line is executed. Either remove inplace=True or do not do the variable assignment.
score: 1

http://stackoverflow.com/q/52595012
accepted answer: http://stackoverflow.com/a/52595280
tagged with: pretty-print
answer count: 1
has comment: http://stackoverflow.com/comment/92154432
has title: XML ElementTree with pretty print
has body: 1.) if you look at the following tags and the spaces of my xml-output you will notice that the spaces are not that correct, cause of the code in 2.) & & & Current output: <SD-ID-Gesart> <SD-ID-Code> DD-RE-1.0G-10 14.84 73.19 7.92 95.32 <Form>Rectangle <Art>Deckendurchbruch/Art> -HT-SAN-DURCHBRUCH 1.OG OKFF +4,50 m 1,800000 <Höhe>0,500000</Höhe> 0,450000 <Status_Neu>0</Status_Neu> <Status_Geändert>1</Status_Geändert> <SD-ID-Code> 2.) I am calling indent() to pretty print my xml-files. It is working almost as wished, except from one little mistake in the code you see below. The mistake you can see in the xml-output in the picture above. def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + "" if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i 3.) with the code you see next i create the ElementTree, when it went through indent(). indent(sd) tree = ET.ElementTree(sd) tree.write(open(pfad + '\\'+ datei_name + '.xml', "w"), encoding='utf-8', xml_declaration=True, method='xml') I need to edit the definition of the indent() indent function to get the spaces correct. In that case I really have no idea how to put back the spaces when the tag is equal. I would be very very happy if you could help me getting that fixed.
score: 0
has answer: http://stackoverflow.com/a/52595280
has comment: http://stackoverflow.com/comment/92144502
tagged with: elementtree
has comment: http://stackoverflow.com/comment/92154390
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/92124774
tagged with: python
has comment: http://stackoverflow.com/comment/92198825
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92198907
type: Question

http://stackoverflow.com/q/52731302
has body: The output is tf.Variable 'Variable_1:0' shape=(10, 15, 9488) dtype=float32_ref I want to convert it to keras layer. input_output = Input(shape=(10,512)) model = Model(input_output, output) Is there any way to do that? currently, the error is Output tensors to a Model must be the output of a Keras Layer (thus holding past layer metadata). Found: tf.Variable 'Variable_1:0' shape=(10, 15, 9488) dtype=float32_ref ============================================= I tried to use Lambda, but got the error below: ValueError: Output tensors to a Model must be the output of a Keras Layer (thus holding past layer metadata). Found: keras.layers.core.Lambda object at 0x7fad52faf550 Here is what I did: def convert_tensor(self, outputs): return outputs input_result = Input(shape=(int(outputs.shape[0]), int(outputs.shape[1]),int(outputs.shape[2]))) outputs = Lambda(self.convert_tensor(outputs), output_shape=(10, 15, 9488)) model = Model(input_result, outputs)
type: Question
has comment: http://stackoverflow.com/comment/92392954
tagged with: keras
upvote count: 3
has title: How to convert Variable to keras Layer
answer count: 1
has answer: http://stackoverflow.com/a/52734395
tagged with: python
favorite count: 0
type: UnansweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/92392506
downvote count: 0

http://stackoverflow.com/comment/92208766
has text: you should not reuse `sequences`, create another empty list and append to it every loop
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52637834
score: 1

http://stackoverflow.com/comment/92296509
type: QuestionComment
comment on: http://stackoverflow.com/q/52684290
has text: why do you want to insert the new list in the second to last position and how do you want to construct the new list?
score: 0
type: Comment

http://stackoverflow.com/q/52668072
has title: Scipy interp1d inversion when using an array input: how to find the root of the output function array?
tagged with: scipy
type: Question
tagged with: numpy
has body: Let's say I have the following 3d-Numpy-array A: array([[[ 1, 2, 3], [ 1, 4, 9]], [[ 1, 8, 27], [ 1, 16, 81]]]) I want to interpolate the data using interp1d with axis=2, i.e. interpolate the function values 1,2,3, 1,4,9, 1,8,27 and 1,16,81 with x=np.array([1,2,3]) simultaneously (the values represent f(x)=x, x^2, x^3 and x^4, respectively). Luckily, this is possible since interp1d is able to take ND-arrays as a second argument, as long as the interpolation axis is equal to the length of x: f = interp1d(x,A,kind='linear',axis=2,fill_value='extrapolate') So far this works pretty well, f(1) produces array([[1., 1.], [1., 1.]]), f(2) produces array([[ 2., 4.], [ 8., 16.]]) and the interpolation f(1.5) produces array([[1.5, 2.5], [4.5, 8.5]]) i.e. I get a 2x2 array of interpolation functions f(x), evaluated at x. Now comes the problem: I want to invert these interpolation functions to get an an x for a specific function value - element wise for each entry of the 2x2 array. When dealing with a 1D-function g this is usually done by finding the root of the interpolation function minus the requested function value, say a: g_subtracted = lambda x: f(x) - a and finding the zero, for example using scipy.optimize.newton: optimize.newton(g_subtracted,1.0) where 1.0 is an initial guess. Here is my actual question: how can I find the zero of my 2x2 interp2d function array f element wise? When I simply do f_subtracted = lambda x: f(x) - a (this works well for my function array) and then optimize.newton(f_subtracted,1.0) I get the following error: File "&lt;ipython-input-187-4cf34581a978&gt;", line 1, in &lt;module&gt; newton(f,1.0) File "/anaconda3/lib/python3.6/site-packages/scipy/optimize/zeros.py", line 201, in newton if q1 == q0: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Seems to me that optimize.newton is not able to deal with 'function arrays' as input to evaluate them element-wise. Does anyone know a way how to do…
tagged with: arrays
has answer: http://stackoverflow.com/a/52673902
score: 0
answer count: 2
tagged with: interpolation
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52669321

http://stackoverflow.com/comment/93010936
has text: great Minimal, Complete, and Verifiable example.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52657272
score: 0

http://stackoverflow.com/comment/92353079
score: 0
type: Comment
type: QuestionComment
has text: can you clear what actually you want so people can help you out over here.
comment on: http://stackoverflow.com/q/52701358

http://stackoverflow.com/q/52591354
has comment: http://stackoverflow.com/comment/92140877
has body: On the server side, Django rest server is configured with following parsers in settings.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.MultiPartParser' ) } When I send a request from a client with the content-type header as "multipart/form-data", it is not resolving the request data sent from the client (file upload). In the debug mode, request.FILES is coming as empty. If I send the same request without the content-type header, the request object contains the File upload data (success case). In the debug mode, request.FILES contains the files uploaded. We have many REST clients and I cannot force the clients not to set the content-type header. Why is Django not able to resolve multipart data when the content-type header "multipart/form-data" ? Am I missing any configuration here?
type: Question
has comment: http://stackoverflow.com/comment/92153373
tagged with: django-rest-framework
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/92118302
tagged with: python
has title: Django does not support REST request Content-type header as "multipart/form-data"
answer count: 0
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/52690401
tagged with: sequence
favorite count: 0
has title: How to count how many time a sequence appears in a give string in python?
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52690487
has answer: http://stackoverflow.com/a/52690487
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52690650
type: Question
has comment: http://stackoverflow.com/comment/92307714
tagged with: string
tagged with: iteration
has answer: http://stackoverflow.com/a/52690463
upvote count: 3
has answer: http://stackoverflow.com/a/52690451
accepted answer: http://stackoverflow.com/a/52690451
has body: I am trying to count how many time a sequence appears in a given string. def count_seqence(str, seq): count = 0 if seq in str: count += 1 return count print(count_seqence("the quick brown fox jumps over the lazy dog","he")) But this only runs once and does not loop, how can i loop and count how many times appears, because i know looping would be for each char and not a seq, this is making me confusing.

http://stackoverflow.com/a/55272460
has body: Instead of messing with the path and stuff in my .bashrc file, I simply appended the line: conda activate sdesign My environment name is sdesign. So it simply activates the environment every time I open a new terminal. Hope that helps.
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52646961
has comment: http://stackoverflow.com/comment/114513690
has comment: http://stackoverflow.com/comment/97335477
downvote count: 0
has comment: http://stackoverflow.com/comment/97277956

http://stackoverflow.com/a/52737768
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/92400417
has body: You should use np.any instead of np.all for the second case of selecting all but black pixels: np.any(image != [0, 0, 0], axis=-1) Or simply get a complement of black pixels by inverting a boolean array by ~: black_pixels_mask = np.all(image == [0, 0, 0], axis=-1) non_black_pixels_mask = ~black_pixels_mask Working example: import numpy as np import matplotlib.pyplot as plt image = plt.imread('example.png') plt.imshow(image) plt.show() image_copy = image.copy() black_pixels_mask = np.all(image == [0, 0, 0], axis=-1) non_black_pixels_mask = np.any(image != [0, 0, 0], axis=-1) # or non_black_pixels_mask = ~black_pixels_mask image_copy[black_pixels_mask] = [255, 255, 255] image_copy[non_black_pixels_mask] = [0, 0, 0] plt.imshow(image_copy) plt.show() In case if someone is using matplotlib to plot the results and gets completely black image or warnings, see this post: Converting all non-black pixels into one colour doesn't produce expected output
type: Answer
score: 34
upvote count: 35
accepted answer of: http://stackoverflow.com/q/52735231
has comment: http://stackoverflow.com/comment/92400698
answers question: http://stackoverflow.com/q/52735231

http://stackoverflow.com/a/52706450
downvote count: 0
score: 1
has body: You can groupby year and apply a function to each group. def get_bin(group): p80 = group.value.quantile(0.8) p90 = group.value.quantile(0.9) group['bin'] = pd.cut( x=group.value, bins=[-np.inf, p80, p90, np.inf], right=False, labels=['&lt;P80', 'P80_90', '&gt;P90']) return group df.groupby(lambda x: x.year).apply(get_bin) # value bin # index # 2015-02-03 23:00:00 33.24 &lt;P80 # 2015-02-04 07:00:00 45.99 &lt;P80 # 2015-02-04 07:30:00 50.23 &gt;P90 # 2015-02-04 09:00:00 48.46 P80_90 # 2015-02-04 10:00:00 48.40 P80_90
type: Answer
answers question: http://stackoverflow.com/q/52703172
upvote count: 1

http://stackoverflow.com/comment/92123493
has text: there are multiple ways, which ones have you tried so far?
score: 4
comment on: http://stackoverflow.com/q/52594304
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52645878
has comment: http://stackoverflow.com/comment/92224684
answers question: http://stackoverflow.com/q/52645197
has comment: http://stackoverflow.com/comment/92225052
has body: If you're defaulting the registration date in data.py then why are you even setting it when you create the user dict? Maybe this is what's causing it. Also why don't you just create a User instead? You have this: user = { 'email': 'wijgowol@kogun.gi', 'registration_date': datetime.datetime.utcnow(), 'last_name': 'Bowen', 'first_name': 'Charlie', } db_user = User (**user) db_user.save() I'd use this instead: db_user = User( email = 'wijgowol@kogun.gi', last_name = 'Bowen', first_name = 'Charlie' ).save() Edit: As per my comment. Also if the registration date is always set when a user is created then why not just use the _id's timestamp? Edit2: As per the API Reference you need to use a Complex DateTimeField the regular DatetimeField doesn't handle microseconds well. From the DatetimeField reference: Note: Microseconds are rounded to the nearest millisecond. Pre UTC microsecond support is effectively broken. Use ComplexDateTimeField if you need accurate microsecond support.
has comment: http://stackoverflow.com/comment/92223825
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92225945
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52645197

http://stackoverflow.com/q/52706164
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: hash
has comment: http://stackoverflow.com/comment/92339385
tagged with: murmurhash
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92360267
upvote count: 3
linked to: http://stackoverflow.com/q/1742866
has title: get murmur hash of a file with Python 3
type: Question
has body: The documentation for the python library Murmur is a bit sparse. I have been trying to adapt the code from this answer: import hashlib from functools import partial def md5sum(filename): with open(filename, mode='rb') as f: d = hashlib.md5() for buf in iter(partial(f.read, 128), b''): d.update(buf) return d.hexdigest() print(md5sum('utils.py')) From what I read in the answer, the md5 can't operate on the whole file at once so it needs this looping. Not sure exactly what would happen on the line d.update(buf) however. The public methods in hashlib.md5() are: 'block_size', 'copy', 'digest', 'digest_size', 'hexdigest', 'name', 'update' whereas mmh3 has 'hash', 'hash64', 'hash_bytes' No update or hexdigest methods.. Does anyone know how to achieve a similar result? The motivation is testing for uniqueness as fast as possible, the results here suggests murmur is a good candidate. Update - Following the comment from @Bakuriu I had a look at mmh3 which seems to be better documented. The public methods inside it are: import mmh3 print([x for x in dir(mmh3) if x[0]!='_']) &gt;&gt;&gt; ['hash', 'hash128', 'hash64', 'hash_bytes', 'hash_from_buffer'] ..so no "update" method. I had a look at the source code for mmh3.hash_from_buffer but it does not look like it contains a loop and it is also not in Python, can't really follow it. Here is a link to the line So for now will just use CRC-32 which is supposed to be almost as good for the purpose, and it is well documented how to do it. If anyone posts a solution will test it out.
has answer: http://stackoverflow.com/a/65594731
tagged with: http://stackoverflow.com/tag/c
linked to: http://stackoverflow.com/q/7829499
has comment: http://stackoverflow.com/comment/92339109
score: 3

http://stackoverflow.com/a/52722637
score: 3
downvote count: 0
upvote count: 3
type: Answer
has body: I'm replacing my initial answer because I had multiple things going on and it took me a while to untangle them. 1) @lenz is correct. In Python 3 it is unnecessary to use unicodecsv.DictReader. Part of what confused me is the difference in implementation. a) For the older unicodecsv.DictReader from Python 2: kw_args={'errors' : None} with open(filename, 'rb', **kw_args) as file: reader = unicodecsv.DictReader(file, dialect = csv.excel, encoding='utf_8_sig' ) b) For Python 3 csv.DictReader kw_args={'newline' : '','errors' : None,'encoding' : 'utf_8_sig'} with open(filename, 'r', **kw_args) as file: reader = csv.DictReader(file, dialect = csv.excel ) To summarize the differences Mode of file open is now text instead of bytes Because of the different open method, the codec can/should be specified in the file open vs. in the DictReader newline parameter is also only valid for the file opened as text. 2) Because my UTF-8 file was produced by Excel, it has a utf_16_le style BOM at the top of the file. The only coded that works for this is 'utf_8_sig'. 3) Because my output files are being read downstream by SQL Server, the output codec needs to be 'utf_16_le' or SQL Server doesn't recognize it. 4) Also, because the target is SQL Server, I have to manually insert the BOM at the top of the file. csvfile.write('\uFEFF') writer.writeheader() If you open the above output file in Excel it will no longer be in columns, but SQL Server (actually SSIS) now knows how to read the file. 5) Just to mess with me a little more, someone had '\n' in a few of the records. With Excel as source and destination, this was not an issue, but it was for SSIS. My solution: for r in record_list: temp={} for k,v in r.items(): if isinstance(v,str): temp[k] = v.replace('\n',' ') else: temp[k] = v writer.writerow(temp)
answers question: http://stackoverflow.com/q/52712201

http://stackoverflow.com/comment/92409149
has text: Welcome to SO!! Please provide more context!! what techniques you applied so that 21 columns became 63. Provide sample data and so on. How can folks help you here with nothing to work with!!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52742168

http://stackoverflow.com/q/52662675
type: Question
tagged with: flask-security
tagged with: flask
has title: SECURITY_PASSWORD_SALT must not be None - flask security
answer count: 2
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/34902378
favorite count: 0
has answer: http://stackoverflow.com/a/62050772
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/55013458
upvote count: 3
linked to: http://stackoverflow.com/q/25942092
has body: This question is related to: Unique Salt per User using Flask-Security, but I'm more concerned with removing this error message. The linked question established that flask-security uses per-user salts, which is good since a global salt is pointless. So my question is what's the point of this configuration variable, and what should I set it to to resolve this error? Does it matter what I set it to? I don't think I need a global salt since flask-security uses passlib which takes care of salts for me. (The error message in the title occurs even when copying the example straight from the docs: (peewee example))

http://stackoverflow.com/a/52629170
upvote count: 1
has body: Iterate over your list of dict, and collect the 'Rank' value from each of it. Then compute the average. &gt;&gt;&gt; _list = [d['Rank'] for d in student_data] &gt;&gt;&gt; average = sum(_list)/len(_list) &gt;&gt;&gt; average 48 Or, even better as suggested by @timgeb average = sum(d['Rank'] for d in student_data)/len(student_data)
downvote count: 0
answers question: http://stackoverflow.com/q/52629063
has comment: http://stackoverflow.com/comment/92191883
type: Answer
has comment: http://stackoverflow.com/comment/92191740
score: 1

http://stackoverflow.com/q/52592935
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92120579
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/38003406
has answer: http://stackoverflow.com/a/52608926
accepted answer: http://stackoverflow.com/a/52608926
answer count: 1
has comment: http://stackoverflow.com/comment/92123455
tagged with: python
has comment: http://stackoverflow.com/comment/92128350
has comment: http://stackoverflow.com/comment/92123125
has comment: http://stackoverflow.com/comment/92120747
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92122928
has title: Why does Pandas DataFrame function infer float64 which can be downcast to float32
has comment: http://stackoverflow.com/comment/92122586
type: Question
has body: I am starting a large matrix which I convert to dataframe in pandas allowing pandas to infer the data type of the columns. The columns are inferred as float64, but I am subsequently able to downcast these columns to float32 using the pandas to_numeric function without a loss of precision. Why is pandas inefficiently inferring the columns as float64 if they are able to be downcast to float32 without a loss of precision? a = np.matrix('0.1 0.2; 0.3 0.4') a_df = pd.DataFrame(list(map(np.ravel, a)), dtype=None) print(genotype_data_df.dtypes) # the columns are float64 genotype_data_df = a_df.apply(pd.to_numeric, downcast='float') # the columns are now float32 I am assuming that there is an underlying technical or practical reason why the library is implemented in this way? If so I am expecting an answer which would explain why this is the case.

twitter
tags question: http://stackoverflow.com/q/52591066
type: Tag
tags question: http://stackoverflow.com/q/52609813
tag name: twitter

http://stackoverflow.com/comment/92343268
comment on: http://stackoverflow.com/q/52708315
type: Comment
has text: If your input string was `foo.bar bar_foo`, what would your desired output be?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92316491
type: QuestionComment
comment on: http://stackoverflow.com/q/52694844
score: 0
has text: @KlausD. You can't use a car that does not have a front, You can use Django without it's ORM, Actually you can use Django with SQL-Alchemy or even you can execute raw SQL queries in Django! it's better to be more specific about what we talking about!
type: Comment

http://stackoverflow.com/comment/92341928
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52707464
has text: I have tried to write [bash run_file.sh] in the end of the first script, but nothing happens when I run it. I just connects to my instance and stops.
score: 0

pyautogui
tags question: http://stackoverflow.com/q/52673702
tags question: http://stackoverflow.com/q/52638519
type: Tag
tag name: pyautogui

http://stackoverflow.com/a/52657618
type: Answer
has body: I figure it out already and got the solution: test = db.session.query(table).filter(table.colA== 'known', (func.year(table.sDate)) == '2018' , (func.month(table.sDate)) &gt;= '7', (func.month(table.sDate)) &lt;= '9')
accepted answer of: http://stackoverflow.com/q/52657365
answers question: http://stackoverflow.com/q/52657365
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92252929

http://stackoverflow.com/q/52601521
answer count: 1
has title: SMTPAuthenticationError: (535, 'Authentication failed: account disabled') Python app
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: heroku
tagged with: sendgrid
score: -1
has body: My Python app using sendgird account on Heroku to send email for user when they forgot password or login by link. Problem is the sendgrid account, after 1-2 month using get disable, and I must change to new account. Full log: Error: Traceback (most recent call last): File "user_profile/services/profile.py", line 595, in send_mail_with_perm msg.send(fail_silently=fail_silently) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/message.py", line 292, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python2.7/site-packages/email_log/backends.py", line 27, in send_messages num_sent += message.send() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/message.py", line 292, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages new_conn_created = self.open() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 67, in open self.connection.login(self.username, self.password) File "/app/.heroku/python/lib/python2.7/smtplib.py", line 623, in login raise SMTPAuthenticationError(code, resp) SMTPAuthenticationError: (535, 'Authentication failed: account disabled') Anyone get same problem ?
type: Question
has answer: http://stackoverflow.com/a/52601606
has comment: http://stackoverflow.com/comment/92138207
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/92305037
score: 0
comment on: http://stackoverflow.com/q/52688864
has text: That's the issue I've been seeing when I run it - so the last user to be added to the list is tpearce, when I run the script it runs through *all* members of the list attributing their tweets to tpearce, and then the next end of list, etc, etc so it causes a lot of errornous data. How do I get the loop to actually run through the list properly please? :/
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92167561
type: QuestionComment
comment on: http://stackoverflow.com/q/52616549
has text: without a chance to check it: CharField seems to return `str`, and BinaryField seems to return `bytes` which are not the same since Python3 (see https://stackoverflow.com/questions/30580386/why-does-comparison-of-bytes-with-str-fails-in-python3). So `read.charfield == b'\0000'.decode()` may be `true`. I suggest using CharField for the mentioned missing functionality of BinaryField.
score: 1
type: Comment

http://stackoverflow.com/a/52665116
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/97816873
type: Answer
accepted answer of: http://stackoverflow.com/q/52628766
has body: The Message.reply() method creates and sends a ReplyToItem item which doesn't support attachments. See https://learn.microsoft.com/en-us/exchange/client-developer/web-service-reference/replytoitem So if you want to send a reply that has attachments, just create a normal Message item that has a 'Re: some subject' title, contains the attachment, and quotes the original message, if that's needed.
answers question: http://stackoverflow.com/q/52628766
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/97832432
upvote count: 1

http://stackoverflow.com/comment/92322027
comment on: http://stackoverflow.com/a/52668918
has text: Thank you for your answer. The only problem I still have is the case in which the input number is small - e.g. if calling `from_uint64(2)` now throws an error. Should I do some kind of casting from Python? I want to accept any number in the range [0, 2^64-1].
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52600109
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52599941
score: 1
has body: Your symmetry function is not building an output image, but modifying the original image. You could modify it like this: def symmetry(img): w, h = img.size() output_image = Image(width=2*w, height=h) # Or whatever method your library provides to create an empty image object for y in range(h): for x in range(w): original_pixel = img.get(x, y) output_image.set(x, y, original_pixel) # Copying original image output_image.set(w - x - 1, y, original_pixel) # mirroring original image return output_image Notice that if you're using OpenCV (the most used library for image processing), python's for loops aren't the best tool to do the job. You could use numpy.flip and merge together the original and flipped arrays to get a boost in the speed of your application.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52599941

http://stackoverflow.com/q/52644217
downvote count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/92221374
has comment: http://stackoverflow.com/comment/92228218
answer count: 1
linked to: http://stackoverflow.com/q/51125808
favorite count: 0
has comment: http://stackoverflow.com/comment/92222107
has comment: http://stackoverflow.com/comment/92220938
tagged with: python
tagged with: logging
has comment: http://stackoverflow.com/comment/92220887
type: AnsweredQuestion
score: 3
has body: I have the following code for my logging : logging.basicConfig( handlers=[ logging.FileHandler("log.txt", "w"), logging.StreamHandler() ], format='%(levelname)s - %(asctime)s - %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) I would like to set a different level for my 2 handlers. But I realy want to keep it simple, I want to do that with the basicConfig. Is there a way I can do that ? I tried that but it failed : logging.basicConfig( handlers=[ logging.FileHandler("log.txt", "w", level=logging.DEBUG), logging.StreamHandler(level=logging.DEBUG) ], format='%(levelname)s - %(asctime)s - %(message)s', datefmt='%H:%M:%S') TypeError: init() got an unexpected keyword argument 'level'
has comment: http://stackoverflow.com/comment/92220981
has title: Python logging.basicConfig set different level for handlers
type: Question
has answer: http://stackoverflow.com/a/52651624
accepted answer: http://stackoverflow.com/a/52651624

http://stackoverflow.com/comment/92412885
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52744034
has text: You can use an "if" statement to go to the previous month if today is the first day of the month.

http://stackoverflow.com/comment/92308530
type: Comment
has text: @AntonvBR, nice example! +1
comment on: http://stackoverflow.com/a/52689290
type: AnswerComment
score: 0

file
type: Tag
tags question: http://stackoverflow.com/q/52693903
tags question: http://stackoverflow.com/q/52744576
tags question: http://stackoverflow.com/q/52675869
tags question: http://stackoverflow.com/q/52615588
tags question: http://stackoverflow.com/q/52617197
tag name: file
tags question: http://stackoverflow.com/q/52722677
tags question: http://stackoverflow.com/q/52713886
tags question: http://stackoverflow.com/q/52709993
tags question: http://stackoverflow.com/q/52669172
tags question: http://stackoverflow.com/q/52605706
tags question: http://stackoverflow.com/q/52622069
tags question: http://stackoverflow.com/q/52688402
tags question: http://stackoverflow.com/q/52597414
tags question: http://stackoverflow.com/q/52724557
tags question: http://stackoverflow.com/q/52638320
tags question: http://stackoverflow.com/q/52619148
tags question: http://stackoverflow.com/q/52722004
tags question: http://stackoverflow.com/q/52620350
tags question: http://stackoverflow.com/q/52644377
tags question: http://stackoverflow.com/q/52697834
tags question: http://stackoverflow.com/q/52722787
tags question: http://stackoverflow.com/q/52715217
tags question: http://stackoverflow.com/q/52641676
tags question: http://stackoverflow.com/q/52610160

http://stackoverflow.com/a/52636445
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52636288
downvote count: 0
has body: Using np.unique() to count the number of unique coordinates ( however, I don't know this is the fastest way or not, it is not, see the timings below): import numpy as np a = [(0,0), (1,1), (1,0), (0,0)] b = np.array(a) u, c = np.unique(b, axis=0, return_counts=True) m = np.max(b)+1 ans = np.zeros((m, m)) ans[u[:,0], u[:,1]] = c # ans array([[ 2., 0.], [ 1., 1.]]) I did some timing: # data preparation max_coord = 10000 max_size = 100000 # this is awful, I know it can be done much better... coords = [(int(np.random.randint(max_coord, size=1)), int(np.random.randint(max_coord, size=1))) for _ in range(max_size)] # timings using %timeit # my solution 139 ms ± 592 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # Paul Panzer's solution 142 ms ± 461 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # with max_size = 1000000 # my solution 827 ms ± 19.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # Paul's solution 748 ms ± 4.62 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Almost the same (though I don't know about their memory footprint; with max_size=1000000 and max_coord=100000 both solutions give MemoryError on my machine). However, I'll go with the @Paul's solution, it is much more neat (and faster when data is big).

http://stackoverflow.com/a/52745090
answers question: http://stackoverflow.com/q/52736390
score: 3
has body: This is a log warning to tell you that this package is not ready to support async syntax, and this is true, we released the first part of the runtime in msrest 0.6.0, but we didn't released any packages with async support yet. For reference that it's just a warning: https://github.com/Azure/msrest-for-python/blob/master/msrest/async_paging.py#L40 It will not impact any code and will not raise any exception. You will get a problem only if you try to use async for of async syntax (because as the warning tells you, it's not ready for). When we'll start shipping async compatible packages by the end of this year, this warning will disappear automatically as more and more package becomes ready. If this warning is really a problem for you, you can disable the logger "msrest.async_paging" or pin msrest to 0.5.5 (before async core support). Feel free to open an issue on our tracker if you feel this is really a massive problem, and depending on how many people I get bad feedback, I might change it to debug for a few months. But once async packages will be released, it will be an important source of feedback and I truly think it would deserve a warning. https://github.com/Azure/azure-sdk-for-python/issues Thank you for your feedback! (I own this code at Microsoft). Edit: Being that you're not the only one with questions about this, I released a 0.6.1 that removes this warning.
has comment: http://stackoverflow.com/comment/102765898
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/102732963
type: Answer
accepted answer of: http://stackoverflow.com/q/52736390
downvote count: 0

http://stackoverflow.com/q/52723103
tagged with: python
upvote count: 4
type: AnsweredQuestion
tagged with: list
downvote count: 1
has answer: http://stackoverflow.com/a/52723354
accepted answer: http://stackoverflow.com/a/52723354
type: Question
score: 3
tagged with: python-2.7
has body: I have an object called Orders. One of the field in orders is last_modified. the format of this field is 01-JAN-16 02.15.49.086630 PM Then i have a list of these orders i.e., orders_list. How can I sort this list based on last_modified value?
answer count: 1
tagged with: sorting
favorite count: 0
has title: how to sort a list based on timestamp value of an object
tagged with: datetime

http://stackoverflow.com/q/52647908
type: Question
has body: I want to run my long runing python script from my console app. I use ("my_script.py"), when I shut down console also python script is terminate. In task manager all(console app and script) is runing under .Net Core Host. How to run python as completly separated process?
score: 3
tagged with: python
linked to: http://stackoverflow.com/q/43515360
upvote count: 3
has title: Start.Process not run scipt in separate process
tagged with: .net-core
answer count: 1
linked to: http://stackoverflow.com/q/27624850
type: UnansweredQuestion
tagged with: c#
has comment: http://stackoverflow.com/comment/92231782
downvote count: 0
has answer: http://stackoverflow.com/a/52648888
favorite count: 0
has comment: http://stackoverflow.com/comment/92228464

http://stackoverflow.com/q/52633151
tagged with: bufr
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/92199858
favorite count: 0
accepted answer: http://stackoverflow.com/a/52633305
has comment: http://stackoverflow.com/comment/92201603
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92199854
has comment: http://stackoverflow.com/comment/92199723
type: AnsweredQuestion
score: 1
has body: I am needing to calculate the length of a dictionary in octects to conform to the BUFR standard which states: Total length of BUFR message, in octets (including Section 0) I have been able to find bytes, but not information for decoding octects. To get bytes I would do: sys.getsizeof(json_list)
has title: Get Length of object in octects
type: Question
has answer: http://stackoverflow.com/a/52633305
downvote count: 0

http://stackoverflow.com/a/52669317
score: 3
has body: The problem is to concatenate a horizontally with b as a column vector. &lt;concat&gt;( |1 2 3|, |0| ) |5 6 7| |1| The concatentation can be done using np.hstack, and b can be converted into a column vector by adding a new axis: &gt;&gt;&gt; np.hstack([a, b[:, np.newaxis]]) array([[1, 2, 3, 0], [5, 6, 7, 1]])
has comment: http://stackoverflow.com/comment/92268548
downvote count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/92269322
answers question: http://stackoverflow.com/q/52669277
type: Answer

http://stackoverflow.com/q/52625998
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/52626324
type: Question
tagged with: numpy
has body: Suppose I have a signal, say, a sine wave: x = np.arange(100) y = np.sin(x/10) When I plot this, I want to highlight in red the regions where the value of y is above a certain threshold, e.g. 0.7. I thought of doing something like this region = [i for i, e in enumerate(y) if e &gt;= 0.7] fig, ax = plt.subplots() ax.plot(x, y) k = region [0] for i in region: if i-k == 1: ax.axvspan(k, i+1, facecolor='red', alpha=0.2) k = i plt.show() The +1 is added because I want to "include" the last point in the highlighted region. However, this generates overlapping axvspans, which means that the first and last one will be "lighter" (because I'm using alpha = 0.2), as in the figure: Is there another (possibly simpler) way to achieve this?
tagged with: arrays
linked to: http://stackoverflow.com/q/47750593
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52626324
favorite count: 0
has title: Get beginning and end of range in array

http://stackoverflow.com/comment/92116668
has text: How did you install this script? `pip install`?
comment on: http://stackoverflow.com/q/52590837
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52710519
downvote count: 0
has body: I am trying to use pcolormesh to plot 3 one dimensional arrays filled with coordinates and values. The arrays below are simply examples, yet they follow the same principle. I have 3 arrays, one for the x coordinate, one for the y coordinate, and one for their value (or z). Each index corresponds to a location. Index of 0 corresponds to x of 1, y of 1 and z of 6. This goes on for all indexes. x = [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4] y = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4] z = [6,2,3,5,8,2,3,2,4,2,3,6,7,3,3,2] plt.figure() plt.pcolor(x,y,z) plt.colorbar() plt.show() I've also tried... x = [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4] y = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4] z = [6,2,3,5,8,2,3,2,4,2,3,6,7,3,3,2] N = np.sqrt(len(x)) N = int(N) np.reshape(x,(N,N)) np.reshape(y,(N,N)) np.reshape(z,(N,N)) plt.pcolormesh(x,y,c=z) plt.show() Nothing seems to be working. Send Help
tagged with: python-2.7
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52710867
tagged with: python
tagged with: colorbar
tagged with: matplotlib
type: Question
has title: Using pcolormesh with 3 one dimensional arrays in python
score: 5
upvote count: 5

http://stackoverflow.com/q/52654020
has comment: http://stackoverflow.com/comment/92239603
tagged with: lambda
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52654128
score: -1
accepted answer: http://stackoverflow.com/a/52654128
type: Question
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/52654206
tagged with: sorting
has body: I am using Thavelick's summarizer with some edits and cannot find a way to fix this error: TypeError: &lt; lambda > () missing 1 required positional argument: 's2' Here is the code I know is causing the error: def reorder(input, output): output.sort(key=lambda s1, s2: input.find(s1)-input.find(s2)) return output Thavelick's summarizer link: https://github.com/thavelick/summarize/blob/master/summarize.py
possible better answer: http://stackoverflow.com/a/52654206
has title: Lambda/Sort Summariser Issue - Python
tagged with: python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92239644

http://stackoverflow.com/comment/92387881
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52731355
has text: For example, i list will contain the index for words, ii list will contain the index for w, while word is just list of strings that are similar to wwd.
score: 0

http://stackoverflow.com/q/52591281
tagged with: image
has title: How to find the most frequent pixel value in an image?
has comment: http://stackoverflow.com/comment/92118299
answer count: 3
score: 2
possible better answer: http://stackoverflow.com/a/74520712
downvote count: 0
has answer: http://stackoverflow.com/a/76333615
has answer: http://stackoverflow.com/a/74520712
has comment: http://stackoverflow.com/comment/92117222
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92119676
has answer: http://stackoverflow.com/a/52592707
tagged with: python
tagged with: computer-vision
has body: Editors comment: How to count pixels occurences in an image? I have a set of images where each pixel consists of 3 integers in the range 0-255. I am interested in finding one pixel that is "representative" (as much as possible) for the entire pixel-population as a whole, and that pixel must occur in the pixel-population. I am determining which pixel is the most common (the median mode) in my set of images makes the most sense. I am using python, but I am not sure how to go about it. The images are stored as an numpy array with dimensions [n, h, w, c], where n is the number of images, h is the height, w is the widthandc` is the channels (RGB).
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92127219
has comment: http://stackoverflow.com/comment/92129320
has comment: http://stackoverflow.com/comment/92118106
tagged with: image-processing
linked to: http://stackoverflow.com/q/30299267
type: Question
accepted answer: http://stackoverflow.com/a/52592707
has comment: http://stackoverflow.com/comment/92129122

http://stackoverflow.com/comment/92335546
has text: I'll post one when i get home along with frames captured using ffmpeg and OpenCV as comparison as well.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52703014
type: QuestionComment

http://stackoverflow.com/comment/92199537
type: QuestionComment
has text: When I get unusual questions from people using coverage.py, I like to find out as much as I can about their uses. It helps me build a better product.
score: 1
comment on: http://stackoverflow.com/q/52610645
type: Comment

http://stackoverflow.com/a/52807228
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52743613
has body: Assuming you have queries and replies as two Tensors. What you need is I think something like below what you can concatenate then with the original batch. batch_size = 10 def reply_shuffle(queries, replies): shuffled_indices = tf.random_uniform(minval=0, maxval=batch_size+1, shape=[batch_size], dtype=tf.int32) shuffled_replies = tf.gather_nd(replies, shuffled_indices) return queries, shuffled_replies
answers question: http://stackoverflow.com/q/52743613
type: Answer
score: 0

http://stackoverflow.com/q/52707344
has title: Google NDB - required property inside StructuredProperty's structure not working as expected
has body: I have encountered an issue with the required option from ndb.Model when it is placed inside a Model specified as a structure from a StructuredProperty. Here is the models definition : class SubModel(ndb.Model): submodel_id = ndb.StringProperty(required=True) class MyModel(ndb.Model): model_id = ndb.StringProperty(required = True) submodels = ndb.StructuredProperty(SubModel, repeated=True) def __init__(self, *args, **kwargs): super(MyModel, self).__init__(*args, **kwargs) if 'submodels' in kwargs.keys(): _submodels = [] for kwarg in kwargs['submodels']: if isinstance(kwarg, SubModel): _submodels.append(kwarg) else: t = SubModel(**kwarg) _submodels.append(t) self.submodels = _submodels What I want to do is either to create a model with no submodels or to create a model in which every submodels have a required id, otherwise, it raises an error. So when I test this model, I get these results : args1 = {"model_id":"some_id","submodels":[{"submodel_id":null}]} model1 = MyModel(**args1) model1.put() print model1.key.id() # Everything works while submodel_id hasn't been set and it returns the key id from Google Datastore args2 = {"model_id":null,"submodels":[{"submodel_id":"some_id"}]} model2 = MyModel(**args2) model2.put() print model2.key.id() # Google Datastore raises an error : Entity has uninitialized properties: model_id Is this behavior standard behavior from ndb.StructuredProperty (meaning that no property options are considered from the structure specified) or should I implement what I want to do differently ? What I also want to do is to make Submodel inherit from ndb.Expando instead of ndb.Model but since ndb.Expando inherits from ndb.Model, that would be an even more precise question...
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has answer: http://stackoverflow.com/a/52711493
type: Question
score: 0
tagged with: app-engine-ndb
answer count: 1

http://stackoverflow.com/comment/95016315
type: Comment
score: 0
has text: `pip install django==2.0.*`
type: AnswerComment
comment on: http://stackoverflow.com/a/53296132

http://stackoverflow.com/comment/92353496
score: 0
has text: It does not need to be a regex solution. I assumed regex would be the most logical solution.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52711543

http://stackoverflow.com/a/52669783
has body: The more numpythonic way to do this is to avoid broadcasting, and use the function designed for this: numpy.column_stack: np.column_stack([a, b]) array([[1, 2, 3, 0], [5, 6, 7, 1]])
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92269688
type: Answer
accepted answer of: http://stackoverflow.com/q/52669277
downvote count: 0
has comment: http://stackoverflow.com/comment/92269628
answers question: http://stackoverflow.com/q/52669277
score: 1

http://stackoverflow.com/comment/92320709
comment on: http://stackoverflow.com/a/52693394
score: 0
type: AnswerComment
type: Comment
has text: @Ajax1234 your answer only appeared after I finished typing. I submitted it anyway in case it helps someone better to understand the problem.

http://stackoverflow.com/comment/92387916
score: 0
comment on: http://stackoverflow.com/a/52731163
type: Comment
has text: is there any other way to do this? If I have 10 API methods, then I'd need to import 10x which feels a little goofy
type: AnswerComment

http://stackoverflow.com/q/52730864
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/53246979
has comment: http://stackoverflow.com/comment/93052183
possible better answer: http://stackoverflow.com/a/53263818
answer count: 3
has comment: http://stackoverflow.com/comment/93183187
has comment: http://stackoverflow.com/comment/93192748
tagged with: pandas
has answer: http://stackoverflow.com/a/53263818
has comment: http://stackoverflow.com/comment/93011851
has comment: http://stackoverflow.com/comment/93126667
tagged with: assign
favorite count: 0
has comment: http://stackoverflow.com/comment/93184362
has title: Re-assign column values in a pandas df
has comment: http://stackoverflow.com/comment/93167076
tagged with: python
has answer: http://stackoverflow.com/a/53270183
has answer: http://stackoverflow.com/a/53246979
has comment: http://stackoverflow.com/comment/93084884
has comment: http://stackoverflow.com/comment/93085070
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/93183168
has comment: http://stackoverflow.com/comment/93177979
downvote count: 3
score: 17
linked to: http://stackoverflow.com/q/54101445
has comment: http://stackoverflow.com/comment/93085456
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/93011702
upvote count: 20
has body: This question is related to rostering or staffing. I'm trying to assign various jobs to individuals (employees). Using the df below, `[Person]` = Individuals (employees) `[Area]` and `[Place]` = unique jobs `[On]` = How many unique jobs are occurring at each point in time So [Area] and [Place] together will make up unique values that are different jobs. These values will be assigned to individuals with the overall aim to use the least amount of individuals possible. The most unique values assigned to any one individual is 3. [On] displays how many current unique values for [Place] and [Area] are occurring. So this provides a concrete guide on how many individuals I need. For example, 1-3 unique values occurring = 1 individual 4-6 unique values occurring = 2 individuals 7-9 unique values occurring = 3 individuals etc Question: Where the amount of unique values in [Area] and [Place] is greater than 3 is causing me trouble. I can't do a groupby where I assign the first 3 unique values to individual 1 and the next 3 unique values to individual 2 etc. I want to group unique values in [Area] and [Place] by [Area]. So look to assign same values in [Area] to an individual (up to 3). Then, if there are leftover values (&lt;3), they should be combined to make a group of 3, where possible. The way I envisage this working is: see into the future by an hour. For each new row of values the script should see how many values will be [On](this provides an indication of how many total individuals are required). Where unique values are >3, they should be assigned by grouping the same value in [Area]. If there are leftover values they should be combined anyhow to make up to a group of 3. Putting that into a step by step process: 1) Use the [On] Column to determine how many individuals are required by looking into the future for an hour 2) Where there are more than 3 unique values occurring assign the identical values in [Area] first. 3) If there are any leftover values then look to com…

http://stackoverflow.com/comment/92127096
type: Comment
comment on: http://stackoverflow.com/a/52591963
has text: yes i already did let me share it with you https://ibb.co/hkrnBz, as you can see alot of empty cells. I have tried to remove none or ' ' with filter method. It didn't help either.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52599918
type: AnsweredQuestion
has body: How can I print Turkish? open("save.txt", "w+").write("C:\Müzikler") folder = open("save.txt", "r+").read() os.listdir(folder) OUTPUT: FileNotFoundError: [WinError 3] The system cannot find the path specified: C:\xfczikler'
duplicate of: http://stackoverflow.com/q/47897384
type: Question
accepted answer: http://stackoverflow.com/a/52599934
linked to: http://stackoverflow.com/q/47897384
score: 0
has answer: http://stackoverflow.com/a/52599934
answer count: 1
has title: write a file with a Turkish character
tagged with: python

http://stackoverflow.com/comment/92194716
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52629035
has text: What line in the code is causing the error?
score: 0

http://stackoverflow.com/q/52645060
tagged with: data-analysis
tagged with: python
has body: I have a multiple text file and upon reading multiple files in a loop it looks like: @UTF8 @PID: 11312/c-00036109-1 @Begin @Languages: eng @Participants: CHI Target_Child, EXA Investigator @ID: eng|ENNI|CHI|4;11.16|male|SLI||Target_Child||| @ID: eng|ENNI|EXA|||||Investigator||| @Comment: Birth of CHI is 9-MAY-1995 @Date: 25-APR-2000 @Tape Location: Disk L10 Track 3 @Bg: A1 *CHI: I saw a giraffe and a elephant . %mor: pro:sub|I v|see&amp;PAST det:art|a n|giraffe coord|and det:art|a n|elephant . %gra: 1|2|SUBJ 2|0|ROOT 3|4|DET 4|2|OBJ 5|4|CONJ 6|7|DET 7|5|COORD 8|2|PUNCT *CHI: &lt;that&gt; [/] (.) that (i)s it . [+ bch] %mor: pro:dem|that cop|be&amp;3S pro:per|it . %gra: 1|2|SUBJ 2|0|ROOT 3|2|PRED 4|2|PUNCT *CHI: I saw an elephant go swimming . %mor: pro:sub|I v|see&amp;PAST det:art|a n|elephant v|go part|swim-PRESP . %gra: 1|2|SUBJ 2|0|ROOT 3|4|DET 4|5|SUBJ 5|2|COMP 6|5|OBJ 7|2|PUNCT *CHI: &lt;I saw eleph&gt; [//] I saw the &lt;g&gt; [/] giraffe and the elephant &lt;s&gt; [//] drop ball in the pool . %mor: pro:sub|I v|see&amp;PAST det:art|the n|giraffe coord|and det:art|the n|elephant n|drop n|ball prep|in det:art|the n|pool . Suppose I have files like SLI-1.txt, SLI2.txt ... SLI-10.txt. The first task is to read all the files into one file and perform below actions on it. From this data, I have to extract only statements which are prefixed or begins with *CHI:. (Note that there are some statements that extend to the next line, you should ensure that you take those into account.) Below is the list of symbols that should be filter off from each of the *CHI: statements extracted. Remove those words that have either [ as prefix or ] as suffix but retain these three symbols: [//], [/], and [*] Retain those words that have either &lt; as prefix or &gt; as suffix but these two symbols should be removed. Remove those words that have prefixes of &amp; and + Retain those words that have either ( as prefix or ) as suffix but these two symbols should be removed. Regular express…
score: -3
accepted answer: http://stackoverflow.com/a/52649107
type: AnsweredQuestion
has title: Filtering a text file for a given conditions and symbols
downvote count: 3
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52649107
favorite count: 0

http://stackoverflow.com/comment/92373572
type: AnswerComment
comment on: http://stackoverflow.com/a/52722075
has text: The error is pretty descriptive is it not? Check your indent blocks to make sure you're indenting properly.
score: 0
type: Comment

http://stackoverflow.com/q/52648147
has answer: http://stackoverflow.com/a/52664517
type: Question
tagged with: sqlalchemy
answer count: 2
accepted answer: http://stackoverflow.com/a/52664517
score: 0
has title: SQLAlchemy Double Inner Join on multiple foreign keys
has body: Please see update at bottom I have three classes. Let's call them Post, PostVersion, and Tag. (This is for an internal version control system in a web app, perhaps similar to StackOverflow, though I'm unsure of their implementation strategy). I sort of use terminology from git to understand it. These are highly simplified versions of the classes for the purposes of this question: class Post(db.Model): id = db.Column(db.Integer, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey("user.id")) author = db.relationship("User", backref="posts") head_id = db.Column(db.Integer, db.ForeignKey("post_version.id")) HEAD = db.relationship("PostVersion", foreign_keys=[head_id]) added = db.Column(db.DateTime, default=datetime.utcnow) class PostVersion(db.Model): id = db.Column(db.Integer, primary_key=True) editor_id = db.Column(db.Integer, db.ForeignKey("user.id")) editor = db.relationship("User") previous_id = db.Column(db.Integer, db.ForeignKey("post_version.id"), default=None) previous = db.relationship("PostVersion") pointer_id = db.Column(db.Integer, db.ForeignKey("post.id")) pointer = db.relationship("Post", foreign_keys=[pointer_id]) post = db.Column(db.Text) modified = db.Column(db.DateTime, default=datetime.utcnow) tag_1_id = db.Column(db.Integer, db.ForeignKey("tag.id"), default=None) tag_2_id = db.Column(db.Integer, db.ForeignKey("tag.id"), default=None) tag_3_id = db.Column(db.Integer, db.ForeignKey("tag.id"), default=None) tag_4_id = db.Column(db.Integer, db.ForeignKey("tag.id"), default=None) tag_5_id = db.Column(db.Integer, db.ForeignKey("tag.id"), default=None) tag_1 = db.relationship("Tag", foreign_keys=[tag_1_id]) tag_2 = db.relationship("Tag", foreign_keys=[tag_2_id]) tag_3 = db.relationship("Tag", foreign_keys=[tag_3_id]) tag_4 = db.relationship("Tag", foreign_keys=[tag_4_id]) tag_5 = db.relationship("Tag", foreign_keys=[tag_5_id]) class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) tag = db.Column(db.String(128)) To make a new post…
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52651171
has answer: http://stackoverflow.com/a/52651171

http://stackoverflow.com/a/52737221
has comment: http://stackoverflow.com/comment/92399188
accepted answer of: http://stackoverflow.com/q/52736914
score: 0
has body: It sounds like what you want is to create two subplots. For this you should use the subplots function from matplotlib. Your code should look something like this: from matplotlib import pyplot as plt import cv2 img = cv2.imread(f) img1 = cv2.imread('compressed_' + f) color = ('b', 'g', 'r') fig, ax = plt.subplots(2,1) for i, col in enumerate(color): histr = cv2.calcHist([img], [i], None, [256], [0, 256]) hist = cv2.calcHist([img1], [i], None, [256], [0, 256]) ax[0].plot(histr, color=col) ax[1].plot(hist, color=col) plt.xlim([0, 256]) plt.title('Original image') plt.show()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92399463
answers question: http://stackoverflow.com/q/52736914
type: Answer

http://stackoverflow.com/a/52658617
has comment: http://stackoverflow.com/comment/92290839
has comment: http://stackoverflow.com/comment/92634662
has comment: http://stackoverflow.com/comment/92634410
has comment: http://stackoverflow.com/comment/92261657
has comment: http://stackoverflow.com/comment/92634182
has comment: http://stackoverflow.com/comment/92633833
has comment: http://stackoverflow.com/comment/92634561
has body: In C, starting with Windows Vista, you can query information for a locale name via GetLocaleInfoEx. The locale information constants to query the ANSI and OEM codepages are, respectively,LOCALE_IDEFAULTANSICODEPAGE (0x1004) and LOCALE_IDEFAULTCODEPAGE (0x000B). You can enumerate all system locale names via EnumSystemLocalesEx and query the ANSI and OEM codepages for each locale in the callback. In a Python script, you can call these functions via ctypes. For example: import ctypes from ctypes import c_int from ctypes.wintypes import BOOL, DWORD, LPVOID, LPWSTR, LPARAM, WCHAR kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) CP_ACP = 0 CP_OEMCP = 1 LOCALE_NAME_USER_DEFAULT = None LOCALE_NAME_SYSTEM_DEFAULT = "!x-sys-default-locale" LOCALE_RETURN_NUMBER = 0x20000000 LOCALE_IDEFAULTCODEPAGE = 0x0000000B LOCALE_IDEFAULTANSICODEPAGE = 0x00001004 LOCALE_SENGLISHLANGUAGENAME = 0x00001001 LOCALE_SENGLISHCOUNTRYNAME = 0x00001002 LOCALE_ENUMPROCEX = ctypes.WINFUNCTYPE(BOOL, LPWSTR, # lpLocaleString DWORD, # dwFlags LPARAM) # lParam def _check_zero(result, func, args): if not result: raise ctypes.WinError(ctypes.get_last_error()) return args kernel32.EnumSystemLocalesEx.errcheck = _check_zero kernel32.EnumSystemLocalesEx.argtypes = ( LOCALE_ENUMPROCEX, # lpLocaleEnumProcEx DWORD, # dwFlags LPARAM, # lParam LPVOID) # lpReserved LCTYPE = DWORD kernel32.GetLocaleInfoEx.errcheck = _check_zero kernel32.GetLocaleInfoEx.argtypes = ( LPWSTR, # lpLocaleName, LCTYPE, # LCType, LPVOID, # lpLCData, c_int) # cchData def get_language(locale=LOCALE_NAME_SYSTEM_DEFAULT): length = kernel32.GetLocaleInfoEx(locale, LOCALE_SENGLISHLANGUAGENAME, None, 0) language = (WCHAR * length)() kernel32.GetLocaleInfoEx(locale, LOCALE_SENGLISHLANGUAGENAME, language, length) return language.value def get_country(locale=LOCALE_NAME_SYSTEM_DEFAULT): length = kernel32.GetLocaleInfoEx(locale, LOCALE_SENGLISHCOUNTRYNAME, None, 0) country = (WCHAR * length)() kernel32.GetLocaleInfoEx(locale, LOCALE_SENGLISHC…
has comment: http://stackoverflow.com/comment/92290659
has comment: http://stackoverflow.com/comment/92632874
upvote count: 4
answers question: http://stackoverflow.com/q/52654470
has comment: http://stackoverflow.com/comment/94123308
has comment: http://stackoverflow.com/comment/92266453
has comment: http://stackoverflow.com/comment/92634299
downvote count: 0
has comment: http://stackoverflow.com/comment/92565403
score: 4
has comment: http://stackoverflow.com/comment/92565386
type: Answer

http://stackoverflow.com/a/52594281
has body: I'm not sure that the code you've posted in this comment is correct, but it is possible to fill the dictionary directly inside the loop d = {} for i in range(len(vertices)): d[i] = [] for j in edges: d[i].append((j[0], j[1]))
score: 0
answers question: http://stackoverflow.com/q/52593764
type: Answer

http://stackoverflow.com/q/52660176
tagged with: setup.py
type: UnansweredQuestion
tagged with: python
has title: Add custom build steps to bdist
answer count: 0
has body: It's possible to add build steps to sdist using the cmdclass argument to setup, E.g., # ./setup.py from setuptools import setup from setuptools.command.sdist import sdist class CustomSdistCommand(sdist): def run(self): # Do some preprocessing... super().run() setup( # ... cmdclass={ 'sdist': CustomSdistCommand, } ) Is it possible to do the same thing when using bdist?
score: 1
upvote count: 1
type: Question
tagged with: python-3.6
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/76487180
downvote count: 0
answers question: http://stackoverflow.com/q/52676020
type: Answer
upvote count: 1
has body: I had this same problem when loading thousands of images. Apparently, some files were not valid images but had the correct file extensions. Perhaps an error during saving? I fixed this by wrapping the load function in a try-catch block, printing the offending files' names and proceeding with the script. # Process the images for image_path in image_paths: """ try-catch block to handle errors in processing individual images. """ try: process_image(image_path, pass_folder, reject_folder) except cv2.error as e: print(f"Error processing image {image_path.name}: {str(e)}")
score: 1

http://stackoverflow.com/comment/92168771
type: Comment
type: QuestionComment
score: 2
has text: Can you post some code for what you've tried so far?
comment on: http://stackoverflow.com/q/52617318

http://stackoverflow.com/a/52759370
has comment: http://stackoverflow.com/comment/117290951
type: Answer
answers question: http://stackoverflow.com/q/52698502
score: 4
has body: Finally, got the custom credentials to work with custom scripting. Short guide how to achieve this. Once the INPUT CONFIGURATION and INJECTOR CONFIGURATION are defined as given above, save it. From Settings, go to CREDENTIALS. Select, +ADD. Give a new name for the CREDENTIALS. Click on the look-up in CREDENTIAL TYPE. You should see the credential saved in the previous step. Now, the interesting bit. The Username and Password that were given as label in INPUT CONFIGURATION gets activated and is now available to accept field values. Specify the appropriate values and save it. This completes the credential part and was the vital piece of information that I missed. Under inventory, sources, the custom script can be selected and the credentials can be looked up. Here, the credentials saved in step 3 will be available. When the custom script is synced, Python script should be able to get the environment variables without any issues.
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/52633122
upvote count: 2
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/92212036
has comment: http://stackoverflow.com/comment/92211938
has comment: http://stackoverflow.com/comment/92199509
has answer: http://stackoverflow.com/a/52672525
has comment: http://stackoverflow.com/comment/92211493
favorite count: 0
possible better answer: http://stackoverflow.com/a/52633199
has title: Apply generic tranformation to numpy array
tagged with: python
has comment: http://stackoverflow.com/comment/92211860
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92200092
has body: Is there easy way to apply generic transformation to numpy array? like FOR EXAMPLE this transposition def T(x,y): return (y, x) # just an example ar = np.array([ [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], ]) ar.transform(T) ar == np.array([ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], ]) https://en.wikipedia.org/wiki/Transformation_(function)
has comment: http://stackoverflow.com/comment/92200824
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52633199
accepted answer: http://stackoverflow.com/a/52672525
type: Question

http://stackoverflow.com/q/52595684
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92128121
has body: I have my python logger set to debug, but it still prints out info messages: import logging from logging.config import fileConfig fileConfig('./log/logging_config_serial.ini') logger = logging.getLogger() logger.debug("debug") 2018-10-01 09:58:43,161 root DEBUG debug logger.info("info") 2018-10-01 09:58:50,997 root INFO info logger.getEffectiveLevel() Out[12]: 10 Looks like it set to debug level on the output (10=DEBUG, 20=INFO) Here is my config file: [loggers] keys=root [handlers] keys=stream_handler,fileHandler [formatters] keys=formatter [logger_root] level=DEBUG handlers=stream_handler,fileHandler [handler_stream_handler] class=StreamHandler level=DEBUG formatter=formatter args=(sys.stderr,) [handler_fileHandler] class=FileHandler level=DEBUG formatter=formatter args=("./log/l5e5_get_header_info_serial_R3.log",) [formatter_formatter] format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
tagged with: python
has title: Why does my python logger still print out messages from higher logging levels when set to DEBUG?
type: AnsweredQuestion
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/8162419
has comment: http://stackoverflow.com/comment/92126159
tagged with: logging
type: Question
tagged with: debugging
has answer: http://stackoverflow.com/a/52595735
accepted answer: http://stackoverflow.com/a/52595735

http://stackoverflow.com/q/52691873
upvote count: 2
tagged with: piecewise
type: Question
tagged with: gurobi
has answer: http://stackoverflow.com/a/61630444
tagged with: optimization
has body: I am trying to implement a piecewise-linear objective in a gurobi optimization problem in python. When trying to get familiar with this method using the example from the gurobi web-site (http://examples.gurobi.com/production-scheduling/) I got stuck and could not really solve the issue myself for several days. Now I hope that someone here can show me, where my interpretation is wrong. The mentioned example optimizes the profit from the production of several goods with limited production capacity, especially a limited amount of working hours of the staff. However, the latter constraint is not hard, but, for some bonus payment, the possible work-hours can be expanded (this is the piecewise-linear function). In the general problem formulation, the problem looks like this: profit = revenue−cost = ∑r(i)x(i)−cost(t) , where r depicts the specific revenues for good “i" and x the share of this good, while the cost term provides potential extra cost for overtime. However, in the actual code, the objective misses the cost term, at least according to my understanding: # Set objective m.setObjective( quicksum(revenue[i]*x[i] for i in range(n)), GRB.MAXIMIZE) I suspect that this is somehow introduced/ accounted for by the Piecewise-linear objective, but unfortunately, I just don’t get how. # Set piecewise linear objective nPts = 101 ti = [] costi = [] lb = 0 ub = maxhours; for i in range(nPts): ti.append(lb + (ub - lb) * i / (nPts - 1)) costi.append(-cost(ti[i], limithours, penalty)) m.setPWLObj(t, ti, costi) m.optimize() Are PWLObj always substracted from the main objective? Is there a way to e.g. multiply the PWLObj to the main objective function? I hope that I not just missed some trivial point (I am still pretty new to programming and optimizing alike). Thanks a lot for your time and support!
score: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92323892
has comment: http://stackoverflow.com/comment/92327433
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Piecewise-Linear Function in Gurobi, understanding the example

http://stackoverflow.com/a/52657660
has body: The problem is the width of a japanese character is a little bit wider than a English character and also the space.' ' There are solutions for this situation. You just need to calculate the width of these two kinds of language. columns = ["通常残業時間", "bbbbbbbbb", "tttt"] for i in column: print('|'.join(list(i))) You could get some things like that. 通|常|残|業|時|間 b|b|b|b|b|b|b|b|b t|t|t|t You could use the | to find the relationship of width. Here I think, it nearly looks like that 5 Japanese equal 9 English character(Don't forget the minus the |.) When you get the width relationship. Then I think you might know how to calculate the length they should fit. Sorry for above wrong or misleading advice. I realized you can't make it align unless you find a different width of space to fit different language chars. But I think I might found some relative question about this and some useful packge. Display width of unicode strings in Python [duplicate] kitchen.text.display.textual_width It just for python2.7 sadly...
answers question: http://stackoverflow.com/q/52657360
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/92248808

http://stackoverflow.com/q/52727590
accepted answer: http://stackoverflow.com/a/52727759
type: Question
has body: choice="y" again="y" coin=0 credit=0 allowed=[0,10,20,50,100,200] def money_insert(): global again global coin global credit global allowed while again=="y": try: coin=int(input("insert coin")) except: print("thats not a coin") while coin not in allowed: print("invalid coin") coin = 0 credit+=coin again=input("another coin y/n?") money_insert() print("you have",credit,"p") print("") print("**********") print("**1 coke 100p**") print("*2 haribo 100p*") print("*3 galaxy 100p*") print("**4 mars 100p**") print("*5 crisps 50p*") selection=int(input("what would you like? 1-5")) while choice=="y": if selection==1: if credit&gt;99: print("Here's your coke") credit-=100 else: print("not enough credit") money_insert() The last bit keeps displaying not enough credit continuously and I don’t know what to do Sorry if this is a really dumb question I’m really new to python
answer count: 1
has comment: http://stackoverflow.com/comment/92380702
has comment: http://stackoverflow.com/comment/92380499
tagged with: python
has answer: http://stackoverflow.com/a/52727759
has title: Can’t manage to get this to work. Keep getting a repetition of not enough credit
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/92380794
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92380732
has comment: http://stackoverflow.com/comment/92380847

http://stackoverflow.com/comment/92288787
score: 0
comment on: http://stackoverflow.com/q/52680031
type: Comment
type: QuestionComment
has text: it looks like after changing the encoding to utf-8, i did not get the BOM. Thank you

http://stackoverflow.com/a/52730553
has comment: http://stackoverflow.com/comment/92566156
answers question: http://stackoverflow.com/q/52686426
type: Answer
upvote count: 1
has body: Clicking in the gutter to set a breakpoint in another file should work. Make sure the code is actually being executed and that you are running the latest version of the extension. As for setting arguments, see the debugging docs and specifically the section on args for your launch.json.
score: 1
downvote count: 0

http://stackoverflow.com/q/52735775
type: Question
score: 1
has comment: http://stackoverflow.com/comment/92396346
has title: I want to be able to find a specific piece of data using the date
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52736214
answer count: 3
has body: This is a dictionary for some data. When I print it, it prints out in two distinct columns. I have looked on here for how to search through it and find a specific piece of data but It is not making any sense to me. If you could tell me how I might search through this (using the date) and then print out the data, that would be greatly appreciated. rainfall = { '01/08/2014':1.0, '21/01/2015':0.20, '22/01/2015':0.10, '23/01/2015':1.00, '24/01/2015':0.30, '25/01/2015':0.40, '26/01/2015':0.75, '27/01/2015':0.20, '28/01/2015':1.00, '29/01/2015':0.20, '30/01/2015':0.20, '31/01/2015':0.30, } for k, v in rainfall.items(): print(f'{k:&lt;4} - {v}') def searching_for_data(): whatdata=input("What date would you like to find (format: DD/MM/YYYY)") if whatdata in rainfall: print(find(whatdata)) finddata=input("Would you like to find a specific piece of data?") if finddata == "Yes": searching_for_data()
tagged with: search
accepted answer: http://stackoverflow.com/a/52736214
possible better answer: http://stackoverflow.com/a/52735811
has answer: http://stackoverflow.com/a/52735811
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52736292

http://stackoverflow.com/q/52744816
upvote count: 1
type: Question
score: 1
has title: wikicfp.xml parser python 3
has comment: http://stackoverflow.com/comment/92414611
tagged with: xml-parsing
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52746157
favorite count: 0
has comment: http://stackoverflow.com/comment/92414630
has comment: http://stackoverflow.com/comment/92414651
has comment: http://stackoverflow.com/comment/92414379
tagged with: python
has body: I am trying to parse the wikicfp.v1.2008.xml and wikicfp.v1.2009.xml and wikicfp.v1.2010.xml. The three available versions in the link below. https://github.com/creswick/wikicfp-parser/tree/master/data I tried with XML.etree.ElementTree and with beautifulsoup, but I got a lot of encoding errors like not well-formed (invalid token): line 949, column 40 UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 63563: character maps to undefined> I couldn't progress because of the errors. I aim to parse each row and save it in a SQL script file or CSV file for later usage. from bs4 import BeautifulSoup out_file = open("final.sql","w") out_file.write("--DROP TABLE event1;\n") out_file.write("CREATE TABLE event1 (eventid int, fullname TEXT, location TEXT, begindate TINYTEXT , finishdate TINYTEXT , weblink TEXT, info TEXT, PRIMARY KEY (eventid));\n") out_file.close() infile = open("wikicfp.v1.2009.xml",encoding='utf-8-sig') contents = infile.read() soup = BeautifulSoup(contents) rows = soup.find_all('row') c = 0 for count in rows: tempsoup = rows[c] try: ei = tempsoup.findAll("field", {"name":"eventid"}) if not ei[0].contents[0].strip(): ei = "No info" eventid = ei[0].contents[0].strip() except Exception: eventid = 0 try: fn = tempsoup.findAll("field", {"name":"fullname"}) s = fn[0].contents[0].strip() fullname = s.decode('utf-8') fullname = fullname.replace("'","_") except Exception: fullname = "No info" try: l = tempsoup.findAll("field", {"name":"location"}) s = l[0].contents[0].strip() location = s.decode('utf-8') location = location.replace("'","_") except Exception: location = "No info" try: bd = tempsoup.findAll("field", {"name":"begindate"}) s = bd[0].contents[0].strip() begindate = s.decode('utf-8') except Exception: begindate = "No info" try: fd = tempsoup.findAll("field", {"name":"finishdate"}) s = fd[0].contents[0].strip() finishdate = s.decode('utf-8') except Exception: finishdate = "No info" try: wl = tempsoup.findAll("field", {"name":"weblink"})…
has comment: http://stackoverflow.com/comment/92418679
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/92375601
type: AnswerComment
type: Comment
has text: Seems this can work well for me. I have just one question, does it work with the same principle as a class or do I have to declare everything in the function?
comment on: http://stackoverflow.com/a/52725016
score: 0

http://stackoverflow.com/a/52628902
has body: You cannot access django form's fields by index, you must use key. So you need to do something like this: {{ form2.myField }} {{ form2.myField2 }} Trying to access form fields by index will not work: {{ form2[1] }} // Incorrect syntax {{ form2.1 }} // correct syntax but you can access fields using index, must use key.
score: 0
accepted answer of: http://stackoverflow.com/q/52628689
type: Answer
answers question: http://stackoverflow.com/q/52628689
type: AcceptedAnswer

http://stackoverflow.com/a/52597027
has comment: http://stackoverflow.com/comment/92128625
answers question: http://stackoverflow.com/q/52596921
score: 7
upvote count: 7
downvote count: 0
type: Answer
has body: Both loops are broken. The first one only happens to work due to the very specific coincidence that test is exactly two characters long, and so can be unpacked into two variables x and y. To iterate over a dict's keys and values, write: for k,v in d.items(): ... If you just want the keys you can do: for k in d: ... In detail, when you loop over a dict it iterates over the keys. for x,y in test_dict The dict has exactly one key, "ab". So on the first and only iteration, it assigns that string to x and y as if you'd written: x,y = "ab" As it happens, this is a valid unpacking. Two variables on the left, a two-item container on the right. x becomes "a" and y becomes "b". If test were longer or shorter the first loop would also crash with either "need more than N values to unpack" or "too many values to unpack". Why is the string unpacked in 1 scenario but not unpacked in the other? The second loop iterates over the string "ab" directly. When you iterate over a string it breaks the string into single-character strings. The first iteration is "a" and the second is "b". On that first iteration, it tries to do: x,y = "a" This assignment fails with "need more than 1 value to unpack" because there are two variables on the left and only one character on the right.

http://stackoverflow.com/q/52711386
has answer: http://stackoverflow.com/a/59979246
upvote count: 5
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/30629031
has comment: http://stackoverflow.com/comment/92348943
has comment: http://stackoverflow.com/comment/92348973
downvote count: 0
has title: How to properly use pandas groupby with apply function for side effects? (First group applied twice)
tagged with: dataframe
favorite count: 0
tagged with: apply
type: Question
score: 5
has comment: http://stackoverflow.com/comment/92348930
linked to: http://stackoverflow.com/q/21390035
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
tagged with: python
has body: I am using pandas to groupby certain columns in a dataframe and apply a custom function to these groups. The applied function makes use of side effects and acts on global data objects within the function. A documented caveat with pandas, groupby and apply is that by design it applies the function called twice on the first group to decide whether it can take a fast or slow code path. This is documented here: http://pandas.pydata.org/pandas-docs/stable/groupby.html#flexible-apply Demonstrated here: In [144]: d = pd.DataFrame({"a":["x", "y"], "b":[1,2]}) In [145]: def identity(df): .....: print(df) .....: return df .....: In [146]: d.groupby("a").apply(identity) a b 0 x 1 a b 0 x 1 a b 1 y 2 Out[146]: a b 0 x 1 1 y 2 Mentioned in a few other stackoverflow posts here: Python pandas groupby object apply method duplicates first group Is Pandas 0.16.1 groupby().apply() method applying function more than once to the same group? Mentioned on GitHub here: https://github.com/pandas-dev/pandas/issues/7739 https://github.com/pandas-dev/pandas/issues/19167 This means that my side effect is called twice on the first group and results in unwanted changes. My question is how do I use pandas, groupby and apply without the side effects being applied twice on the first group (or any group for that matter) and guarantee it is only called once on every group? I was thinking of created a dummy/fake group at the top of the DataFrame but I wanted to extend my question to the stackoverflow community for a better solution and for the benefit of others. Thank you for your help. EDIT: As requested in the comments, a few more details on the custom function and side effects. The use of a custom function with side effects makes use of a global dictionary at the beginning and end of the function. It retrieves data with a key and applies those values to rows, at the end of the function, the updated values get updated to the global dictionary so the new values are reflected in the next iteration. The…

http://stackoverflow.com/q/52589124
has title: Python/Selenium: How to automatic press to button "Next" while its on the screen?
tagged with: python
possible better answer: http://stackoverflow.com/a/52589611
score: 0
has answer: http://stackoverflow.com/a/52589611
tagged with: selenium
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52589437
answer count: 2
has body: I'm writing autotest on Selenium, using python. After call a window, tooltip displayed on the screen. There are 27 steps, to complete tutorial (27 tooltips). Tooltips displayed one by one. There are the "Next" button on every tooltip (got same xpath for every step). How can I make selenium click on the "Next" button, while its displayed on the screen? step1 = driver.find_element_by_xpath('/html/body/div[2]/div/button') step1.click() print "Step 1 = OK" step2 = driver.find_element_by_xpath('/html/body/div[2]/div/button') step2.click() print "Step 2 = OK"
accepted answer: http://stackoverflow.com/a/52589437

http://stackoverflow.com/comment/92124905
score: 0
comment on: http://stackoverflow.com/a/52595004
type: AnswerComment
has text: I still got the same output that has `.0`. The code is correct but I am not getting the correct output.
type: Comment

http://stackoverflow.com/comment/92325024
has text: good, but in some cases when I have many plots, it prints all the title together and then the plots, maybe its my machine, but otherwise good
comment on: http://stackoverflow.com/a/52699231
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92205778
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52619696
has text: @wchlm: No multi-line formatting in comments. Even if you get a line break into the comment box, it won't be a line break in the resulting comment. You can't write complicated code snippets in a comment. Try ideone or pastebin or something.
score: 0

http://stackoverflow.com/comment/92242891
score: 0
comment on: http://stackoverflow.com/q/52655573
type: Comment
type: QuestionComment
has text: @JoshuaNixon, viewing the traceback seemed like a start but all I can get out of it is something like ```AttributeError("'Dummy' object has no attribute 'name'",)```. But here Dummy is the Type of the variable, not its name.

http://stackoverflow.com/comment/92291433
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52681426
score: 0
has text: General advice: Python indent is 4 spaces, not 2, and certainly not 2 in half of the program, and 4 in the other half. Consistent code formatting matters.

http://stackoverflow.com/q/52701133
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/54215554
tagged with: orange
has title: How do you select attributes by name in Orange
answer count: 1
downvote count: 0
has body: I have this file with a lot of attributes I want to use only a few of the attributes. How can I select for example three attributes with specific names? The documentation only talks about random sampling of attributes and list indexing of the attributes that you want. list_of_attr=[Orange.data.variable.ContinuousVariable(name="home_ppg_pre_game")] new_domain = Orange.data.Domain(list_of_attr, data.domain.class_var) new_data = Orange.data.Table(new_domain, data) I tried this but the new_data only had missing values.

http://stackoverflow.com/comment/92324985
type: QuestionComment
comment on: http://stackoverflow.com/q/52698078
has text: I wanted to sort the Datarames (which are rowing results) to year and event. Each DataFrame is a specific event at a regatta in a specific year.
score: 0
type: Comment

http://stackoverflow.com/comment/92345857
has text: "SyntaxError - bad input" isn't a kind of SyntaxError Python actually issues, as far as I'm aware, and the code you've posted displays no visible errors. Could you include the complete, exact error message in your question, including stack trace?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52709762

http://stackoverflow.com/q/52652858
score: 0
answer count: 3
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92237499
has body: >Hello guys. I am making a program for my french lesson. My goal here is to make a word bank. My programs goal is to see if i added an 'i' word, or to add an 'i' word. I tried wordBank.append() but it didn't update the list. How can i update the word list? Code is below. wordBank = ["Apres", "Bureau", "Dejenuer", "Deime", "Dimanche", "jeudi", "Lundi", "Mardi", "Matin", "Midi",] def hoşGeldin(): inp1 = input("Fransızca kelime deposuna hoşgeldin!\nBaşlamak için 'Başla' yaz.\n") if inp1 == "Başla": istekNe() elif inp1 != "Başla": hoşGeldin() def depoCheck(): kelimeCheck = input("Bakmak istediğiniz kelimeyi yaz.\n") if kelimeCheck in wordBank: print("%s kelime listesinde" % kelimeCheck) def istekNe(): inp2 = input("Kelime aramak için Arat, Kelime eklemek için Yeni yaz.\n") if inp2 == "Arat": depoCheck() elif inp2 == "Yeni": yeniSözcük() elif inp2 != "Başla" or "Arat": istekNe() def yeniSözcük(): inp3 = input("Eklemek istediğiniz kelimeyi yaz.\n") wordBank.append("%s" % inp3) inp1 = input("Fransızca kelime deposuna hoşgeldin!\nBaşlamak için 'Başla' yaz.\n") if inp1 == "Başla": istekNe() elif inp1 != "Başla": hoşGeldin()
has answer: http://stackoverflow.com/a/52653154
type: AnsweredQuestion
has title: How to update a list
has answer: http://stackoverflow.com/a/52692727
has comment: http://stackoverflow.com/comment/92284758
type: Question
has comment: http://stackoverflow.com/comment/92237373
has comment: http://stackoverflow.com/comment/92240323
accepted answer: http://stackoverflow.com/a/52692727
possible better answer: http://stackoverflow.com/a/52653330
has answer: http://stackoverflow.com/a/52653330

http://stackoverflow.com/a/52753815
has comment: http://stackoverflow.com/comment/92794376
answers question: http://stackoverflow.com/q/52733625
downvote count: 0
has body: Let us start from scratch by creating a toy module called my_module. First, we need to create a model. The file addons/my_module/models/models.py contains: from odoo import api, fields, models, tools, _ class Books(models.Model): _name = 'my_module.books' title = fields.Char(string='Title') author = fields.Char(string='Author') Now, we are in position to create menus, actions and views. The file addons/my_module/views/views.xml contains: <?xml version="1.0" encoding="utf-8"?> <menuitem name="My top menu" id="my_module.menu_root"/> <menuitem name="My left-side menu" id="my_module.menu_left" parent="my_module.menu_root"/> My books - List view my_module.books My books - Form view my_module.books My Books - Window action my_module.books tree,form <menuitem name="Books" id="my_module.menu_books" parent="my_module.menu_left" action="my_module.books_action_window" sequence="6" /> Then, we need a manifesto. The file addons/my_module/__manifest__.py contains: { 'name': "my_module", 'summary': "Answer to Stack Overflow Question 52733625", 'description': "Answer to Stack Overflow Question 52733625", 'author': "Adán Cortés Medina", 'website': "http://www.linkedin.com/in/1acme", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/9.0/openerp/addons/base/module/module_data.xml # for the full list 'category': 'Uncategorized', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['website'], # always loaded 'data': [ 'views/views.xml', #'security/ir.model.access.csv', ], # only loaded in demonstration mode 'demo': [ #'demo/demo.xml', ], } At this point, you most likely want to create a new database and load the module. There will be a menu on top named My top menu, then there will be a label on the left reading My left-side menu and beneath there will be a menu reading Books which, when you click on it, the list view for the books model will be shown. Also, when you click on the Create button, you wil…
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/93046858
score: 1

http://stackoverflow.com/a/52708611
answers question: http://stackoverflow.com/q/52708568
type: Answer
has body: You're missing the object level in your indexing: messagejson['Records'][0]['sql']['object']['key'] # src-1.txt
downvote count: 0
score: 1
upvote count: 1

inheritance
tags question: http://stackoverflow.com/q/52658210
tags question: http://stackoverflow.com/q/52619696
tags question: http://stackoverflow.com/q/52696551
tag name: inheritance
tags question: http://stackoverflow.com/q/52623819
tags question: http://stackoverflow.com/q/52675152
tags question: http://stackoverflow.com/q/52635152
type: Tag
tags question: http://stackoverflow.com/q/52694555
tags question: http://stackoverflow.com/q/52590892
tags question: http://stackoverflow.com/q/52745859
tags question: http://stackoverflow.com/q/52665981
tags question: http://stackoverflow.com/q/52642360
tags question: http://stackoverflow.com/q/52684947

http://stackoverflow.com/q/52602226
has body: When I run docker-compose up --build I get the following error: web_1 | /opt/conda/bin/python3: can't find '__main__' module in 'glm-plotter' glm-plotter/glm-plotter.py: ... if __name__ == "__main__": app.secret_key = 'B0er23j/4yX R~XHH!jmN]LWX/,?Rh' app.run() Dockerfile FROM continuumio/miniconda3 RUN apt-get update &amp;&amp; apt-get install -y \ libpq-dev \ build-essential RUN apt-get install -y python3 RUN apt-get install -y python3-pip ADD . /code WORKDIR /code RUN pip3 install -r requirements.txt RUN cd glm-plotter RUN ls glm-plotter CMD ["python3", "glm-plotter"]
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52602309
has comment: http://stackoverflow.com/comment/92138640
has title: Docker python3: can't find '__main__' module
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/52602309
tagged with: docker
type: Question
type: AnsweredQuestion
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/92229515
comment on: http://stackoverflow.com/a/52629140
type: Comment
has text: See edit with adjustment to *outliers* build inside loop and using a numpy-ified version of `haversine()`.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52588822
has body: I have written a code which plays a video in two different frames using two threads.The code looks fine but the cv2.imshow method does not display the videos playing. The video player opens and closes immediately. Help required in resolving the issue. import threading import cv2 def print_cube(num): """ function to print cube of given num """ print("start") print(num) cv2.imshow("video1",num) print("end") cv2.destroyAllWindows() def print_square(num): """ function to print square of given num """ print("start1") print(num) cv2.imshow("video2",num) print("end2") if __name__ == "__main__": # creating thread cap = cv2.VideoCapture("C:\\Users\shakarna\Desktop\video.mp4") while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) t1 = threading.Thread(target=print_square, args=(frame,)) t2 = threading.Thread(target=print_cube, args=(gray,)) # starting thread 1 t1.start() # starting thread 2 t2.start() # wait until thread 1 is completely executed t1.join() # wait until thread 2 is completely executed t2.join() if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
tagged with: video-processing
downvote count: 2
tagged with: multithreading
has comment: http://stackoverflow.com/comment/92150704
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52589053
type: Question
has comment: http://stackoverflow.com/comment/92174467
upvote count: 0
has comment: http://stackoverflow.com/comment/92174618
answer count: 1
accepted answer: http://stackoverflow.com/a/52589053
score: -2
favorite count: 0
has title: Python Video Processing

http://stackoverflow.com/a/52728780
accepted answer of: http://stackoverflow.com/q/52728462
has body: First of all a QGraphicsItem is not a QWidget, so it has those events and does not handle them directly, that's what QGraphicsView and QGraphicsScene do. For example you say that you want to have a moveable rectangle because that task is simple is QGraphicsView, it is not necessary to overwrite: from PyQt5 import QtCore, QtWidgets class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) scene = QtWidgets.QGraphicsScene(self) view = QtWidgets.QGraphicsView(scene) self.setCentralWidget(view) rect_item = QtWidgets.QGraphicsRectItem(QtCore.QRectF(0, 0, 100, 100)) rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True) scene.addItem(rect_item) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.resize(640, 480) w.show() sys.exit(app.exec_()) If you want to change the way you paint the rectangle you must overwrite the paint() method as shown below: from PyQt5 import QtCore, QtGui, QtWidgets class RectItem(QtWidgets.QGraphicsRectItem): def paint(self, painter, option, widget=None): super(RectItem, self).paint(painter, option, widget) painter.save() painter.setRenderHint(QtGui.QPainter.Antialiasing) painter.setBrush(QtCore.Qt.red) painter.drawEllipse(option.rect) painter.restore() class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) scene = QtWidgets.QGraphicsScene(self) view = QtWidgets.QGraphicsView(scene) self.setCentralWidget(view) rect_item = RectItem(QtCore.QRectF(0, 0, 100, 100)) rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True) scene.addItem(rect_item) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.resize(640, 480) w.show() sys.exit(app.exec_()) Update: from PyQt5 import QtCore, QtGui, QtWidgets class GraphicsScene(QtWidgets.QGraphicsScene): def __init__(self, parent=None): super(GraphicsScene, self).__init__(QtCore.QRectF(-500, -500, 10…
upvote count: 10
has comment: http://stackoverflow.com/comment/92383085
score: 10
has comment: http://stackoverflow.com/comment/92383554
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52728462

http://stackoverflow.com/q/52600262
type: Question
has body: I have completed the steps provided by Google to implement push notifications using the Drive API. Everything goes as described except I do not receive any notifications from Google whenever a change occurs (listed as Step 4 below). Below is a summary of the steps I followed and the results at each stage: Step 1 (Success): Verify that you own the domain I went to Search Console as directed and successfully verified the site. Step 2 (Success): Register your domain I visited the Domain Verification page and added my domain in the API Console. Google API Console updated to show the list with my desired domain. I have a valid SSL certificate from GoDaddy for my domain and have verified that as well. Step 3 (Success): Created my notification channel Using the python SDK, I created the channel and got back a response from Google. The python code below shows how I did this. Note: The address included in my request directs Google to send notifications to my Flask website that I am hosting in Google's App Engine. I am showing the domain as my_domain.com here for privacy as I am in the process of bringing up the site. channel_id = str(uuid.uuid4()) body = { 'kind': 'api#channel', 'id': channel_id, 'type': 'web_hook', 'address': "https://my_domain.com/notifications" } try: start_page_token = service.changes().getStartPageToken().execute().get('startPageToken'); print(service.changes().watch(pageToken=start_page_token, body=body).execute()) except Exception as e: print('Exception: {}'.format(e)) And here is the response from Google: {u'resourceId': u'vTMwJWl7a23Af1LK1TpJZ38eO_0', u'kind': u'api#channel', u'expiration': u'1538433975000', u'id': u'dce14225-95c8-42a7-9945-4fed1604c848', u'resourceUri': u'https://www.googleapis.com/drive/v3/changes?alt=json&amp;includeCorpusRemovals=false&amp;includeRemoved=true&amp;includeTeamDriveItems=false&amp;pageSize=100&amp;pageToken=4919&amp;restrictToMyDrive=false&amp;spaces=drive&amp;supportsTeamDrives=false&amp;alt=json'} Step 4 (Failed)…
has comment: http://stackoverflow.com/comment/92239955
downvote count: 0
tagged with: flask
has answer: http://stackoverflow.com/a/52624001
has comment: http://stackoverflow.com/comment/92163935
tagged with: push-notification
answer count: 1
has title: How to successfully receive Google Drive v3 Push Notifications using python?
has comment: http://stackoverflow.com/comment/107514333
has comment: http://stackoverflow.com/comment/107601290
favorite count: 0
tagged with: google-drive-api
type: UnansweredQuestion
tagged with: google-app-engine
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/92154851

http://stackoverflow.com/a/52747171
has body: You cannot install python3-setuptools with pip — there is no such pip-installable package: https://pypi.org/project/python3-setuptools/ — error 404. In python ecosystem the package is called simply setuptools. python3-setuptools is the name of the package in Debian/Ubuntu package system: https://packages.debian.org/search?keywords=python3-setuptools&amp;searchon=names&amp;suite=stable&amp;section=all https://packages.ubuntu.com/search?keywords=python3-setuptools&amp;searchon=names&amp;suite=bionic&amp;section=all So either you install it with apt install python3-setuptools or pip3 install setuptools.
has comment: http://stackoverflow.com/comment/92437330
answers question: http://stackoverflow.com/q/52743272
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/a/52731458
type: Answer
has comment: http://stackoverflow.com/comment/92388164
has comment: http://stackoverflow.com/comment/92426196
has comment: http://stackoverflow.com/comment/92426954
has comment: http://stackoverflow.com/comment/92424854
has comment: http://stackoverflow.com/comment/92388150
has comment: http://stackoverflow.com/comment/92426627
has comment: http://stackoverflow.com/comment/92497718
upvote count: 1
answers question: http://stackoverflow.com/q/52730684
has comment: http://stackoverflow.com/comment/92427110
has comment: http://stackoverflow.com/comment/92426741
has comment: http://stackoverflow.com/comment/92426673
has comment: http://stackoverflow.com/comment/92496779
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92388297
has comment: http://stackoverflow.com/comment/92388173
has body: I just changed one line near the end of the code in your question and it started working: . . . # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # Process input (events) for event in pygame.event.get(): # check for closing window if event.type == pygame.QUIT: running = False # Update all_sprites.update() # Draw / render screen.fill(GREEN) all_sprites.draw(screen) # *after* drawing everything, flip the display pygame.display.flip() # &lt;----- FIX THIS LINE pygame.quit()

http://stackoverflow.com/comment/92230386
score: 0
type: Comment
has text: @probat 6 year old machine ;) But I'm on Linux. When you're on Windows, starting up processes takes longer because Windows does no forking.
comment on: http://stackoverflow.com/a/52637805
type: AnswerComment

http://stackoverflow.com/q/52629295
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/92380201
tagged with: windows-installer
has body: I'm writing an application for a venue that will have large-scale competitions. In order to effectively manage those competitions, multiple employees need to engage with and modify a set of data in real-time, from multiple machines in the gym. I have created a Python application which accomplishes this by communicating with a MySQL server (which allows as many instances of the application as necessary to communicate with it). Is there a nice way to get MySQL server installed on a client machine along with this Python application (It only necessarily needs to end up on one machine)? Perhaps is there a way to wrap the installers together? Am I asking the right question? I have no experience with application distribution, and I'm open to all suggestions. Thanks.
accepted answer: http://stackoverflow.com/a/52727076
score: 0
has comment: http://stackoverflow.com/comment/92377459
answer count: 1
has comment: http://stackoverflow.com/comment/92378227
has title: Is it possible to install MySQL Server along with standalone client-side software?
has comment: http://stackoverflow.com/comment/92388672
tagged with: software-distribution
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52727076

http://stackoverflow.com/comment/92261032
comment on: http://stackoverflow.com/q/52664884
type: Comment
score: 1
has text: you could just use the input string as the filename for your flipped image.
type: QuestionComment

http://stackoverflow.com/q/52626888
has comment: http://stackoverflow.com/comment/92187880
tagged with: pyqt
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/92187404
has comment: http://stackoverflow.com/comment/92187490
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52627793
has comment: http://stackoverflow.com/comment/92187192
accepted answer: http://stackoverflow.com/a/52627793
tagged with: pyqt5
has body: I'm a PyQt5 newbie. I've written a simple CLI script that makes a GET request, prints the result, then exits with an error: "QWaitCondition: Destroyed while threads are still waiting" What am I doing wrong? My code is shown below: from PyQt5.QtCore import QCoreApplication, QObject, QUrl from PyQt5.QtNetwork import QNetworkRequest, QNetworkAccessManager, QNetworkReply import sys class MainWindow(QObject): def __init__(self): super().__init__() target = "http://pyqt.sourceforge.net/Docs/PyQt5/index.html" request = QNetworkRequest(QUrl(target)) self.networkAccessManager = QNetworkAccessManager() #self.networkAccessManager.finished[QNetworkReply].connect(self.headsUp) self.networkAccessManager.finished.connect(self.onFinished) self.networkAccessManager.get(request) def onFinished(self, response): #response is an object of type QNetworkReply error = response.error() if (error == QNetworkReply.NoError): result = response.readAll() print(response.header(QNetworkRequest.ContentTypeHeader)) print(response.header(QNetworkRequest.LastModifiedHeader)) print(response.header(QNetworkRequest.ContentLengthHeader)) else: print("There was an error. "+response.errorString()) self.windUp(response) def windUp(self, replyObject): #replyObject is an object of type QNetworkReply print("Done") replyObject.deleteLater() QCoreApplication.quit() if __name__ == '__main__': qApp = QCoreApplication(sys.argv) w = MainWindow() sys.exit(qApp.exec_())
has title: QCoreApplication doesn't terminate gracefully
type: Question
has comment: http://stackoverflow.com/comment/92189043

http://stackoverflow.com/comment/92389320
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52732087
score: 0
has text: Your first `for` loop is iterating in the range [0, 101[ when it should be (as you said) [1-100], use `range(1,101)` instead of `range(101)`

dbscan
tags question: http://stackoverflow.com/q/52732600
tag name: dbscan
type: Tag

http://stackoverflow.com/q/52611672
upvote count: 1
tagged with: box2d
has title: How to use Box 2 D on google colab
score: 1
type: Question
answer count: 1
has body: I am currently trying to optimize OpenAIGym's BipedalWalker with neat. In order to use Bipedalwalker, it is necessary to install Box 2 D, but a problem arises. In order to install Box 2 d on colab, we did the following first. !apt-get install python-box2d &gt; /dev/null !pip install gym[Box_2D] import gym env = gym.make("BipedalWalker-v2") However, this caused the following error /usr/local/lib/python3.6/dist-packages/gym/envs/box2d/lunar_lander.py in &lt;module&gt;() 2 import numpy as np 3 ----&gt; 4 import Box2D 5 from Box2D.b2 import (edgeShape, circleShape, fixtureDef, polygonShape, revoluteJointDef, contactListener) 6 ModuleNotFoundError: No module named 'Box2D' Since it did not work in the earlier method, next time I put Box 2 D, I tried the following. !apt-get -qq -y install swig&gt; /dev/null !apt-get install build-essential python-dev swig python-pygame subversion &gt; /dev/null !git clone https://github.com/pybox2d/pybox2d !python pybox2d/setup.py build However, the following error also occurred with this method. Traceback (most recent call last):File "pybox2d/setup.py", line 151, in &lt;module&gt; write_init() File "pybox2d/setup.py", line 66, in write_init license_header = open(os.path.join(source_dir, 'pybox2d_license_header.txt')).read()FileNotFoundError: [Errno 2] No such file or directory: 'Box2D/pybox2d_license_header.txt' What is a good way to put Box 2d on colab?
tagged with: apt-get
downvote count: 0
has answer: http://stackoverflow.com/a/53352157
tagged with: google-colaboratory
favorite count: 0
tagged with: python
tagged with: openai-gym
type: UnansweredQuestion

http://stackoverflow.com/q/52682669
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52682791
tagged with: python
has title: How can I drop the index of a Pandas Series (pandas.core.series.Series) to return a numpy.ndarray?
downvote count: 1
type: Question
has body: I'm trying to show a confusion matrix for predicted test data (binary text classification). But I can't get y_pred to match y_test after running model.predict(). First, let's look at the test/true data: y_test = (y_test &gt; 0.5) print(y_test) print(type(y_test)) Output: 2 False 17 True 18 True ... 4980 True 4986 False 4990 True pandas.core.series.Series The missing indexes are contained in the training set. Here's what happens when we predict based on test data: y_pred = model.predict(data_test) y_pred = (y_pred &gt; 0.5) print(y_pred) print(type(y_pred)) Output: [[ True] [ True] [ True] [False] ... [ True] [ True] [ True]] numpy.ndarray Test/True data: y_test = (y_test &gt; 0.5) print(y_test) Output: 2 False 17 True 18 True ... 4980 True 4986 False 4990 True Ultimately I'm looking to build a confusion matrix, but the data isn't the same format. from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) What do you recommend? Attempts so far: y_test_np = y_test.values Output: [False True True ... True False True] Closer, but it looks like I need each item to also be an array (e.g. [[ True] [False] [ True]]). How can I align the arrays?
score: -1
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/92295460
answer count: 1
has comment: http://stackoverflow.com/comment/92293861
favorite count: 0

http://stackoverflow.com/q/52648664
accepted answer: http://stackoverflow.com/a/52648776
has title: Merging dataframes with arrays in columns
upvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52648810
has answer: http://stackoverflow.com/a/52648810
score: 1
has body: In pandas, how to merge two datasets so that arrays contained in columns concatenates ? For instance, let d1 and d2 two datasets to be merged. In my case I have around 100 relatively small dataframes to merge: &gt;&gt; d1 id seq 0 AAA (1, 2, 3, 4) 1 BBB (1, 2, 3, 4) &lt;--- &gt;&gt; d2 id seq 0 CCC (1, 2, 3, 4) 1 DDD (1, 2, 3, 4) 2 BBB (5, 6, 7) &lt;--- Now we want: &gt;&gt; df id seq AAA (1, 2, 3, 4) BBB (1, 2, 3, 4, 5, 6, 7) &lt;--- DDD (1, 2, 3, 4) CCC (1, 2, 3, 4) How to do that efficiently ? I tried merged but it seems I'm obliged to pass by the method apply which I want to avoid.
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52648776
tagged with: pandas
tagged with: python
favorite count: 0

http://stackoverflow.com/a/52936728
has comment: http://stackoverflow.com/comment/93146691
has comment: http://stackoverflow.com/comment/93585381
has comment: http://stackoverflow.com/comment/96590566
has comment: http://stackoverflow.com/comment/93171544
has comment: http://stackoverflow.com/comment/93469732
has body: I note that your first image (test1.bmp) appears to be corrupt and ImageMagick reports it has incorrect length. Your second image does not appear to be compressed with RLE8 compression and also is a palettised image, but with alpha/transparency. Your third image is palletised, non-alpha with RLE8 compression. My version of PIL can read only the second file - the first and third, which are RLE encoded cannot be read. You asked for a workaround - may I suggest pyvips which can read the files without issues: import pyvips from PIL import Image # Load troublesome file using vips, and write to a memory buffer image = pyvips.Image.new_from_file('test1.bmp') mem_img = image.write_to_memory() # Read from memory buffer into Numpy array imgnp=np.frombuffer(mem_img, dtype=np.uint8).reshape(image.height, image.width, 3) # Convert Numpy array to PIL Image and write to disk Image.fromarray(imgnp).save('result.png')
has comment: http://stackoverflow.com/comment/93470749
has comment: http://stackoverflow.com/comment/93019285
upvote count: 1
has comment: http://stackoverflow.com/comment/93149143
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/93583240
has comment: http://stackoverflow.com/comment/93473557
has comment: http://stackoverflow.com/comment/93266847
has comment: http://stackoverflow.com/comment/93501540
has comment: http://stackoverflow.com/comment/93266598
has comment: http://stackoverflow.com/comment/93245385
has comment: http://stackoverflow.com/comment/96665941
type: Answer
answers question: http://stackoverflow.com/q/52619276
has comment: http://stackoverflow.com/comment/93013276
has comment: http://stackoverflow.com/comment/92894566
has comment: http://stackoverflow.com/comment/93146410
has comment: http://stackoverflow.com/comment/96589784
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52619276
has comment: http://stackoverflow.com/comment/93508544
score: 1

http://stackoverflow.com/comment/92360774
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52717510
has text: Did you search the doc before asking ? https://docs.djangoproject.com/en/2.1/topics/db/queries/#lookups-that-span-relationships
score: 2

http://stackoverflow.com/q/52591339
has comment: http://stackoverflow.com/comment/92117512
has answer: http://stackoverflow.com/a/52591594
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/92117434
has answer: http://stackoverflow.com/a/52591510
has body: I have two lists: List_main = ['a','b','c','d','e','f','g','h'] List_sub = ['c','f','d'] I now joined these lists into: list_joined = ['a','b','c','d','e','f','g','h','c','f','d'] I want to remove the first occurrences of elements in List_sub from the joined list 'list_joined'. Final output i am looking for is to obtain a list which has the List_sub elements appended at the end.: ['a','b','e','g','h','c','f','d'] I tried an approach where i found out the index of sub_list elements from the List_main. [i for i,x in enumerate(path_stores_new) if x == value ] and then use del list_joined[index] But i think there may be a better way of doing this. Any leads? Note: List_main has unique values
has answer: http://stackoverflow.com/a/52592066
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/52591544
has comment: http://stackoverflow.com/comment/92117396
has comment: http://stackoverflow.com/comment/92117458
score: -1
has comment: http://stackoverflow.com/comment/92117588
has comment: http://stackoverflow.com/comment/92117331
has answer: http://stackoverflow.com/a/52591504
has title: Remove First occurance of an element from list python
favorite count: 0
possible better answer: http://stackoverflow.com/a/52591544
has answer: http://stackoverflow.com/a/52591626
has comment: http://stackoverflow.com/comment/92117358
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52591509
accepted answer: http://stackoverflow.com/a/52591509
has answer: http://stackoverflow.com/a/52591564

http://stackoverflow.com/comment/92211999
type: QuestionComment
has text: This question is far too broad. If you show us what you have tried so far, we can better help you. Just copy and paste your source code (as text) here and press "Ctrl + K" to have the whole code indented by 4 spaces and thus formatted just the way has to be
comment on: http://stackoverflow.com/q/52633071
score: 0
type: Comment

http://stackoverflow.com/a/54802505
has body: You should use env of clone_from. with Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd): repo = Repo.clone_from(config.url, tmpdir, branch=branch) → git.Repo.clone_from(url, repo_dir, env={"GIT_SSH_COMMAND": 'ssh -i /PATH/TO/KEY'})
upvote count: 3
has comment: http://stackoverflow.com/comment/101341181
score: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52592918

http://stackoverflow.com/comment/92387118
has text: No worries. Thanks for your help.
type: AnswerComment
comment on: http://stackoverflow.com/a/52706434
score: 0
type: Comment

http://stackoverflow.com/a/52659852
downvote count: 0
answers question: http://stackoverflow.com/q/52659782
has body: Looks like you need findNext method. Ex: from bs4 import BeautifulSoup html = """ X1 Value of X1 """ soup = BeautifulSoup(html, "html.parser") for tag in soup.find_all("h4", text="X1"): #Find all h4 with required text. print(tag.findNext("a").text) Output: Value of X1
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/92245325
type: QuestionComment
comment on: http://stackoverflow.com/q/52657227
has text: Sure, have a look at [How do I format by code blocks?](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks). In short, use backticks for inline code and indent 4 spaces per line for longer blocks. (There are a few other methods covered in that post.)
score: 0
type: Comment

http://stackoverflow.com/a/52655770
accepted answer of: http://stackoverflow.com/q/52634073
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52634073
upvote count: 1
has body: I solved this by defining a parent class for all the classes then using a metaclass to keep a track of the names of the classes created, check for 'derived from itself' and then report any names that were reused. #!/usr/bin/python class _Object_Meta(type): _defined = set() def __init__(cls, name, bases, dct): for base in bases: if name == base.__name__: break else: if name in _Object_Meta._defined: raise RuntimeError("%s redefined" % name) _Object_Meta._defined.add(name) class Object(object): __metaclass__ = _Object_Meta class A(Object): x = 1 class B(Object): x = 2 class C(Object): x = 3 class B(B): x = 4 class C(Object): x = 5
type: AcceptedAnswer

http://stackoverflow.com/q/52705105
tagged with: discord
has title: Pymysql error with syntax and I don't understand
tagged with: bots
has comment: http://stackoverflow.com/comment/92337516
score: 0
tagged with: mysql
type: Question
tagged with: discord.py
has body: I trying to add users in to database but stuck with this error: [08/Oct/2018 14:18:01] - [O M N I A] Updated online for user: Майор пейн [08/Oct/2018 14:18:01] - [O M N I A] Updated online for user: Nikodus Exception in thread Thread-4: 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 "/root/bot/botevents.py", line 48, in counter db_cursor.execute("INSERT INTO `users` (`server_id`, `user_name`, `user_id`, `last_update_online`, `last_update`) VALUES ('{0}', '{1}', '{2}', {3}, {3})".format(server.id, member.name.replace("'", ''), member.id, time.time())) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 516, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 727, in _read_query_result result.read() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1066, in read first_packet = self.connection._read_packet() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 683, in _read_packet packet.check_error() File "/usr/local/lib/python3.5/dist-packages/pymysql/protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.5/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '397911167944622100', 1539008281.6296663, 1539008281.6296663)' at line 1") It's add some users b…
has comment: http://stackoverflow.com/comment/92337235
answer count: 1
has answer: http://stackoverflow.com/a/52705881
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52694936
has comment: http://stackoverflow.com/comment/92317058
type: UnansweredQuestion
has title: How to do Zip code matching using pandas in a vectorised manner?
tagged with: python
has comment: http://stackoverflow.com/comment/92316414
answer count: 0
has comment: http://stackoverflow.com/comment/92317843
has comment: http://stackoverflow.com/comment/92317756
has body: I have a series of containing zip codes like zip_codes = pd.Series(['10001', '1020', '98068']) Now I have to compare it against a master table containing all the US zip codes and create a a Boolean series stating if a match is found or not. zip_master = pd.DataFrame([['98292', 'Lake Ketchum'], ['98068', 'Roslyn'], ['99013', 99013]], columns=['Zip Code', 'City Name']) Is there a vectorised way to do this? I looked into series string methods here, but could not figure out if its the right thing to use. EDIT 1: As per the comments - we can use the dataframe method isin So my main initial question is answered. I would like to extend this question little further. Is it possible to partial string matching in a vectorised way. Say I have a series containing city names and I want to match it against City Name of zip master. ? I have seen string matching being used like here- But its not vectorised. Is there any efficient vectorised method for it Should I use some other technique like cacheing or data base to get this done?
type: Question
has comment: http://stackoverflow.com/comment/92316545
has comment: http://stackoverflow.com/comment/92316650
linked to: http://stackoverflow.com/q/13636848
has comment: http://stackoverflow.com/comment/92317811
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92316987
has comment: http://stackoverflow.com/comment/92316433

http://stackoverflow.com/comment/92169895
has text: I think you will have to keep clarifying. Are there any precedence issue ? Priority in the equations ? I have a solution in mind to make you add all your functions together. But you said something about add, sub, mul and div in your question. Yes, what about those ? How will it be decided if I've got to add, sub, mul or div ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52617814

jinja2
tags question: http://stackoverflow.com/q/52678355
tags question: http://stackoverflow.com/q/52663376
tags question: http://stackoverflow.com/q/52618581
tags question: http://stackoverflow.com/q/52676374
tags question: http://stackoverflow.com/q/52705784
type: Tag
tags question: http://stackoverflow.com/q/52594285
tags question: http://stackoverflow.com/q/52608052
tags question: http://stackoverflow.com/q/52683386
tags question: http://stackoverflow.com/q/52699913
tags question: http://stackoverflow.com/q/52606820
tags question: http://stackoverflow.com/q/52599124
tag name: jinja2
tags question: http://stackoverflow.com/q/52742797
tags question: http://stackoverflow.com/q/52656157
tags question: http://stackoverflow.com/q/52683831

http://stackoverflow.com/comment/92293332
comment on: http://stackoverflow.com/a/52647126
has text: Thank you that was very helpful.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52591084
has comment: http://stackoverflow.com/comment/92213800
tagged with: python
has answer: http://stackoverflow.com/a/52592754
upvote count: 3
type: UnansweredQuestion
has title: Effective scripting option to Automate MKS Integrity
tagged with: mks
type: Question
has body: I want to create one script that will open the Windows application to perform some task. Application is PTC integrity, I want to write a script that would open the items ( via unique Item ID ) and make changes in one of it's attribute's value and save it. Tasks that my script should do: 1. Open the application. 2. Open the document using ID. 3. Open the Item via provided ID. 4. Assign a new value to the attribute provided by the script. I would like to know which scripting language should I use to get the above task done. Can it be done via VBA or Perl or Python etc. Since I'm new I'm open for good suggestions. NOTE : I've worked on AutoIT before. So, Let me know if it can be of any use for PTC Integrity Automation.
linked to: http://stackoverflow.com/q/33168596
tagged with: mks-integrity
score: -1
tagged with: ui-automation
has answer: http://stackoverflow.com/a/55297579
has comment: http://stackoverflow.com/comment/92120186
answer count: 2
downvote count: 4
tagged with: perl
favorite count: 0

http://stackoverflow.com/comment/92271709
comment on: http://stackoverflow.com/q/52670666
score: 0
type: Comment
type: QuestionComment
has text: Thank you for clarifying between `readline()` and `readlines()`. I know you can pass a list to a method (`__init__`), I meant was that you cannot pass a list as multiple arguments. A list `[1, 2, 3, 4]` is 1 argument, this method needs 4 arguments.

http://stackoverflow.com/comment/92386723
comment on: http://stackoverflow.com/q/52730150
type: Comment
type: QuestionComment
has text: you may want to check what's being returned in requests.get(link).text
score: 0

http://stackoverflow.com/comment/92211213
comment on: http://stackoverflow.com/a/52639080
score: 0
type: AnswerComment
has text: Actually it shows the text. It was not showing because the background appears to be white and so does the text. Anyway, It is really weird.
type: Comment

http://stackoverflow.com/comment/92205996
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52636401
has text: @JohnGordon That is very false. `min(brands, key=lambda x:int(x[1]))[0]`
type: QuestionComment

http://stackoverflow.com/comment/92371460
type: QuestionComment
score: 0
has text: @MSalters I already checked all the instances that can be checked and there are differences, so I don't know why PyInsane always uses the same scanner. Also I said I thought in buying an USB hub, I haven't used it yet, I read about that internal USB hubs are most unlikly to have that Kind of functions, that's why I thought of getting an external one.
type: Comment
comment on: http://stackoverflow.com/q/52719371

http://stackoverflow.com/comment/92271786
type: Comment
type: AnswerComment
has text: It came to my mind, that my song lengths are in minutes and seconds. So probably adding them as floats is not the right way to do it, no?
comment on: http://stackoverflow.com/a/52663109
score: 0

http://stackoverflow.com/comment/92343981
has text: What is dupe? I read the Python documentation again and I couldn't find the reason. But I found an explanation [here](https://mathematica.stackexchange.com/a/2120): "I think the reason is to prevent biasing numbers on average upward or downward."
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52708695
score: 1

http://stackoverflow.com/q/52661388
answer count: 2
has answer: http://stackoverflow.com/a/52661476
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52668620
has comment: http://stackoverflow.com/comment/92252899
has answer: http://stackoverflow.com/a/52668620
tagged with: python
accepted answer: http://stackoverflow.com/a/52661476
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has title: Write a list of list into a file using list comprehension
has body: suppose we have a list of list called A: A = [[1, 100, 200, 300],[2, 300, 400, 500]] and we want to write A into a file with format below: "1\t\100\t\200\t300\n2\t\300\t400\t500" it's all in string can it be accomplished by using list comprehension on write() or writelines() function ?

http://stackoverflow.com/q/52694289
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92334502
has comment: http://stackoverflow.com/comment/92342794
accepted answer: http://stackoverflow.com/a/52694329
has title: Difference between dask pivot_table and pandas pivot_table python
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/92334528
favorite count: 0
tagged with: python-3.x
tagged with: dask
tagged with: pivot-table
upvote count: 1
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92342773
type: Question
has body: It seems we can achieve same goal using pivot_table from both libraries, but which one is more efficient in performance for large dataset?
has answer: http://stackoverflow.com/a/52694329

http://stackoverflow.com/comment/130426863
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52724022
has text: I had the same issue, but it was caused because of a negative dimension error, I had to fix and check the model architecture in a separate file and everything was fixed.
type: Comment

http://stackoverflow.com/comment/92414879
type: Comment
type: QuestionComment
has text: Sorry, could you clarify what exactly you're asking? Please correct me if it's obvious and I'm just reading it wrong or something.
score: 1
comment on: http://stackoverflow.com/q/52745085

http://stackoverflow.com/q/52663245
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52663371
upvote count: 2
has comment: http://stackoverflow.com/comment/92256616
has comment: http://stackoverflow.com/comment/92256506
type: Question
has body: Can I filter records by range of date given by the user? I want to create a Daterange form(it will contain start date and end date) in django where the user will give their specific dates and it will filter the objects based on that dates given by the user... Can I perform this in Django?
has title: How to filter records by range of date in django?
has comment: http://stackoverflow.com/comment/92256477
linked to: http://stackoverflow.com/q/4668619
has answer: http://stackoverflow.com/a/52663371
downvote count: 0
answer count: 1
tagged with: django-rest-framework
favorite count: 0
tagged with: django
tagged with: python

http://stackoverflow.com/comment/92144964
comment on: http://stackoverflow.com/a/52605275
has text: __init__ is a special function that gets executed when you instantiate the object. So if you include an __init__ in your character class, whenever you instantiate a character() object, the __init__ is executed.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92305114
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52688668
has text: It's a classic form of bad data. You have two options. Either you fix them by fixing what is generating your data (the best option) or you fix your data by changing say `' 24:'` by `' 00:'` (simple thing to do in Python).

http://stackoverflow.com/comment/92206027
type: QuestionComment
has text: @mypetlion Very nice!
comment on: http://stackoverflow.com/q/52636401
score: 0
type: Comment

http://stackoverflow.com/comment/92416674
comment on: http://stackoverflow.com/q/52745589
type: Comment
type: QuestionComment
has text: `alphanum = ''.join(chr(n) for n in range(48, 123) if chr(n).isalnum()); table = str.maketrans(alphanum, alphanum[10:] + alphanum[:10]);print('12 Cats'.translate(table))` gives `BC Mk32`.
score: 0

http://stackoverflow.com/comment/92208733
type: Comment
has text: Obviously, since that's a `SyntaxError` :) .. this was more referring to `grid[ids]`, which OP presumably tried first and found to be not working ..
comment on: http://stackoverflow.com/a/52635908
type: AnswerComment
score: 0

http://stackoverflow.com/a/52609398
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52609260
answers question: http://stackoverflow.com/q/52609260
upvote count: 2
type: AcceptedAnswer
has body: I'm no expert in R by any means but as far as I can tell, this is what you are looking for: &gt;&gt;&gt; np.tile([0, 1], 3) array([0, 1, 0, 1, 0, 1])
type: Answer

http://stackoverflow.com/comment/92441256
score: 0
type: AnswerComment
has text: both in [CT_R class](https://github.com/python-openxml/python-docx/blob/master/docx/oxml/text/run.py) and [Run class](https://github.com/python-openxml/python-docx/blob/master/docx/text/run.py) I've not found any methods that you've using in that code... Also, see the **question Update**.
type: Comment
comment on: http://stackoverflow.com/a/52745782

http://stackoverflow.com/q/52620752
has comment: http://stackoverflow.com/comment/92177967
has title: Python regex: Add "-" inside a string using re.sub
has comment: http://stackoverflow.com/comment/92175505
type: Question
has answer: http://stackoverflow.com/a/52620957
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92175629
has comment: http://stackoverflow.com/comment/92178156
accepted answer: http://stackoverflow.com/a/52620957
has comment: http://stackoverflow.com/comment/92175344
has comment: http://stackoverflow.com/comment/92175305
tagged with: pandas
has comment: http://stackoverflow.com/comment/92175310
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/92177604
upvote count: 1
type: AnsweredQuestion
has body: I have this line in my .txt file: 2016CT1021 I want to make it like this: 2016-CT-1021 I tried to use this Python regex: "re.sub": data = re.sub(r'\d\d+(?:\w\w\d\d\d\d)', r'\d\d+(?:-\w\w-\d\d\d\d)', data) But it didn't change/replace. Please someone help me. Thank you!
score: 1

http://stackoverflow.com/a/52644517
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52643774
type: Answer
accepted answer of: http://stackoverflow.com/q/52643774
downvote count: 0
has comment: http://stackoverflow.com/comment/92225752
score: 1
has body: What you are seeing is the string representation, and ugly newline \n characters, of a pd.Series object returned by the loc acessor. You should use pd.DataFrame.at to return scalars, and note there's no need here for nested {} for your index labels: L = [f'{df.at[indi, ci]} ({indi}, {ci})' \ for ci, vali in d.items() \ for indi in vali] print(L) ['abc (0, col1)', 'tre (2, col1)', 'bar (1, col2)']

http://stackoverflow.com/a/52608107
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/125418208
upvote count: 23
has comment: http://stackoverflow.com/comment/118468432
score: 22
type: AcceptedAnswer
has body: If you convert the Chicago boundary GeoDataFrame to a single polygon, eg with: chicago = df_chicago.geometry.unary_union then you can use boolean filtering with the within operator to select points within and outside of Chicago: within_chicago = df[df.geometry.within(chicago)] outside_chicago = df[~df.geometry.within(chicago)] using ~ to invert the boolean condition. Alternatively, you could use the disjoint spatial predicate: outside_chicago = df[df.geometry.disjoint(chicago)]
accepted answer of: http://stackoverflow.com/q/52600811
answers question: http://stackoverflow.com/q/52600811

http://stackoverflow.com/a/52629200
accepted answer of: http://stackoverflow.com/q/52628160
answers question: http://stackoverflow.com/q/52628160
type: AcceptedAnswer
score: 0
has body: As you point out the problem are the many lines of code that you use because it seems that you are creating 12 QActions, but the simplest thing is to iterate for it, the calendar module is used, on the other hand instead of connecting the triggered signal of the QActions it can be used the triggered signal of the QMenu that returns the modified QAction as shown below: import sys import calendar from PyQt5 import QtCore, QtWidgets class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) menu_months = self.menuBar().addMenu("Settings") menu_months.triggered.connect(self.on_triggered) for i in range(1, 13): name = calendar.month_name[i] action = menu_months.addAction(name) action.setCheckable(True) @QtCore.pyqtSlot(QtWidgets.QAction) def on_triggered(self, action): print("{} : {}".format(action.text(), action.isChecked())) # uncomment if you want to see the status of all actions """menu = self.sender() for action in menu.actions(): print("{} : {}".format(action.text(), action.isChecked()))""" if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.resize(640, 480) w.show() sys.exit(app.exec_())
type: Answer

http://stackoverflow.com/q/52592918
has comment: http://stackoverflow.com/comment/92122539
linked to: http://stackoverflow.com/q/39523216
downvote count: 0
has answer: http://stackoverflow.com/a/59898753
answer count: 3
linked to: http://stackoverflow.com/q/28291909
favorite count: 0
has answer: http://stackoverflow.com/a/64392977
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54802505
tagged with: git
has body: i have a problem with cloning git repository in my application. KEY_FILE = "/opt/app/.ssh/id_rsa" def read_git_branch(config_id, branch): config = RepoConfig.objects.get(id=config_id) save_rsa_key(Credentials.objects.get(id=1).key) git_ssh_identity_file = os.path.expanduser(KEY_FILE) git_ssh_cmd = 'ssh -i %s' % git_ssh_identity_file with Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd): with tempfile.TemporaryDirectory() as tmpdir: repo = Repo.clone_from(config.url, tmpdir, branch=branch) branch_obj, _ = Branch.objects.get_or_create(name=branch) .... def save_rsa_key(key): if not os.path.exists(os.path.dirname(KEY_FILE)): try: os.makedirs(os.path.dirname(KEY_FILE)) except OSError as exc: if exc.errno != errno.EEXIST: raise with open(KEY_FILE, 'w') as id_rsa: id_rsa.write(key) os.chmod(KEY_FILE, 0o600) Expected result is to clone repository to temporary directory, do something with it and delete all files. Instead I'm getting: DEBUG/ForkPoolWorker-2] AutoInterrupt wait stderr: b'Host key verification failed.\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.\n' git.exc.GitCommandError: Cmd('git') failed due to: exit code(128) cmdline: git clone --branch=master -v git@gitlab.foo:bar/project.git /tmp/tmpi_w2xhgt stderr: 'Host key verification failed. When i try to connect to the same repo directly from machine with key file created by code above with: ssh-agent bash -c 'ssh-add /opt/app/.ssh/id_rsa; git clone git@gitlab.foo:bar/project.git' Repo is cloned without problems + host is added to known_hosts. After doing that my code works as expected... It has to be something with known_hosts. Anyone had similar problem? Thanks for your help.
tagged with: gitpython
score: 3
linked to: http://stackoverflow.com/q/13597115
upvote count: 3
type: Question
has title: GitPython - cloning with ssh key - Host key verification failed

http://stackoverflow.com/q/52696433
downvote count: 0
score: 4
linked to: http://stackoverflow.com/q/52603847
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/50154940
tagged with: pageloadstrategy
has answer: http://stackoverflow.com/a/52697039
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/52696588
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52696588
tagged with: dom
linked to: http://stackoverflow.com/q/44770796
type: Question
upvote count: 4
has body: I have been trying to use selenium to scrape and entire web page. I expect at least a handful of them are spa's such as Angular, React, Vue so that is why I am using Selenium. I need to download the entire page (if some content isn't loaded from lazy loading because of not scrolling down that is fine). I have tried setting a time.sleep() delay, but that has not worked. After I get the page I am looking to hash it and store it in a db to compare later and check to see if the content has changed. Currently the hash is different every time and that is because selenium is not downloading the entire page, each time a different partial amount is missing. I have confirmed this on several web pages not just a singular one. I also have probably a 1000+ web pages to go through by hand just getting all the links so I do not have time to find an element on them to make sure it is loaded. How long this process takes is not important. If it takes 1+ hours so be it, speed is not important only accuracy. If you have an alternative idea please also share. My driver declaration from selenium import webdriver from selenium.common.exceptions import WebDriverException driverPath = '/usr/lib/chromium-browser/chromedriver' def create_web_driver(): options = webdriver.ChromeOptions() options.add_argument('headless') # set the window size options.add_argument('window-size=1200x600') # try to initalize the driver try: driver = webdriver.Chrome(executable_path=driverPath, chrome_options=options) except WebDriverException: print("failed to start driver at path: " + driverPath) return driver My url call my timeout = 20 driver.get(url) time.sleep(timeout) content = driver.page_source content = content.encode('utf-8') hashed_content = hashlib.sha512(content).hexdigest() ^ getting different hash here every time since same url not producing same web page
answer count: 2
accepted answer: http://stackoverflow.com/a/52697039
has title: Selenium download entire html

http://stackoverflow.com/comment/92397418
type: QuestionComment
comment on: http://stackoverflow.com/q/52736269
has text: Yes, it's possible. You have to check the weights in the network and back track them from your output, and then you can color the original pixels that lead to the decision. IBM provides this natively in their platform, I'm sure others do as well.
score: 0
type: Comment

http://stackoverflow.com/comment/92344823
comment on: http://stackoverflow.com/q/52709166
score: 0
type: Comment
type: QuestionComment
has text: ingvar yes you are right keys is already defined

http://stackoverflow.com/a/52674794
downvote count: 0
score: 1
has body: If you were to use something like the Python gensim library to load a pre-existing vector set (in the original word2vec.c format) into its KeyedVectors representation, then the raw vectors will be in a numpy array in its vectors property. For example: kv = KeyedVectors.load_word2vec_format('word_vectors.bin', binary=True) print(kv.vectors.shape) You could then use a library function like scikit-learn's pairwise_distances() to compute the distance matrix: from sklearn.metrics import pairwise_distances distances = pairwise_distances(kv.vectors, metric="cosine") Because the sklearn routine uses optimized native math routines, it will likely be a lot faster than your initial loops-in-pure-Python approach. Note, though, that the resulting distances matrix may be huge! (You can find out which words are in which kv.vectors slots via the list in kv.index2entity, or look up the slot for a word via the dict in kv.vocab.)
accepted answer of: http://stackoverflow.com/q/52663908
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52663908
type: Answer

http://stackoverflow.com/q/52632242
has body: I have a problem concerning ticks and labels on my graph, that seems to be a really basic question, but i simply cannot figure it out: I need to start the y-axis of my graph at 1 instead of 0. That is, what i achive with ax = plt.gca() ax.set_ylim([1, 250]) #y-axis limits My problem now is to set the right ticks and their labels. So i want to start my graph with 1 at the very bottom, followed by 50, 100, 150, 200, 250. I have played around a lot with yticks, e.g.: import matplotlib.pyplot as plt ticks=[1, 50, 100, 150, 200, 250] labels=[1, 50, 100, 150, 200, 250] plt.yticks(ticks, [labels]) but i cannot figure out, what iam doing wrong. Thx in advance!
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/92197837
has answer: http://stackoverflow.com/a/52632795
score: 0
has comment: http://stackoverflow.com/comment/92198011
answer count: 1
has title: Matplotlib ticks at y-axis
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/92212610
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52601383
score: 0
has text: It worked, but still says `Cannot find reference 'appengine' in '__init__.py'` and `Unresolved reference 'ndb'` ...

http://stackoverflow.com/q/52668124
accepted answer: http://stackoverflow.com/a/52668721
tagged with: data-cleaning
tagged with: python
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92266933
has title: Python str.maketrans Remove Punctuation with Empty Space
type: Question
has body: I am using maketrans from string module in Python 3 to do simple text preprocessing like lowering, removing digits and punctuations. The problem is that during the punctuation removal all words are attached together with no empty space! For example, let's say I have the following text: text='[{"Hello":"List:","Test"321:[{"Hello":"Airplane Towel for Kitchen"},{"Hello":2 "&amp;nbsp;Repair massive utilities&amp;nbsp;"2},{"Hello":"Some 3 appliance for our kitchen"2}' text=text.lower() text=text.translate(str.maketrans(' ',' ',string.digits)) Works just fine, it gives: '[{"hello":"list:","test":[{"hello":"airplane towel for kitchen"},{"hello": "&amp;nbsp;repair massives utilities&amp;nbsp;"},{"hello":"some appliance for our kitchen"}' But once I want to remove the punctuations: text=text.translate(str.maketrans(' ',' ',string.punctuation)) It gives me this: 'hellolisttesthelloairplane towel for kitchenhello nbsprepair massives utilitiesnbsphellosome appliance for our kitchen' Ideally it should yield: 'hello list test hello airplane towel for kitchen hello nbsp repair massives utilities nbsp hello some appliance for our kitchen' There is not specific reason I am doing it with maketrans, but I like as it is fast and easy and kind of stuck solving it. Thanks! Disclaimer: I already know how to do it with re like the following: import re s = "string.]With. Punctuation?" s = re.sub(r'[^\w\s]','',s)
score: 0
has answer: http://stackoverflow.com/a/52668721
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/92266355

http://stackoverflow.com/comment/92359272
has text: your `while i*i <= j:` condition is the problem. It exits when `i*i` is `<=` the value of of element on the list and your initial condition is `i=2` so for `4` , `i*i` matches the exit condition and hence the code does not go into the loop. Also you are not going to get prime factors with this code. as you do incremental increase of `i` and not go through a list of primes.
score: 0
comment on: http://stackoverflow.com/q/52716888
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52722587
has body: I am wondering if it is possible in Python to assign the value from an input statement to a variable, while making the presence of input the condition of a while loop. What I tried: while w = input("Enter word to define:\n").lower(): output = define_word(w) if type(output) = list: for item in output: print(item) What I got: File "main.py", line 23 while w = input("Enter word to define:\n").lower(): ^ SyntaxError: invalid syntax I am curious if there is a way of assigning user input to a variable provided there is any user input instead of repeating the same input statement within the loop and assigning it to a variable separately. Thank you, criticism is welcome, this is my first question on Stackoverflow ever...
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
duplicate of: http://stackoverflow.com/q/2603956
downvote count: 1
has comment: http://stackoverflow.com/comment/92370425
type: Question
has title: assign input to variable if input is condition of while loop
linked to: http://stackoverflow.com/q/2603956

http://stackoverflow.com/comment/92209287
has text: it's the newest version
type: Comment
comment on: http://stackoverflow.com/a/52613818
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92239174
type: AnswerComment
comment on: http://stackoverflow.com/a/52653641
type: Comment
has text: Yep, the one is most likely to change. I will try to think about your idea but wanted to avoid blind looping. Thanks anyway...
score: 0

http://stackoverflow.com/a/52735219
has body: Per my knowledge, maybe Azure Function is not suitable for entire application. Based on the statement in Azure Function Overview, Functions is a great solution for processing data, integrating systems, working with the internet-of-things (IoT), and building simple APIs and microservices. It is more suitable for snippet of code to process data in schedule. For both .Net application and Python application, you could use custom activity. Please see the Github guidance and this Python tutorial.
type: Answer
answers question: http://stackoverflow.com/q/52637153
score: 0

http://stackoverflow.com/comment/92291818
has text: `root.findall('a/from/b')` also finds all `"b"` with `"from"` ancestor in `a` parent
type: Comment
comment on: http://stackoverflow.com/a/52681788
score: 1
type: AnswerComment

http://stackoverflow.com/q/52640036
tagged with: tensorflow
type: Question
downvote count: 0
has body: I am implementing a keras layer AnchorTargets for retinanet in object detection, it inputs anchors and annotations (i.e. ground-truth bounding-boxes). The ideas for the codes are motivated by keras-retinanet in github. However, I got error in labels_shape = (input_shape[0]*input_shape[1], num_classes) since input_shape[0] denotes batch size, which is unavailable during network construction. Is there any suggestions for this issue? Thanks. def batch_anchor_targets_bbox( anchors, annotations, num_classes, mask_shape=None, negative_overlap=0.4, positive_overlap=0.5, **kwargs): """ Generate anchor targets for bbox detection. Args anchors: np.array of annotations of shape (B, N, 4) for (x1, y1, x2, y2). annotations: np.array of shape (B, M, 5) for (x1, y1, x2, y2, label). num_classes: Number of classes to predict. mask_shape: If the image is padded with zeros, mask_shape can be used to mark the relevant part of the image. negative_overlap: IoU overlap for negative anchors (all anchors with overlap &lt; negative_overlap are negative). positive_overlap: IoU overlap or positive anchors (all anchors with overlap &gt; positive_overlap are positive). Returns labels: np.array of shape (B, N, num_classes) where a row consists of 0 for negative and 1 for positive for a certain class. annotations: np.array of shape (B, N, 5) for (x1, y1, x2, y2, label) containing the annotations corresponding to each anchor or 0 if there is no corresponding anchor. anchor_states: np.array of shape (B, N) containing the state of an anchor (-1 for ignore, 0 for bg, 1 for fg). """ # anchor states: 1 is positive, 0 is negative, -1 is dont care anchors = keras.backend.cast(anchors, 'float32') annotations = keras.backend.cast(annotations, 'float32') input_shape = keras.backend.int_shape(anchors) annos_shape = keras.backend.int_shape(annotations) overlaps = batch_compute_overlap(anchors, annotations) argmax_overlaps_inds = keras.backend.argmax(overlaps, axis=2) max_overlaps = keras.backend.max(overlaps, …
tagged with: keras
has answer: http://stackoverflow.com/a/52654806
answer count: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: keras with tensorflow backend: layer implementation when batch_size is used, but it is None during graph construction
score: 1

http://stackoverflow.com/a/52649836
upvote count: 3
has body: Since there are only seven colors simple masking will under reasonable assumptions be quite competitive. Timings below are for 100x100x3 @ 8bit random images: timings np.unique 6.510251379047986 masking 0.2401340039796196 Note that much but not all of the speedup is due to merging the channels into a single one. Code: import numpy as np def create(M, N, k=7): while True: colors = np.random.randint(0, 256**3, (k,), dtype=np.int32) if np.unique(colors).size == k: break picture = colors[np.random.randint(0, k, (M, N))] RGB = np.s_[..., :-1] if picture.dtype.str.startswith('&lt;') else np.s_[..., 1:] return picture.view(np.uint8).reshape(*picture.shape, 4)[RGB] def f_df(image): return np.unique(image.reshape(-1, 3), return_counts = True, axis = 0) def f_pp(image, nmax=50): iai32 = np.pad(image, ((0, 0), (0, 0), (0, 1)), mode='constant') iai32 = iai32.view(np.uint32).ravel() colors = np.empty((nmax+1,), np.uint32) counts = np.empty((nmax+1,), int) colors[0] = iai32[0] counts[0] = 0 match = iai32 == colors[0] for i in range(1, nmax+1): counts[i] = np.count_nonzero(match) if counts[i] == iai32.size: return colors.view(np.uint8).reshape(-1, 4)[:i, :-1], np.diff(counts[:i+1]) colors[i] = iai32[match.argmin()] match |= iai32 == colors[i] raise ValueError('Too many colors') image = create(100, 100, 7) col_df, cnt_df = f_df(image) col_pp, cnt_pp = f_pp(image) #print(col_df) #print(cnt_df) #print(col_pp) #print(cnt_pp) idx_df = np.lexsort(col_df.T) idx_pp = np.lexsort(col_pp.T) assert np.all(cnt_df[idx_df] == cnt_pp[idx_pp]) from timeit import timeit print('timings') print('np.unique', timeit(lambda: f_df(image), number=1000)) print('masking ', timeit(lambda: f_pp(image), number=1000))
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52644348
type: Answer
has comment: http://stackoverflow.com/comment/139136808

http://stackoverflow.com/comment/117804106
has text: why you changed depreciated to deprecated ? is there a thing called deprecated ?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/66615498

http://stackoverflow.com/comment/92135969
score: 0
type: Comment
type: QuestionComment
has text: Please edit your code for greater clarity
comment on: http://stackoverflow.com/q/52600812

http://stackoverflow.com/a/52692288
has comment: http://stackoverflow.com/comment/92377620
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/92377518
answers question: http://stackoverflow.com/q/52691826
score: 2
accepted answer of: http://stackoverflow.com/q/52691826
has body: Your code has several problems: An object is not callable, so you should not use (), a class if it is. A QFrame does not have the print_ method, only QTextEdit and some classes have it, in the general case you should use QPainter. The class that provides Qt Designer is not a widget so I recommend you not to modify it or implement the logic there since you will have several problems, it is best to create a class that inherits the appropriate widget according to the template and use the class of Qt Designer to fill it Considering the above, the solution is as follows: from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(615, 356) self.frame = QtWidgets.QFrame(Form) self.frame.setGeometry(QtCore.QRect(10, 10, 571, 301)) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName("frame") self.textEdit = QtWidgets.QTextEdit(self.frame) self.textEdit.setGeometry(QtCore.QRect(100, 10, 331, 71)) self.textEdit.setObjectName("textEdit") self.tableWidget = QtWidgets.QTableWidget(self.frame) self.tableWidget.setGeometry(QtCore.QRect(30, 90, 521, 121)) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(3) self.tableWidget.setRowCount(3) 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.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(2, item) self.pushButton = QtWidgets.QPushButton(self.frame) self.pushButton.setGeometry(QtCore.QRect(240, 250, 91, 41)) self.pushButton.setObjectName("pushButton") …
has comment: http://stackoverflow.com/comment/92359430
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92330921

http://stackoverflow.com/comment/92122833
type: Comment
type: QuestionComment
has text: the simplest solution would be to poll the clipboard at a suitable rate and act whenever the clipboard content changes, this could be achieved with tkinters `Tk.after` method however if you aren't actually using the library for anything else this would be overkill, simply using a loop with a sleep is probably sufficient, however you'd need to decide an adequate poll rate
comment on: http://stackoverflow.com/q/52593557
score: 0

validation
tags question: http://stackoverflow.com/q/52602835
tags question: http://stackoverflow.com/q/52729786
type: Tag
tag name: validation
tags question: http://stackoverflow.com/q/52611498
tags question: http://stackoverflow.com/q/52647626
tags question: http://stackoverflow.com/q/52638375
tags question: http://stackoverflow.com/q/52616268

http://stackoverflow.com/q/52717117
type: UnansweredQuestion
tagged with: datetime
tagged with: python
upvote count: 3
type: Question
score: 3
has body: I currently have a dataframe which has a column containing date-time values as object datatype. col1 col2 col3 0 A 10 2016-06-05 11:00:00 0 B 11 2016-06-04 00:00:00 0 C 12 2016-06-02 05:00:00 0 D 13 2016-06-03 02:00:00 What Im trying to do is convert the col3 into date-time values so that it would just give me: Year-Month-Day-Hour For some datetime feature engineering later on. When I try: df['col3'] = pd.to_datetime(df['col3']) I get this error: OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 3008-07-25 00:00:00 Any ideas? Thanks
tagged with: dataframe
has title: Coverting string value to datetime
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52717134

http://stackoverflow.com/q/52686954
has title: How to link a select category from template to django model object?
score: 0
has answer: http://stackoverflow.com/a/52688425
answer count: 1
has body: I have a many to many relationship in my product model (category field). I am able to display the category data in a select box which is a multiple selection. What I want to do is have the user select one or more categories from the template and then save the data in my product model. Here is my code: if request.method =='POST': print ('entered') name = request.POST['name'] brand = request.POST['brand'] sku = request.POST['sku'] price = request.POST['price'] quantity = request.POST['quantity'] description = request.POST['description'] imageurls = request.POST['urls'] print('imageurls',imageurls) categorylist = request.POST['categories'] print('categorylist',categorylist) categories = re.findall(r"[\w']+", categorylist) print categories imageurls = imageurls.split('~') print('iageurls',imageurls) for x in categories: categoryobj = Category.objects.filter(name=x).values() _id = categoryobj.id print('_id',_id) print ('categoryobj',categoryobj) # Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj) return HttpResponse('success') models.py class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.') description = models.TextField() is_active = models.BooleanField(default=True) meta_keywords = models.CharField("Meta Keywords", max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField("Meta Description", max_length=255, help_text='Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('catalog:categories', kwargs={'category_slug': self.slug}) class Meta: ordering = ['-created_at'] verbose_name_plural = 'Categories' class Product(models.Mod…
type: UnansweredQuestion
tagged with: python
tagged with: django
type: Question

http://stackoverflow.com/q/52638320
score: -3
has title: Creating a filename from variable
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52638337
has body: I have a filename named hosts_access_log_00.txt that I take in from user input like filename = input() I need to write some output to another filename called records_host_access_log_00.txt where the host_access_log_00.txt comes from filename. How can I create this filename with this specific name? (i.e. prepending "records" to the filename)
tagged with: python
answer count: 1
linked to: http://stackoverflow.com/q/4435169
tagged with: file
downvote count: 3
duplicate of: http://stackoverflow.com/q/4435169
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/92304752
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52688880
has text: You are searching for an empty string (`''`), but you should be searching for space (`' '`)

http://stackoverflow.com/comment/92318610
comment on: http://stackoverflow.com/a/52695804
score: 0
type: AnswerComment
has text: Thats actually cleaner. Let me also add to answer. Great.
type: Comment

http://stackoverflow.com/a/52643650
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52643361
accepted answer of: http://stackoverflow.com/q/52643361
has comment: http://stackoverflow.com/comment/92222248
upvote count: 1
has comment: http://stackoverflow.com/comment/92220873
has body: If you are familiar with how to work with sqlite you can take advantage of pandas and split your tables into chunks, then push them back to your database. Here is how you could split the data: import pandas as pd df = pd.DataFrame({'a': ['hi', 'bye', 'bye', 'bye', 'hi', 'hi'], 'c': [234, 342, 433, 234, 435, 455], 'b': [4, 7, 5, 4, 56, 3], 'd': ['lala', 'lulu', 'abc', 'abd', 'abc', 'a']}) dfs = {i: df.loc[df['a']==i] for i in df['a'].unique()} dfs #{'bye': a b c d # 1 bye 7 342 lulu # 2 bye 5 433 abc # 3 bye 4 234 abd, # 'hi': a b c d # 0 hi 4 234 lala # 4 hi 56 435 abc # 5 hi 3 455 a}

http://stackoverflow.com/comment/92172722
type: QuestionComment
type: Comment
has text: Show us the template render call. As it is, you've given us a python variable called `codes` and a template variable called `result`, and we have no idea how those are supposed to be related.
comment on: http://stackoverflow.com/q/52618581
score: 0

http://stackoverflow.com/q/52710013
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52710369
type: Question
linked to: http://stackoverflow.com/q/40515418
favorite count: 0
has body: I have a strong text.xlsx file with several cols and thousand rows. I need to delete the text from the cells that do not contain the word student I tried with the following but it didn't work so far, it deletes all the column: df.loc[~df["Column1"].str.contains('student',case=True),'Column1']=' '
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52710369
answer count: 1
has comment: http://stackoverflow.com/comment/92346591
has title: Replace the text by blank spaces in cells that do not contain a specific word .xlsx in Pandas
upvote count: 1
tagged with: python

hudson
type: Tag
tag name: hudson
tags question: http://stackoverflow.com/q/52734889

http://stackoverflow.com/comment/92289067
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52680244
score: 1
has text: Imagine you have a variable or function `print_data`. Then opening parentheses after you typed just `print` wouldn't be helpful.

http://stackoverflow.com/q/52612318
linked to: http://stackoverflow.com/q/19290762
linked to: http://stackoverflow.com/q/4081217
tagged with: python
has comment: http://stackoverflow.com/comment/92159418
has title: Iterating and changing elements in a list in Python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52612479
accepted answer: http://stackoverflow.com/a/52612479
has answer: http://stackoverflow.com/a/52612469
type: Question
has comment: http://stackoverflow.com/comment/92159482
duplicate of: http://stackoverflow.com/q/19290762
has comment: http://stackoverflow.com/comment/92159262
score: 0
answer count: 2
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/52612469
favorite count: 0
has body: I'm supposed to find the largest number in a list, and then change all the elements of the list to that number. But when I print the output after the iteration, it still hasn't changed. What am I doing wrong please ? Ar =[5,4,11] ArMax = max(Ar) for i in Ar: i = ArMax print(Ar)

http://stackoverflow.com/comment/128271529
score: 0
has text: I have installed it.
type: AnswerComment
comment on: http://stackoverflow.com/a/52681202
type: Comment

http://stackoverflow.com/a/52602866
downvote count: 0
has body: Assuming your date columns are strings, you can use assign() with to_datetime() like this: df.assign(date = pd.to_datetime(df['YYYY'] + "-" + df['MM'] + "-" + df['DD'])) YYYY MM DD foo date 0 2010 5 1 0 2010-05-01 1 2012 10 2 1 2012-10-02 2 2015 12 3 2 2015-12-03 Data: data = {"YYYY": ["2010", "2012", "2015"], "MM": ["5", "10", "12"], "DD": ["1", "2", "3"], "foo": range(3)} df = pd.DataFrame(data)
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52602654
score: 1

http://stackoverflow.com/a/52649947
has comment: http://stackoverflow.com/comment/92231727
accepted answer of: http://stackoverflow.com/q/52649802
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92231925
answers question: http://stackoverflow.com/q/52649802
has comment: http://stackoverflow.com/comment/92231890
score: 0
type: Answer
has body: The syntax you have in your question it is already a tuple, you can get a list using the list class for that effect. &gt;&gt;&gt; tuple_numbers = (2,3,4,5,6) &gt;&gt;&gt; list_numbers = list(tuple_numbers) &gt;&gt;&gt; list_numbers [2,3,4,5,6] I see you're new to Python, at least seems to be that way. So I'll recommend reading about list and tuples. If you want to apply some transformation to list items, try map. Note Take into account that it is not the same: list(2,3,4,5) that list((2,3,4,5)). The first is wrong since you are passing more than one argument Happy coding!

http://stackoverflow.com/comment/92401581
comment on: http://stackoverflow.com/a/52736844
type: AnswerComment
has text: The output is blank in those cases unless you also include the number of divisions to check with the naive grid search that's currently implemented, as there are no results with that resolution that would satisfy the epsilon requirement. If you need an exact result, you may want to look into symbolic math libraries for Python, or if you just want a more exact (but still not fully exact) result, use a root-finding algorithm like Newton's or something.
score: 0
type: Comment

http://stackoverflow.com/comment/92367029
comment on: http://stackoverflow.com/a/52720748
type: Comment
score: 0
type: AnswerComment
has text: I just want to show the latest date as when the user chose the dates the template should display the selected dates by the user...Can You tell me is my process of accomplishing this is right???

http://stackoverflow.com/q/52736681
has title: Is there any way to speed up my Daugman's operator function on numpy?
type: Question
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/92400111
favorite count: 0
linked to: http://stackoverflow.com/q/23295642
upvote count: 2
linked to: http://stackoverflow.com/q/35215161
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92399171
score: 2
has body: Few days ago I tried to find python implementation of Daugman's Iris detection algorithm. I found only one repo on github, but implementation was very slow, around 46 sec on my laptop. So, I rewrote all stuff, according to this formulae: Final result is ~85 times faster (~530 ms on my laptop), but it is still not fast enough fo real-time video processing (at 10 fps, at least). I've read this stackoverflow topics 1,2 and tried to vectorize the code. I've tested map(), np.vectorize(), np.fromiter(), but they were no faster than my current solution (some of them were even slower) and I am out of ideas. Is there a way to vectorize code below or I need to use C extensions or try to run it on PyPy? My solution: def daugman(center, start_r, gray_img): """return maximal intense radius for given center center -- tuple(x, y) start_r -- int gray_img -- grayscale picture as np.array(), it should be square """ # get separate coordinates x, y = center # get img dimensions h, w = gray_img.shape # for calculation convinience img_shape = np.array([h, w]) c = np.array(center) # define some other vars tmp = [] mask = np.zeros_like(gray) # for every radius in range # we are presuming that iris will be no bigger than 1/3 of picture for r in range(start_r, int(h/3)): # draw circle on mask cv2.circle(mask, center, r, 255, 1) # get pixel from original image radii = gray_img &amp; mask # it is faster than np or cv2 # normalize tmp.append(radii[radii &gt; 0].sum()/(2*3.1415*r)) # refresh mask mask.fill(0) # calculate delta of radius intensitiveness tmp = np.array(tmp) tmp = tmp[1:] - tmp[:-1] # aply gaussian filter tmp = abs(cv2.GaussianBlur(tmp[:-1], (1, 5), 0)) # get maximum value idx = np.argmax(tmp) # return value, center coords, radius return tmp[idx], [center, idx + start_r] def find_iris(gray, start_r): """Apply daugman() on every pixel in calculated image slice gray -- graysacale img as np.array() start_r -- initial radius as int Selection of image slice guarantees that every radius …
tagged with: performance
answer count: 0

http://stackoverflow.com/comment/92284655
comment on: http://stackoverflow.com/q/52676742
score: 0
type: QuestionComment
has text: very common formats to use are json and yaml files. Python has excellent libraries for both.
type: Comment

http://stackoverflow.com/q/52673610
possible better answer: http://stackoverflow.com/a/52675560
has answer: http://stackoverflow.com/a/52675560
upvote count: 56
tagged with: python
linked to: http://stackoverflow.com/q/1987694
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/68079548
tagged with: pytorch
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/59889715
tagged with: debugging
has body: I came across this PyTorch tutorial (in neural_networks_tutorial.py) where they construct a simple neural network and run an inference. I would like to print the contents of the entire input tensor for debugging purposes. What I get when I try to print the tensor is something like this and not the entire tensor: I saw a similar link for numpy but was not sure about what would work for PyTorch. I can convert it to numpy and may be view it, but would like to avoid the extra overhead. Is there a way for me to print the entire tensor?
answer count: 3
downvote count: 0
score: 56
accepted answer: http://stackoverflow.com/a/59889715
favorite count: 0
has title: Printing all the contents of a tensor

http://stackoverflow.com/a/52592210
has body: Use selenium, and something like this driver.find_element_by_css_selector('div.RC-runnerPriceWrapper').get_attribute('data-diffusion-decimal')
answers question: http://stackoverflow.com/q/52591846
score: 1
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/52711665
favorite count: 0
tagged with: postgresql
tagged with: python
type: UnansweredQuestion
has body: I have a Docker setup, with a Flask app and a Postgresql backend. I want to be able to create all of my tables in Postgres from their Models defined in Flask-SqlAlchemy. This is currently not working for me. In my app __init__.py I create my app with config files. from flask import Flask def create_app(): app = Flask(__name__) app.config.from_pyfile("config.py") app.config.from_pyfile("secrets.py") return app app = create_app() from app import routes In my routes.py I make the DB from the app, and then set it up before the first request(with my Models imported): from .models import User, Community, Post, Debate ... db = SQLAlchemy(app) @app.before_first_request def setup(): db.init_app(app) with app.app_context(): db.metadata.drop_all(bind=db.engine) db.metadata.create_all(bind=db.engine) db.session.commit() My models inherit from a BaseModel I made which inherits from db.Model, where db is an import of the db I defined in routes.py. What am I doing wrong here? How can I make flask-sqlalchemy automatically create my tables for me? Am I barking up the wrong tree?
type: Question
tagged with: sqlalchemy
upvote count: 4
has answer: http://stackoverflow.com/a/59501815
has title: Getting flask-sqlalchemy to create tables from Models with db.create_all
downvote count: 0
answer count: 1
score: 4
tagged with: flask

http://stackoverflow.com/a/52734309
upvote count: 1
answers question: http://stackoverflow.com/q/52729169
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52729169
type: Answer
has body: Use matplotlib.dates.DateFormatter. First import it at the top import matplotlib.dates as mdates then replace this line fig = plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=5)) by something like this myFmt = mdates.DateFormatter('%y-%m-%d %H') # here you can format your datetick labels as desired plt.gca().xaxis.set_major_formatter(myFmt) In a example with random numbers (since you haven't provided sample data), it looks like this Here, the formatter is chosen as you wanted: dates + hours. For further info about how to format the date on the axis, check here
score: 1

http://stackoverflow.com/comment/92350453
comment on: http://stackoverflow.com/a/52712074
type: Comment
has text: df['Countdown'] = (df['date']-df['full dates']).dt.days
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92401855
comment on: http://stackoverflow.com/q/52738220
score: 0
type: Comment
type: QuestionComment
has text: i'm really sorry.....Forgot those things. Problem solved.

http://stackoverflow.com/a/52687586
has body: So the error comes from the fact that in your serializer, you don't specify object_id in the meta fields. By default all fields in a django model are required and do not accept null values. If you want a field to be null, you need explicitly set null=True for the field in your model. But in your case, as it is part of the unique constraint, i don't expect that null is correct value. Solution is to include the object_id in your serializer's fields. You may send it in your post request but your serializer will ignore it as it is not in the list of fields to serialize. That's why I asked you to include your POST data which you send.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52685653

http://stackoverflow.com/q/52604732
score: 8
favorite count: 0
upvote count: 8
type: UnansweredQuestion
tagged with: python
has title: Enable debug mode in Flask in production mode
has body: In bottle all i have to do to enable debug mode is: from bottle import debug application = Bottle() app = application debug(True) How can i do the same in Flask framework?
has answer: http://stackoverflow.com/a/64788558
has answer: http://stackoverflow.com/a/77560808
has answer: http://stackoverflow.com/a/65746752
type: Question
has answer: http://stackoverflow.com/a/71570308
has answer: http://stackoverflow.com/a/52605149
has answer: http://stackoverflow.com/a/52604909
tagged with: flask
has answer: http://stackoverflow.com/a/54145143
downvote count: 0
answer count: 7

http://stackoverflow.com/q/52613373
score: 0
answer count: 2
has body: I used below code to split a dataframe using dask: result=dd.from_pandas(df, chunksize=75) I use below code to create a custom json file: for z in result: createjson (z) It just didnt work! how can I access to each chunk?
tagged with: pandas
has comment: http://stackoverflow.com/comment/92161194
has answer: http://stackoverflow.com/a/52613490
tagged with: dask
has title: get/access each chunk of dask.dataframe(df, chunksize=100)
tagged with: python
has answer: http://stackoverflow.com/a/52614174
type: AnsweredQuestion
type: Question
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52614174
accepted answer: http://stackoverflow.com/a/52613490

http://stackoverflow.com/comment/92362414
type: AnswerComment
comment on: http://stackoverflow.com/a/52715105
type: Comment
has text: Yes, I gave it also in the future I'l give you up for this help :)
score: 0

http://stackoverflow.com/comment/92329950
type: Comment
comment on: http://stackoverflow.com/a/52701064
has text: When I try your proposed code I get the exact value. But when I replace `Proba = np.array(7.4687206e-10)` by the output of my function, that is : `Proba = model.predict(img) = 7.4687206e-10`; I get alwayes [[1.]].
score: 0
type: AnswerComment

http://stackoverflow.com/q/52615414
answer count: 3
has comment: http://stackoverflow.com/comment/92205886
has answer: http://stackoverflow.com/a/52653068
tagged with: jupyter
has answer: http://stackoverflow.com/a/54495580
favorite count: 0
has title: How to set ipython/jupyter as the default python terminal for vscode?
has comment: http://stackoverflow.com/comment/92507652
score: 16
tagged with: python
upvote count: 16
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/54495580
tagged with: ipython
has answer: http://stackoverflow.com/a/53968855
type: Question
tagged with: visual-studio-code
linked to: http://stackoverflow.com/q/52310689
downvote count: 0
possible better answer: http://stackoverflow.com/a/53968855
linked to: http://stackoverflow.com/q/54332723
has body: How can I choose ipython/jupyter as the DEFAULT python terminal? I use both a windows 10 and a linux machine with the anaconda distribution. If I type "ipython" on the terminal, it opens an ipython session. If I run the debugger or shift+enter a line, it automatically runs on a "barebones" python shell. Should be simple...but I have been googling and messing with the settings for half an hour with no success. Looked up https://code.visualstudio.com/docs/python/tutorial-flask Use IPython REPL in VS Code but could not find a way to set it up on my linux or win10 machines. Any ideas?

http://stackoverflow.com/comment/92331188
type: Comment
has text: Can you please share the error your getting.
score: 0
comment on: http://stackoverflow.com/q/52702033
type: QuestionComment

http://stackoverflow.com/a/52646096
has comment: http://stackoverflow.com/comment/92224344
has comment: http://stackoverflow.com/comment/92224304
has body: You could use another for loop to loop through the axes, and use ax.annotate instead to make sure you are plotting to the right axes: for ax in [ax5, ax6, ax7, ax8]: for i, ciiu_4n1 in enumerate(micro.ciiu_4n1): ax.annotate(ciiu_4n1, [micro.total_tax[i], micro.id_inf[i]]) If each plot uses different datasets then the solution would be to do your initial loop for each axes as shown in Bazingaa's answer
upvote count: 1
has comment: http://stackoverflow.com/comment/92224533
answers question: http://stackoverflow.com/q/52646026
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/52731367
type: Answer
accepted answer of: http://stackoverflow.com/q/52731273
score: 2
answers question: http://stackoverflow.com/q/52731273
has comment: http://stackoverflow.com/comment/92387788
upvote count: 2
has comment: http://stackoverflow.com/comment/92387824
has body: Docstring Example Let's show how an example of a multi-line docstring: def my_function(): """Do nothing, but document it. No, really, it doesn't do anything. """ pass Let's see how this would look like when we print it print my_function.__doc__ Do nothing, but document it. No, really, it doesn't do anything. Declaration of docstrings The following Python file shows the declaration of docstrings within a python source file: """ Assuming this is file mymodule.py, then this string, being the first statement in the file, will become the "mymodule" module's docstring when the file is imported. """ class MyClass(object): """The class's docstring""" def my_method(self): """The method's docstring""" def my_function(): """The function's docstring""" How to access the Docstring The following is an interactive session showing how the docstrings may be accessed &gt;&gt;&gt; import mymodule &gt;&gt;&gt; help(mymodule) Assuming this is file mymodule.py then this string, being the first statement in the file will become the mymodule modules docstring when the file is imported. &gt;&gt;&gt; help(mymodule.MyClass) The class's docstring &gt;&gt;&gt; help(mymodule.MyClass.my_method) The method's docstring &gt;&gt;&gt; help(mymodule.my_function) The function's docstring
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92387816

http://stackoverflow.com/q/52595277
has answer: http://stackoverflow.com/a/52597449
type: AnsweredQuestion
has body: I found the following formula on another post and slightly modified it which gets very close to the data, but now I’m not sure what regex adjustment to make. The following code places the regex result (from html string) into result, which is almost the JSON, but it starts with from bs4 import BeautifulSoup import re soup = BeautifulSoup(""" ... """, "html.parser") pattern = re.compile(r"\s+=\s+(\{.*?\});\n") result = soup.find("script", text=pattern) Sidenotes: While technically the json could be manually extracted without regex in this case, results are slightly different in various pages I would like to learn regex, but presently don’t have the bandwidth to start from the ground up.
type: Question
linked to: http://stackoverflow.com/q/43852187
accepted answer: http://stackoverflow.com/a/52595362
score: 0
answer count: 2
has title: Regex formula almost extracts JSON, but result is wrapped with extra data
has answer: http://stackoverflow.com/a/52595362
possible better answer: http://stackoverflow.com/a/52597449
tagged with: python
tagged with: regex

genetic-algorithm
tags question: http://stackoverflow.com/q/52646909
tag name: genetic-algorithm
tags question: http://stackoverflow.com/q/52710727
type: Tag

http://stackoverflow.com/comment/92125868
comment on: http://stackoverflow.com/q/52595329
score: 0
type: Comment
type: QuestionComment
has text: How do you know it returns a wrong result?

http://stackoverflow.com/comment/92357165
has text: @ZhaoyangXu The problem has two aspects: ① The server is returning HTML with a NUL (which it shouldn't) and ② the parser aborts at the NUL (which is annoying only because of ①). The main thing is understanding what's happening so one can anticipate similar problems and their symptoms better. The other thing is to fix the concrete problem at hand. It doesn't solve all similar issues (like otherwise broken HTML or similar) of course, but at least exactly this one.
comment on: http://stackoverflow.com/a/52700350
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/92125132
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52595004
has text: it's strange. Which pandas version are you using? Mine is 0.22.0. Maybe it's a bug. Why don't you try converting to int first: `df['cable_block'].astype(int).astype(str) + '/' + df['pair'].astype(int).astype(str)` ?
score: 0

http://stackoverflow.com/comment/92329623
type: QuestionComment
has text: So, are you trying to group by month (and "Compteur")?
type: Comment
comment on: http://stackoverflow.com/q/52701303
score: 0

http://stackoverflow.com/a/74717495
downvote count: 1
has comment: http://stackoverflow.com/comment/131873201
answers question: http://stackoverflow.com/q/52679401
has body: a = input() //for string b = int(input()) //for int c = float(input()) //for float
score: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/52600364
type: Question
downvote count: 0
has body: pyinstaller makes huge sized file(over 1.2GB). I don't know why... Is there any helper? Thank you. Env Anaconda - Python 3.6.6 Imports from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.alert import Alert import xlwings as xw from tkinter import * from tkinter import messagebox from tkinter import filedialog Commands Tried pyinstaller --noconsole --onefile "./test.py" --name="test.exe" pyinstaller -F "./test.py" --name="test.exe" File List Starts with 'mkl' Sorted ASC by Size
answer count: 1
has answer: http://stackoverflow.com/a/52694699
favorite count: 0
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/92135236
upvote count: 1
tagged with: python
has title: pyinstaller makes huge sized file
tagged with: selenium-webdriver
type: AnsweredQuestion
tagged with: xlwings
score: 1
accepted answer: http://stackoverflow.com/a/52694699

http://stackoverflow.com/a/52664511
type: Answer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/52664433
accepted answer of: http://stackoverflow.com/q/52664433
type: AcceptedAnswer
has body: I think it would be more straightforward if you used table merges. items.merge(users'User_ID', 'Name', left_on='Its_User_ID', right_on='User_ID', how='left') This will add the column Name to the new dataset, which you can of-course rename later. This will be much more efficient that doing the operation via a for loop column-wise.
upvote count: 3

http://stackoverflow.com/q/52710503
has title: Convert multiple tables from a html file to Excel preserving the CSS styles
type: Question
tagged with: html-table
answer count: 2
has body: I have a html file and there are some tables, and I want to convert this html to Excel. Actually I can copy all page and paste it in Excel but I will have to repeat this process other html files. Can I use python for this process?
has answer: http://stackoverflow.com/a/52710562
score: 0
tagged with: http://stackoverflow.com/tag/html
type: UnansweredQuestion
tagged with: python
tagged with: excel
has answer: http://stackoverflow.com/a/55253401

http://stackoverflow.com/comment/92138411
comment on: http://stackoverflow.com/a/52599896
score: 0
type: AnswerComment
has text: ` else: print('{} is not a valid prime number'.format(i)) for idx, item in enumerate(check, start = 2): if not item: print('\t{} * {} = {} '.format(idx, int(i/idx), i))` @Daniel
type: Comment

http://stackoverflow.com/a/52724113
upvote count: 3
answers question: http://stackoverflow.com/q/52723919
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52723919
type: AcceptedAnswer
type: Answer
score: 3
has body: My guess was to try quoting the URL: [testenv] commands = pip install -e "git+ssh://git@bitbucket.org/org/repo#egg=repo[server]" and that seems to do the trick.

http://stackoverflow.com/a/52710737
has body: Read and process line-by line: with open('triangles.txt','r') as infile: for line in infile: ...
answers question: http://stackoverflow.com/q/52710650
type: Answer
score: 0

http://stackoverflow.com/q/52616351
has body: In my project i have a binary like this: data1 = b'"[5, \\"WEB99\\", \\"Test\\", true, \\"2018-08-12\\"]"' i would extract some informations (without \), for example date1[0] -> 5 or data1[4] -> "2018-08-12" For doing this i try to convert my binary in a dict using json like this: data1 = data1.decode('utf-8') then d1 = json.dumps(data1, default='utf-8') but the result is a mess: '"\"[5, \\\"WEB99\\\", \\\"Test\\\", true, \\\"2018-08-12\\\"]\""' how can i convert in a pythonic way my binary data in a format for extracting values? Thanks in advance
possible better answer: http://stackoverflow.com/a/52616366
has comment: http://stackoverflow.com/comment/92167375
has answer: http://stackoverflow.com/a/52616366
has comment: http://stackoverflow.com/comment/92167011
tagged with: python
tagged with: utf-8
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92167300
has answer: http://stackoverflow.com/a/52616541
score: 0
has comment: http://stackoverflow.com/comment/92167143
has comment: http://stackoverflow.com/comment/92167126
has title: Python from binary to dict
type: Question
has comment: http://stackoverflow.com/comment/92167077
has comment: http://stackoverflow.com/comment/92167089
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/52616541
answer count: 2
has comment: http://stackoverflow.com/comment/92167383
has comment: http://stackoverflow.com/comment/92167181

http://stackoverflow.com/q/52594121
tagged with: opencv
score: 2
tagged with: python-imaging-library
downvote count: 0
type: Question
upvote count: 2
has body: Im trying to make image compressor in my django project. I did well with jpg, but got a lot of problems with png. For compression i using PIL and cv2, but cant get result better then 16% of compression for big PNG files (>1 mb). Ive tryed to combine both libraries, and its still not innove. Here simple code of my view: (the above code for jpg compression) elif picture.mode == ('RGBA'): if photo.image.size &lt; 1000000: colorsloss = picture.convert(mode="P", palette=Image.ADAPTIVE) colorsloss.save('media/new/'+name,"PNG",quality=75, optimize=True, bits=8) else: originalImage = cv.imread(str('/home/andrey/sjimalka'+ photo.image.url)) cv.imwrite('media/new/'+name, originalImage,[cv.IMWRITE_PNG_COMPRESSION, 9]) cvcompressed = Image.open('media/new/'+name) cvcompressed.convert(mode="RGB") cvcompressed.save('media/new/'+name,"PNG",quality=75, optimize=True) So here ive got 2 big problems: 1) If ive got low size image (&lt; 1 mb), i using P mode in Pillow. It works great, but if i compressing image with gradient, i can see some distortions in places where i got gradient. I have good compression (something like 85%), but no idea yet how to fix it. 2) I cant get good compression of big png files. My best goal yet is 16%, with really good quality, but it still not innove. Mb i do something wrong, or i shold use any other library or technology to make it better. I want to get a list 50% of compression with big png files. I already tryed to use pngquant, but their docs wasnt too clear for me, and i cant find good code examples.
has answer: http://stackoverflow.com/a/52616555
has title: Compression PNG with PIL and cv2
linked to: http://stackoverflow.com/q/32413523
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/q/52653975
has body: So I have a list that looks something like [’A’, 1, 3, 6, ’B’, 3, 5, ’C’, 6, 7, 3] how do I divide the list into sublists everytime there is a new string so that I would get [A’, 1, 3, 6] [’B’, 3, 5] [’C’, 6, 7, 3]
upvote count: 0
tagged with: list
type: Question
has comment: http://stackoverflow.com/comment/92240424
has answer: http://stackoverflow.com/a/52654219
answer count: 6
score: -1
has answer: http://stackoverflow.com/a/52654276
has answer: http://stackoverflow.com/a/52673482
has answer: http://stackoverflow.com/a/52654231
downvote count: 1
has answer: http://stackoverflow.com/a/52654133
has title: Divide list when there is a shift from int to str
favorite count: 0
has answer: http://stackoverflow.com/a/52654233
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52604414
tagged with: pandas
has body: I have a dataset x text 1 one 2 two 4 four 5 five 7 seven now I want output as x text 1 one 2 two 3 null 4 four 5 five 6 null 7 seven
accepted answer: http://stackoverflow.com/a/52604434
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52604434
type: AnsweredQuestion
score: 3
has title: I need to insert null values for missing index in python pandas
type: Question
upvote count: 4
tagged with: missing-data
answer count: 1
favorite count: 0

http://stackoverflow.com/a/52649238
answers question: http://stackoverflow.com/q/52631569
has body: First of all, if you have files with different sampling rates, you should consider resampling (a.k.a. samling rate conversion). This is what's normally done to solve your problem. Second, PortAudio (the C library behind the sounddevice module) doesn't support changing the sampling rate of an existing stream. There are other audio frameworks which theoretically support that (e.g. JACK), if you really need that. Third, if you really need streams with different sampling rate, you can of course close one stream and open another one with a different sampling rate. On some platforms you can even have multiple streams (with potentially different settings) at the same time. You should not close the stream in the finished_callback, in fact you should call no functions from the sounddevice module in there. It's probably not a good idea to create a stream in the update_plot callback, because it would be destroyed when the variable goes out of scope (which happens very quickly because the function is typically very short). You should probably make a separate thread for plotting and handle stopping and restarting audio streams in the main thread (or vice versa).
score: 0
type: Answer

http://stackoverflow.com/comment/92155041
comment on: http://stackoverflow.com/a/52610263
type: AnswerComment
type: Comment
score: 0
has text: @Wen, there is no difference i see its just i was reproducing the OPS scenario to test and answer , so there should be no offence? is there any issues.

http://stackoverflow.com/comment/92213363
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52640376
type: Comment
has text: thanks, im new to programming, ill have to check out this formatting thing.

http://stackoverflow.com/comment/92208403
type: QuestionComment
has text: That's what I thought, I got it now thanks!
comment on: http://stackoverflow.com/q/52618450
score: 0
type: Comment

http://stackoverflow.com/q/52682288
has body: Let's say I have a list ls = [[1,2,3], [4,5,6], [7,8,9]] Now I want to split this list into other smaller square 2d lists where the square's side is determined by an input k. So if k was 2, I would get 4 new lists trying to distribute the elements equally between them and those lists would be: L1 = [1,2, 4,5] L2 = [3, 6] L3 = [7,8] L4 = [9] I am not so sure how can I do this. I can split a list if I decide the number of squares, but not if the number of squares is a random number input from the user. I tried this, but I am not sure how do I continue from this point, after deciding the first block of elements. ls = [[1,2,3], [4,5,6], [7,8,9]] def splitList(ls, k): if len(ls) == 1: return ls[0] else: for x in range(k): for y in range(k): print (ls[x][y]) print (splitList(ls, 2)) Any help would be greatly appreciated. Thank you for your time!
answer count: 2
tagged with: arrays
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52683245
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: list
upvote count: 2
has title: Split a 2D list into square blocks with equally distributed elements
type: Question
possible better answer: http://stackoverflow.com/a/52683245
tagged with: split
has answer: http://stackoverflow.com/a/52682724
accepted answer: http://stackoverflow.com/a/52682724
has comment: http://stackoverflow.com/comment/92293675

http://stackoverflow.com/a/52629718
has body: you should value the global limit. Code: must_print = True def myfunction(must_print): global must_print must_print = True if bool(must_print) == True: print("Done") elif bool(must_print) == False: print("Change value") if __name__ == "__main__": myfunction(must_print) Output: Done
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52629441

http://stackoverflow.com/q/52643591
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52644134
favorite count: 0
has comment: http://stackoverflow.com/comment/92219880
has answer: http://stackoverflow.com/a/52644461
tagged with: python
has comment: http://stackoverflow.com/comment/92219945
has comment: http://stackoverflow.com/comment/92219799
has title: Python not checking csv against input
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92219748
has comment: http://stackoverflow.com/comment/92219629
has comment: http://stackoverflow.com/comment/92219833
has body: I'm creating a project during my spare time which is a user-based quiz with score-keeping and high score tallies. Currently i'm stuck with stage 1 of the creation which is the login section. I'm using CSVs for this as I have found them easier to edit than other methods. The problem is that it only checks the first row of the file and nothing else. This can cause issues when it comes to people added after the first row, as it checks the first row, sees they don't match and throws the "Incorrect" error below. I've used print() statements to try and see if there's any issues with inputs or python checking the csv file, however everything seems perfectly fine, it's responding with the full csv in the correct format, so it should work. def login(): print("\n") print("-----------------------------------------") print("Create an account") print("-----------------------------------------") uname = input("Enter name: ") pword = input("Enter a password: ") print("----------------------------------------") print("Please wait...") print("-----------------------------------------") UD = open(os.path.join(os.path.dirname(__file__), 'users.csv'), 'r') for line in UD: user = line.split(",") print("input for uname is: "+uname) print("input for pword is: "+pword) print(user[0]) print(user[1]) if user[0] == uname and user[1] == pword: print("\n") print("-----------------------------------------") print("Login successful!") print("-----------------------------------------") UD.close() else: print("\n") print("----------------ERROR!-----------------") print("Incorrect username / password!\n") break The CSV file currently contains only these entries: person1 password1 person2 password2 What am I doing wrong? Any help is gladly appreciated. Edit: Output of running the current code: Enter name: person1 Enter a password: password1 ---------------------------------------- Please wait... ----------------------------------------- ----------------ERROR!----------------- Incorrect username / pas…
type: Question
score: 0
answer count: 2

http://stackoverflow.com/comment/92440390
comment on: http://stackoverflow.com/a/52743223
type: Comment
has text: I get back the exact same response
score: 0
type: AnswerComment

http://stackoverflow.com/q/52669276
tagged with: python
upvote count: 0
score: -5
has answer: http://stackoverflow.com/a/52669315
tagged with: web-scraping
has body: I created a website using HTML and CSS and now, I need to crawl through it to download the images. If the link for locally hosted website is like: http://localhost/Webpage.html Is it possible?
type: Question
has comment: http://stackoverflow.com/comment/92268342
downvote count: 5
has comment: http://stackoverflow.com/comment/92268376
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has title: Can I crawl locally hosted website using python?
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/92283912
type: QuestionComment
comment on: http://stackoverflow.com/q/52676843
score: 0
type: Comment
has text: it worked!!! thanks!!!!

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/52736424
tags question: http://stackoverflow.com/q/52747087
tags question: http://stackoverflow.com/q/52671262

http://stackoverflow.com/a/52696193
has body: I've experienced this problem with Keras as well, it has to do with the random seed, you can fix your random seed like this before importing the Keras, so that you could get the consistent result. import numpy as np np.random.seed(1000) import os import random os.environ['PYTHONHASHSEED'] = '0' random.seed(12345) # Also set the tf randomness to some fixed values like this if you need: tf.set_random_seed(1234) This worked for me.
score: 1
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52695534

http://stackoverflow.com/q/52669094
has body: I'm new to Python, and my tutor taught us about formatting, if else statements and print. He wants us to use the import function to read data from a CSV file, and he gave us a starting piece of code to help us with that, which is: import csv filePath = "data.csv" with open(filePath) as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['first_name'], row['last_name']) The CSV file contains the following: first_name,last_name,student_id,CSIT110,CSIT121,CSIT135,CSIT142 Peter,Tan,S1012342D,89,67,54,78 John,Lim,S1014322H,87,78,86,67 Ada,Ang,S1023456I,54,78,65,54 So what the objective is, is to prompt the user for their student number. And if the student number exists, it prints out their name, ID and grades. So far, my code is this: import csv filePath = "data.csv" student_num=input("Enter student ID:") with open(filePath) as csvfile: reader = csv.DictReader(csvfile) for row in reader: #average = int((row['CSIT110'])+int(row['CSIT121'])+int(row['CSIT135'])+int(row['CSIT142']))/4 if (student_num == ""): print("Empty input. Please enter again.") elif (student_num == "S1012342D"): print("=================") print("Student's details") print("=================") print("Student ID | First Name | Last Name") print("{0:&lt;10} |{1:&gt;11} | {2:&lt;10}".format(row['student_id'],row['first_name'],row['last_name'])) print("===============================================") print("CSIT110 | CSIT121 | CSIT135 | CSIT142 | Average") print("{0:^8}|{1:^9}|{2:^9}|{3:^9}|".format(row['CSIT110'],row['CSIT121'],row['CSIT135'],row['CSIT142'])) elif (student_num == "S1014322H"): print("=================") print("Student ID | First Name | Last Name") print("{0:&lt;10} |{1:&gt;11} | {2:&lt;10}".format(row['student_id'],row['first_name'],row['last_name'])) else: print("No student record found.") When I type one of the student ID, it just loops and prints out all the details. Would love some help!
tagged with: python
has comment: http://stackoverflow.com/comment/92267991
possible better answer: http://stackoverflow.com/a/52669333
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52669333
has title: How do I display data from CSV based on user input?
has answer: http://stackoverflow.com/a/52671191
type: Question
has answer: http://stackoverflow.com/a/52669331
has comment: http://stackoverflow.com/comment/92268531
has comment: http://stackoverflow.com/comment/92268205
score: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/52669331

http://stackoverflow.com/comment/92333965
has text: I’d rename them to have lower dashes instead of spaces. It’s easier to check for lower dashes than to check for spaces. Sometimes a space is referred to as “\ “, so it’s easierto rely on a simpler character, such as “_”. You can then replace those with spaces in your game.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52703558
score: 0

http://stackoverflow.com/a/52595404
type: AcceptedAnswer
downvote count: 0
has body: This one might be a little hardcoded, but is probably more understandable for people who are just starting out in Python: import os import shutil # Enter the 'Project' folder os.chdir('C:\\Users\\Me\\Project') # Filter for folders that contain the word 'folder' folders = [folder for folder in os.listdir() if 'folder' in folder] for folder in folders: # Get the last letter of every folder suffix = folder[-1] # Build source and destination path for the csv files source = folder + '\\data.csv' dest = 'alldata\\data' + suffix + '.csv' shutil.move(source, dest)
type: Answer
accepted answer of: http://stackoverflow.com/q/52594852
answers question: http://stackoverflow.com/q/52594852
score: 1
upvote count: 1

http://stackoverflow.com/q/52649308
type: Question
tagged with: python
score: 0
has title: "\" Line break makes pandas dataframe columns reorder alphabetically
has answer: http://stackoverflow.com/a/52649934
has comment: http://stackoverflow.com/comment/92231264
has comment: http://stackoverflow.com/comment/92231491
accepted answer: http://stackoverflow.com/a/52649934
tagged with: pandas
has comment: http://stackoverflow.com/comment/92231054
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92231376
answer count: 1
has body: My code got too big, so I started using "\" for better readability. I've noticed however, that my columns got reorder alphabetically by doing this. Does anyone know how to stop this from happening? Here's the code: def unsettled_event(team_name,market): """Returns all bets tied to this specific event.""" combos_list = df[(df["home"] == team_name) \ &amp; (df["profit"].isnull()) \ &amp; (df["market"] == market) \ &amp; (df['settled_date']).isnull()].combo_id.dropna().unique() df_combos = df[df["combo_id"].isin(combos_list)].sort_values("combo_id") \ "combo_id", "home", "market", "odds", "selection", "bookmaker", "broker", "stake_adj", "is_won" df_singles = df[(df["home"] == team_name) \ &amp; (df["leg_size"] == 1) \ &amp; (df["profit"].isnull()) \ &amp; (df["market"] == market) \ &amp; (df['settled_date']).isnull()] \ "combo_id", "home", "market", "selection", "odds", "bookmaker", "broker", "stake_adj", "is_won" return pd.concat([df_singles, df_combos], ignore_index=True) So in the end, df.columns is returning: ['bookmaker', 'broker', 'combo_id', 'home', 'is_won', 'market', 'odds', 'selection', 'stake_adj'] And it should return: ["combo_id", "home", "market", "selection", "odds", "bookmaker", "broker", "stake_adj", "is_won"]
has comment: http://stackoverflow.com/comment/92231158

http://stackoverflow.com/q/52732128
type: Question
score: 2
tagged with: recurrent-neural-network
upvote count: 2
tagged with: deep-learning
favorite count: 0
tagged with: optimization
has title: Will gradient accumulate with multiple loss in RNNs?
tagged with: python
has body: Suppose I'm using pytorch for implementation. Say I have a RNN like model, which have a loss at every step: for step in step_cnts: output = rnn(input, hidden) loss = loss + criteria(output, target) When backward with loss.backward(), will gradient accumulate at every step of the RNN? And won't this accumulating leads to gradient explode? By the way, if I average the loss with loss = loss / step_cnts, will the gradient be different from the sum version?
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: gradient

http://stackoverflow.com/a/52615744
has body: Use list comprehension: In [1]: ll = [[] for x in range(5)] In [2]: ll Out[2]: [[], [], [], [], []]
answers question: http://stackoverflow.com/q/52615560
score: 0
type: Answer

http://stackoverflow.com/comment/92371030
has text: I want to filter all the journal objects which is created within the 'Start_Date' and the "End_Date" of the selectdate objects
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52722840
score: 0

http://stackoverflow.com/comment/92337834
has text: I am getting this error now 'generator' object has no attribute 'user'
comment on: http://stackoverflow.com/a/52703642
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52715613
accepted answer of: http://stackoverflow.com/q/52714532
has comment: http://stackoverflow.com/comment/92356947
answers question: http://stackoverflow.com/q/52714532
type: Answer
score: 2
upvote count: 2
has body: The infinite recursion is caused by the fact that the type constructor can return an instance of your metaclass. In this line here: interm_base = type(cname + 'Intermediate', bases, attrs) If any of the base classes in bases is an instance of TestType, then the subclass will also be an instance of TestType. That is why Test can be created with no problems, but SubTest causes infinite recursion. The fix is simple: Create the intermediate class without an __init__ attribute. That way if '__init__' in attrs: will be False, and the endless recursion is avoided. class TestType(type): def __new__(cls, cname, bases, attrs): # Dynamically create the __init__ function def init(self, message): self.message = message # If the __init__ method is being subclassed if '__init__' in attrs: # Create an intermediate class to become the base. interm_base = type(cname + 'Intermediate', bases, {}) # Add the intermediate class as our base. bases = (interm_base,) else: # Assign the created function as the __init__ method. attrs['__init__'] = init # Create the class. return super().__new__(cls, cname, bases, attrs)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52633208
answer count: 0
favorite count: 0
type: Question
has body: The html page consists if two forms of similar type and refers to same database. The form should take input details of a family of two. However after inputting and submitting the form, the older written objects in the database are erased and overwritten by the newly created objects. I want the objects to be created seperately. This is my index.html Fill the form below {% csrf_token %} Enter name {{ form.name }} Enter age {{ form.age }} Enter phone number {{ form.phone }} Enter name {{ form.name }} Enter age {{ form.age }} Enter phone number {{ form.phone }}
tagged with: python
has comment: http://stackoverflow.com/comment/92199961
has title: How to input data into different objects in the same database through forms on same html page?
has comment: http://stackoverflow.com/comment/92199830
score: 0
tagged with: django
upvote count: 1
downvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/125418208
comment on: http://stackoverflow.com/a/52608107
type: AnswerComment
score: 0
has text: @umbe1987 Did your `df` and `df_chicago` have the same coordinate reference system? If they had different CRSs, the points for one could, for example, be measured in degrees while the points for the other could be in meters from (0,0), which would cause points from one to fall far outside of the bounding polygon from the other. You can check via `df.crs` and `df_chicago.crs`, and if they're different, you can update the geometry in one via `df_chicago = df_chicago.to_crs(df.crs)`.
type: Comment

http://stackoverflow.com/comment/92184035
type: Comment
type: QuestionComment
has text: That's why I ask what do you want to do. Is this a one-off or infrequent call? Or a frequent prediction request? SQL Server 2017 can not only use Python scripts, it can compile prediction models created from them and use them in queries. Jupyter as a service is great, unless you have high traffic - it's not a web server after all
score: 0
comment on: http://stackoverflow.com/q/52624483

http://stackoverflow.com/q/52597237
score: 0
tagged with: db2
accepted answer: http://stackoverflow.com/a/52597313
has title: Anaconda: Despite of installing can't import ibm_db
type: AnsweredQuestion
tagged with: sql
has body: I am able to install ibm_dbpackage in order to access DB2 from Jupyter notebook: !pip install ibm_db Requirement already satisfied: ibm_db in /anaconda2/lib/python2.7/site-packages (2.0.9) but while trying to import there's an error: import ibm_db --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-2-fe3bb08c8a05&gt; in &lt;module&gt;() ----&gt; 1 import ibm_db ModuleNotFoundError: No module named 'ibm_db' Restarted the Kernel couple of times but it also had no impact. Anything that I am missing here? Update: Was able to resolve the issue by executing the below in Jupyter: !pip uninstall ibm_db and then !conda install ibm_db -c anacharsis
has answer: http://stackoverflow.com/a/52597313
type: Question
has answer: http://stackoverflow.com/a/62127105
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/62127105

http://stackoverflow.com/comment/129608080
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52637939
type: AnswerComment
has text: "If _wait is False_ then this method _will return immediately_ and the resources associated with the executor will be freed when all pending futures are done executing"

http://stackoverflow.com/comment/92209896
has text: @ElliottFrisch literally dying, well played my good sir
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52638534

http://stackoverflow.com/comment/132746148
comment on: http://stackoverflow.com/a/65316879
type: Comment
score: 1
has text: it doesn't work anymore
type: AnswerComment

http://stackoverflow.com/q/52685135
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52685149
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52743821
tagged with: latex
score: 0
has body: I have recently installed LaTeX2WP in order to create mathematical equations in an online blog. When testing latex2wp.py example.tex in the command prompt, the following error is returned C:\Latex2Wordpress>latex2wp.py DCT.tex Traceback (most recent call last): File "C:\Latex2Wordpress\latex2wp.py", line 657, in <module> s=extractbody(s) File "C:\Latex2Wordpress\latex2wp.py", line 153, in extractbody for i in range(1,(len(L)+1)/2) : TypeError: 'float' object cannot be interpreted as an integer The error is due to two lines in the latex2wp file provided by the download of LaTeX2WP. I think that I can adjust these two lines and fix the error message. I have pasted all of latex2wp below and bolded the two relevant lines: """ Copyright 2009 Luca Trevisan Additional contributors: Radu Grigore LaTeX2WP version 0.6.2 This file is part of LaTeX2WP, a program that converts a LaTeX document into a format that is ready to be copied and pasted into WordPress. You are free to redistribute and/or modify LaTeX2WP under the terms of the GNU General Public License (GPL), version 3 or (at your option) any later version. I hope you will find LaTeX2WP useful, but be advised that it comes WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details. You should have received a copy of the GNU General Public License along with LaTeX2WP. If you can't find it, see <http://www.gnu.org/licenses/>. """ import re from sys import argv from latex2wpstyle import * # prepare variables computed from the info in latex2wpstyle count = dict() for thm in ThmEnvs: count[T[thm]] = 0 count["section"] = count["subsection"] = count["equation"] = 0 ref={} endlatex = "&fg="+textcolor if HTML : endproof = " " inthm = "" """ At the beginning, the commands \$, \% and \& are temporarily replaced by placeholders (the second entry in each 4-tuple). At the end, The placeholders in text mode are replaced by the third entry, and the placeho…
tagged with: python
has title: Problem using LaTeX2WP with Python - TypeError: 'float' object cannot be interpreted as an integer
tagged with: integer
possible better answer: http://stackoverflow.com/a/52743821
accepted answer: http://stackoverflow.com/a/52685149

http://stackoverflow.com/a/52626794
upvote count: 2
score: 2
has body: It appears a deliberate decision in jsonpath-ng that if the sub does not change anything, the item is converted to None. I find this rather puzzling. As a workaround, you could append a + at the end of the string and then rewrite it with sub, which will now always modify it, not producing None.
accepted answer of: http://stackoverflow.com/q/52626356
answers question: http://stackoverflow.com/q/52626356
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92188803

http://stackoverflow.com/q/52711936
score: 1
has comment: http://stackoverflow.com/comment/92353405
tagged with: memory
has body: Does Python / Django save variables between page refresh? Here is my code: class Item(models.Model): id = models.AutoField(primary_key=True) _images_set = [] @csrf_exempt def get_products(request): item = Item() item._images_set.append('Yay') return HttpResponse(json_utilities.get_success()) Every time I refresh the page, and stop the debugging to inspect item, the _images_set grows by 1. I come from the PHP world, where every time a page reloads all the variables are reset. Could someone explain what is going on here? I don't want _images_set to just keep growing and growing, how do I tell Python / Django to reset all variables at each new page load?
downvote count: 0
has comment: http://stackoverflow.com/comment/92355590
favorite count: 0
has title: How do I prevent Python / Django from saving variables in memory between page refreshes?
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: middleware
type: Question

http://stackoverflow.com/comment/92306844
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52689985
has text: @roganjosh Given a list A of elements of length N, ranging from 0 to N. All elements may not be present in the array. If the element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is not present display -1 at that place.

http://stackoverflow.com/q/52634552
type: Question
has comment: http://stackoverflow.com/comment/134592093
has body: In python, when I try to use the requests library or any other library that requires connecting to the internet, the response comes extremely slow. Code as simple as the following can take 2 to 5 minutes. import requests requests.get('https://www.google.com') The same code finishes within 1 second on my Linux machine. If I use non-python method to achieve the same thing, i.e. curl curl 'https://www.google.com' The response comes in less than 1 second. What may be causing this? Where should I be looking? I don't know much about networking or Macs in general, so can someone help me debug with detailed instructions?
tagged with: network-programming
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92203116
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92202503
has title: MacOS High Sierra 10.13.6 -> Extremely Slow Requests Library
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17782142
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/92203840
score: 2
has comment: http://stackoverflow.com/comment/92202938
has answer: http://stackoverflow.com/a/52636754
upvote count: 2
tagged with: python-requests

http://stackoverflow.com/comment/124843701
score: 0
comment on: http://stackoverflow.com/a/52593889
type: AnswerComment
has text: how do i write typing if have multiple keys and values, with keys and values of different types for a dict like: `{'a':1, b'abc':[1.0,2.0,3.0],23:['x','y','z']}`.types are :"{str:int, bytes-string:list(floats), int: list(str)}"
type: Comment

http://stackoverflow.com/a/52722611
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52722520
answers question: http://stackoverflow.com/q/52722520
score: 3
type: AcceptedAnswer
downvote count: 1
type: Answer
has body: Iterate the list and keep index value which is not multiple of 3 [value for key,value in enumerate(x,1) if key%3!=0 ]

http://stackoverflow.com/q/52644307
tagged with: python
upvote count: 3
has title: How to use `bokeh.models.expressions`
has body: In bokeh 0.13.0, how to use expression to calculate a column value from another of a ColumnDataSource? According to the document, I should be able to do something like the following: from bokeh.core.properties import expr ds = ColumnDataSource(data={'a':[1,2,3]}) plot.circle(x='a', y=expr('a+1'), size=20, source=ds) But this does not work. They say "...will be computed ... using a ColumnDataSource as input". Unfortunately there is no any example showing how to use this input.
type: UnansweredQuestion
tagged with: bokeh
downvote count: 0
answer count: 0
favorite count: 0
type: Question
score: 3

http://stackoverflow.com/q/52683720
favorite count: 0
has comment: http://stackoverflow.com/comment/92296114
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/52684730
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92296043
tagged with: arduino
type: Question
has title: Sending data from python to Arduino throught serial port
has comment: http://stackoverflow.com/comment/92295504
has answer: http://stackoverflow.com/a/52684730
has comment: http://stackoverflow.com/comment/92297253
has comment: http://stackoverflow.com/comment/92295489
has comment: http://stackoverflow.com/comment/92296170
downvote count: 0
answer count: 1
has body: I'm trying to make Arduino trigger a relay if the char "s" is read on serial port. That char "s" is sent by python based on an image read from screen. My problem is that arduino seems not able to read from serial port as it never performs the if condition. My guess is that there is some kind of deadlock between the two (that's why I put ardu.close() in the function foo) This is my arduino code: char serial; #define RELAY1 7 void setup() { Serial.begin(9600); pinMode(RELAY1, OUTPUT); } void loop() { if(Serial.available() &gt; 0){ serial = Serial.read(); //Serial.print(serial); if(serial=='s'){ digitalWrite(RELAY1,0); Serial.println("Light ON"); delay(2000); digitalWrite(RELAY1,1); Serial.println("Light OFF"); delay(2000); } } } This is my python code: import time import serial #from serial import serial import cv2 import mss import numpy import pytesseract def foo(): print("sent") ardu= serial.Serial('COM6',9600, timeout=.1) time.sleep(1) ardu.write('s'.encode()) time.sleep(1) ardu.close() foo()
has comment: http://stackoverflow.com/comment/92306633

http://stackoverflow.com/q/52705423
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52705698
upvote count: 1
answer count: 1
has title: Match a value in the column and return another column in pandas | python
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52705698
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: string
has body: I have an input file1 of two columns(tab-separted): c1\tc2 aaa\t232 65 19 32 bbew\t32 22 20 jhsi\t986 1 32 463 221 And input file2 which have one column: c1 19 1 32 277 what I want is to search an element from file2 in file1, and return the corresponding value in c1. If there is more than one matched value, then return all together in one column. Here is what should the output file be like: 19 aaa 1 jhsi 32 aaa bbew jhsi 277 277 would be left empty because it does not exist. Any suggestion will be helpful.
favorite count: 0

http://stackoverflow.com/comment/92294588
type: Comment
has text: the command "if not enemy:" is useless... it is already inside of an 'else' that only gets executed whenever enemy is not a valid value... the error is due to the mis-indentation, simply delete this 'if' inside the 'else' and i'm pretty sure it will work
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52683142

http://stackoverflow.com/a/52636390
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52636288
has body: Move to flat indexing and use np.bincount. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; coords = [(0, 0), (1, 1), (0, 0)] &gt;&gt;&gt; &gt;&gt;&gt; shp = np.max(coords, axis=0) + 1 &gt;&gt;&gt; flt = np.ravel_multi_index(np.moveaxis(coords, -1, 0), shp) &gt;&gt;&gt; result = np.bincount(flt, minlength=shp.prod()).reshape(shp) &gt;&gt;&gt; &gt;&gt;&gt; result array([[2, 0], [0, 1]]) EDIT As pointed out by @MikeMiller moveaxis is overkill here; np.transpose(coords) or if coords happen to be an array coords.T is better. moveaxis would be more general if coords were for some reason more than 2D but that doesn't look like a likely scenario.
type: Answer
answers question: http://stackoverflow.com/q/52636288
score: 3
has comment: http://stackoverflow.com/comment/92206865
has comment: http://stackoverflow.com/comment/92206579
has comment: http://stackoverflow.com/comment/92226578

http://stackoverflow.com/q/52691196
tagged with: batch-file
tagged with: windows
answer count: 1
has answer: http://stackoverflow.com/a/52691255
has title: Get a variable as filename from python script and use it in a batch script
tagged with: python
favorite count: 0
type: AnsweredQuestion
upvote count: 0
has body: I have a python script which gives the output as: The lastest filename of a directory. I want to use this filename in a batch script. How can i able to do it?
type: Question
downvote count: 2
score: -2
accepted answer: http://stackoverflow.com/a/52691255

http://stackoverflow.com/comment/92358030
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52716268
has text: WindowsError: [Error 2] The system cannot find the file specified
type: AnswerComment

http://stackoverflow.com/a/52698389
has body: Change username = form.cleaned_data['username'] to username = form.cleaned_data['username'].lower()
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52698322

http://stackoverflow.com/a/52727053
downvote count: 0
answers question: http://stackoverflow.com/q/52726818
type: Answer
has body: You're trying to add an entire list of emails as a single entry in the set. What you want is to add the actual emails each one in a separate set entry. The problem is in this line: allLinks.add(results) It adds the entire results list as a single element in the set and that doesn't work. Use this instead: allLinks.update(results) This will update the set with elements from the list, but each element will be a separate entry in the set.
score: 1
upvote count: 1

http://stackoverflow.com/q/52642283
type: AnsweredQuestion
has title: matplotlib: change active axes
has body: I have multiple objects that visualize different things. They all are passed a reference to a single Figure instance and create their own axes objects (only one of them is active at the same time) Code for demonstration would be: import numpy as np import matplotlib.pyplot as plt # the visualization objects are jupyter widgets in production code %matplotlib widget plt.ioff() def update_fig(f): f.canvas.draw() f.canvas.flush_events() f = plt.figure() # first visualizer is created and plots into the figure ax1 = f.add_subplot(1,1,1, label="visualizer_1") img1 = np.random.randint(0, 256, (20, 20, 3)) vis1 = ax1.imshow(img1) update_fig(f) # second visualizer is created and plots into the figure ax2 = f.add_subplot(1,1,1, label="visualizer_2") vis2 = ax2.plot(np.linspace(0, 5), 2 * np.linspace(0, 5)) update_fig(f) How can I then switch which axes to show in the plot? Already tried plt.sca(ax1) to go back to the first visualization but that did not work. Of course I could use a different figure for each visualization object but since I have many of them, I would rather avoid that.
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52643544
tagged with: matplotlib
score: -1
has answer: http://stackoverflow.com/a/52643544
has comment: http://stackoverflow.com/comment/92218146
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92218666
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/92273654
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52671447
has text: @Daniel R. I have looked at uncertainties and they don't handle "pint quantities" (I think) - so that would mean that pint would somehow have to make sense of uncertainties' measurement class.

http://stackoverflow.com/q/52600048
possible better answer: http://stackoverflow.com/a/52600093
favorite count: 0
has answer: http://stackoverflow.com/a/52600093
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/52600218
score: 2
type: AnsweredQuestion
upvote count: 3
has body: Good day. I am using Pygame with Python 3.6.5. Here's my code: if event.type == pygame.KEYDOWN: if pygame.key == pygame.K_UP: my_change = -15 my += my_change pygame.display.update() clock.tick(24) My problem is, that when I add running = True while running: To the top of that code, and then run it, my window just stops responding, even though I added just, like, 2 lines of code! P.S: I have no code to break out of this yet. Could this be one possible reason for this? I do de-indent later on in the code, though, so it only runs for a short period of time. Also: This is all actually in my main game loop. Also: My sprite, Super Mario, just falls right through my ground. Any help or ideas on this and/or how to fix this issue? Thanks!!!
downvote count: 1
has comment: http://stackoverflow.com/comment/92134596
type: Question
has title: Pygame Python window stops responding
has comment: http://stackoverflow.com/comment/92134628
has comment: http://stackoverflow.com/comment/92134605
accepted answer: http://stackoverflow.com/a/52600218
answer count: 2
has comment: http://stackoverflow.com/comment/92134636

http://stackoverflow.com/comment/92355292
type: AnswerComment
score: 0
type: Comment
has text: Right, I fixed my answer - it should should be **MessageSerializer**. Please accept the answer
comment on: http://stackoverflow.com/a/52702708

http://stackoverflow.com/a/52613987
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52613887
has body: Give it a test! &gt;&gt;&gt; sample_list = [1, 2, 3] &gt;&gt;&gt; sample_list[True] 2 &gt;&gt;&gt; sample_list[False] 1 I believe you can deduct the fact that True is equivalent to 1 and False is equivalent to 0. Additional test: &gt;&gt;&gt; False == 0 True &gt;&gt;&gt; True == 1 True I believe this would help.

http://stackoverflow.com/comment/92368399
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52721099
score: 0
has text: never mind. i misread the question.

http://stackoverflow.com/comment/92183597
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52625051
has text: ... and your problem is?
type: Comment

http://stackoverflow.com/q/52646089
tagged with: tkinter
possible better answer: http://stackoverflow.com/a/52646439
has answer: http://stackoverflow.com/a/52646439
type: Question
has comment: http://stackoverflow.com/comment/92224392
has body: I am programming in spyder 3.2.8; python 3.6 using tkinter. Set up my whole script and used pyinstaller to develop an application. In my script I want to include the function iconbitmap(''). The problem is once I do this I specify an image path and when I develop the application it creates an error when I move the application to another PC. I know why this error occurs. It is because the file path specified does not exist on the new PC. I want to change the widget icon with that function. It works like I said in my script, but once I develop and transfer from one pc to another it can not find the image in question and hence creates the problem. This is the specific part of the code I am trying to run: window= tk.Tk() window.title("Heating Requirement") window.geometry("650x275") window.iconbitmap(r'LOGO.ico') As you can see it is simple but path dependent. In my script it runs perfectly. The problem however is as stated above with the image being path dependent. Is there a way to tell pyinstaller to change the iconbitmap instead of doing it in the script which makes it path dependent.... If you tell pyinstaller to change the application icon it is not path dependent as it incorporates the image to the build. I want pyinstaller to incorporate the iconbitimage to the build as well. Is there perhaps an external way to change the iconbitimage. Meaning outside of the script? Is there a way to permanently change the iconbitimage in tkinter?
tagged with: icons
has title: How to load a path independent image into python tkinter making the executable independent from the image path?
score: 0
answer count: 2
tagged with: spyder
has comment: http://stackoverflow.com/comment/92224521
has comment: http://stackoverflow.com/comment/92224776
has answer: http://stackoverflow.com/a/53011870
accepted answer: http://stackoverflow.com/a/53011870
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/92442501
has text: Thanks very much to you both who answered my question. Indeed, I didn´t notice I had defined the global categorias_gastos twice. I fixed that and it partially solved the problem.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52743126

http://stackoverflow.com/q/52618428
has answer: http://stackoverflow.com/a/52619183
has title: A question about Python OOP __init__ method
downvote count: 3
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92171165
has comment: http://stackoverflow.com/comment/92171338
tagged with: oop
has comment: http://stackoverflow.com/comment/92171712
accepted answer: http://stackoverflow.com/a/52619183
has comment: http://stackoverflow.com/comment/92205083
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92171159
has body: I have a short question about Python OOP's __init__ method and is here for help. Let's say I have a module called basic_backend.py which has the following code: items = list() def create_items(app_items): global items items = app_items Then I have another MVC module, in which I wrote: import basic_backend class ModelBasic(object): def __init__(self, app_items): self._item_type = 'product' self.create_items(app_items) My question is, in the __init__ method, I was able to use self to call the function from an imported module. Why am I able to do this please? I am not sure about the theory behind this. Guru please help! Thanks a lot!
tagged with: python
score: -2

http://stackoverflow.com/a/52599153
type: Answer
has comment: http://stackoverflow.com/comment/92133053
has body: You can try this: def list_of_tuples(n, m): return set(tuple(sorted(tup)) for tup in product(range(1,m+1), repeat = n)) For n=3 and m=2, it results in: {(1, 2, 2), (2, 2, 2), (1, 1, 1), (1, 1, 2)} This is not very efficient, though, but perhaps this does not matter.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52599029

http://stackoverflow.com/q/52610492
tagged with: python
has comment: http://stackoverflow.com/comment/92156464
tagged with: jupyter-notebook
has body: So, I tried running this code in both Jupyter and Spyder. It gave me the correct output in the Jupyter notebook but showed be TypeError: 'str' object is not callable in Spyder. Please explain why is it happening. Also, I tried writing float(guess) in the call function but still didn't work. x = 25 epsilon = 0.01 step = 0.1 guess = 0.0 while abs(guess**2-x) &gt;= epsilon: if guess &lt;= x: guess += step else: break if abs(guess**2 - x) &gt;= epsilon: print('failed') else: print('succeeded: ' + str(guess))
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92155425
has comment: http://stackoverflow.com/comment/92156187
type: Question
has title: Why does a code work in Jupyter and doesn't work in Spyder?
has comment: http://stackoverflow.com/comment/92155461
has comment: http://stackoverflow.com/comment/92156414
has comment: http://stackoverflow.com/comment/92155365
has comment: http://stackoverflow.com/comment/92155264
has comment: http://stackoverflow.com/comment/92156311
linked to: http://stackoverflow.com/q/47738537
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92155379
has comment: http://stackoverflow.com/comment/92206621
tagged with: spyder

http://stackoverflow.com/a/52619174
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52619148
answers question: http://stackoverflow.com/q/52619148
score: 3
type: Answer
has body: It will work only once, because after that, python is done reading the file (here's a question that discusses this in detail). Read it once and store it in a variable: &gt;&gt;&gt; f = open("C:\\Users\\vivrd\\Desktop\\testing.txt") &gt;&gt;&gt; items = f.readlines() # items should now be a list of lines in the file &gt;&gt;&gt; f.close() # make sure to close the file If you want to re-read, move the 'cursor' back to the beginning of the file (before closing) using seek: &gt;&gt;&gt; items = f.readlines() &gt;&gt;&gt; f.seek(0) &gt;&gt;&gt; more_items = f.readlines() &gt;&gt;&gt; f.close()

http://stackoverflow.com/comment/92275487
has text: Please create a [mcve].
type: QuestionComment
comment on: http://stackoverflow.com/q/52672817
score: 1
type: Comment

http://stackoverflow.com/q/52723523
has body: I need to make a filter for pandoc to hide some specific div in my markdown document. I try to understand how filters works, but I can't understand it. I try this filters which contains some code I need to use : https://github.com/chdemko/pandoc-latex-environment/blob/master/pandoc_latex_environment.py but it fails : $ pandoc myFile.md -t json | python3 pandoc_latex_environment.py Traceback (most recent call last): File "test.py", line 56, in &lt;module&gt; main() File "test.py", line 53, in main toJSONFilters([environment]) File "/usr/lib/python3/dist-packages/pandocfilters.py", line 76, in toJSONFilters altered = reduce(lambda x, action: walk(x, action, format, doc[0]['unMeta']), actions, doc) File "/usr/lib/python3/dist-packages/pandocfilters.py", line 76, in &lt;lambda&gt; altered = reduce(lambda x, action: walk(x, action, format, doc[0]['unMeta']), actions, doc) KeyError: 0 My question is : how can I make a python filter for pandoc which delete all div with class "hidden". Thanks. Sorry for my bad english.
has answer: http://stackoverflow.com/a/52747578
downvote count: 4
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92433609
score: -3
tagged with: python
type: UnansweredQuestion
upvote count: 1
tagged with: pandoc
has title: pandoc filter to hide div of a certain class
type: Question

http://stackoverflow.com/comment/92351327
comment on: http://stackoverflow.com/q/52712731
type: Comment
has text: `sent2` seems like a list of list, whereas `nltk.ne_chunk()` accepts a list
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92277838
comment on: http://stackoverflow.com/q/52674103
has text: I have fixed the issue from that answer. I am looking for why it is happening after uploading more than 10 pics and what about my view. Is this the right way to do?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92234514
type: Comment
type: QuestionComment
has text: I have edited the code above with the changes and typecasting.Still the result is the same dataframe with no formatting. @G.Anderson
comment on: http://stackoverflow.com/q/52650646
score: 0

http://stackoverflow.com/q/52739526
type: Question
has comment: http://stackoverflow.com/comment/92403540
tagged with: concurrency
has comment: http://stackoverflow.com/comment/92404795
score: 0
has comment: http://stackoverflow.com/comment/92403972
answer count: 1
has comment: http://stackoverflow.com/comment/92404051
has comment: http://stackoverflow.com/comment/92403605
has comment: http://stackoverflow.com/comment/92403580
has body: I am trying to use ProcessPoolExecutor from Python concurrent.futures package. However, I achieve very poor performance and I cannot understand why. My code looks like this: import time from itertools import product from concurrent.futures import ProcessPoolExecutor def myfunc(bundle): "A simple function which takes some time to complete." clock_start = time.clock() for _ in range(*bundle): lst = [[0., 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 1.0] for x in range(6)] res = [t for t in product(*lst) if abs(sum(t) - 1.) &lt; 1e-8] clock_elapsed = time.clock() - clock_start return clock_elapsed def parallel(bundles, nworkers): "A function to dispatch execution between different workers." with ProcessPoolExecutor(max_workers=nworkers) as executor: execgen = executor.map(myfunc, bundles) total_clock = 0. for _clock in execgen: total_clock += _clock print("mean iteration: {:.3f} s".format(total_clock / bundles[-1][-1])) (The function myfunc has no interest as such but I expect the execution to be linear in the number of iterations). When I test this code on my computer (Python 3.6, Debian, 8 CPU), I get the following results: &gt;&gt;&gt; parallel([(0, 60)], 1) mean iteration: 3.660 s &gt;&gt;&gt; parallel([(0, 30), (30, 60)], 2) mean iteration: 3.747 s &gt;&gt;&gt; parallel([(0, 20), (20, 40), (40, 60)], 3) mean iteration: 4.413 s &gt;&gt;&gt; parallel([(0, 10), (10, 20), (20, 30), (30, 40), (40, 50), (50, 60)], 6) mean iteration: 7.534 s So, apparently, dividing the execution between 6 workers means that one iteration takes in average twice as much time as it takes with one worker. Since the iteration should be completely independant, I cannot figure out why this is the case?
tagged with: python
has comment: http://stackoverflow.com/comment/92405030
has comment: http://stackoverflow.com/comment/92403927
type: UnansweredQuestion
has title: Unexpected performance when using a ProcessPool in Python
linked to: http://stackoverflow.com/q/45256953
has answer: http://stackoverflow.com/a/55756561

http://stackoverflow.com/q/52684961
tagged with: python-3.6
answer count: 2
has body: I am trying to use pandas to rename a column in CSV files. I want to use a dictionary since sometimes columns with the same information can be named differently (e.g. mobile_phone and telephone instead of phone). I want to rename the first instance of phone. Here is an example to hopefully explain more. Here is the original in this example: 0 name mobile_phone telephone 1 Bob 12364234234 12364234234 2 Joe 23534235435 43564564563 3 Jill 34573474563 78098080807 Here is what I want it to do: 0 name phone telephone 1 Bob 12364234234 12364234234 2 Joe 23534235435 43564564563 3 Jill 34573474563 78098080807 This is the code I tried: phone_dict = { 'phone_number': 'phone', 'mobile_phone': 'phone', 'telephone': 'phone', 'phones': 'phone', } if 'phone' not in df.columns: df.rename(columns=dict(phone_dict), inplace=True) if 'phone' not in df.columns: raise ValueError("What are these peoples numbers!? (Need 'phone' column)") I made a dictionary with some possible column names and that I want them to be named 'phone'. However, when I run this code it turns the columns to this changes the second column instead of the first one that matches a key in the dictionary. I want it to stop after it matches the first column it comes across in the CSV. This is what is happening: 0 name mobile_phone phone 1 Bob 12364234234 12364234234 2 Joe 23534235435 43564564563 3 Jill 34573474563 78098080807 If there is, for example, a third column that matches the dictionary they turn to 'phone' which is again not what I want. I am trying to get it to just change the first column it matches. Here is an example of what happens when I add a third column. It goes from: 0 name mobile_phone telephone phone_1 1 Bob 12364234234 12364234234 36346346311 2 Joe 23534235435 43564564563 34634634623 3 Jill 34573474563 78098080807 34634654622 To this: 0 name phone phone phone 1 Bob 12364234234 12364234234 36346346311 2 Joe 23534235435 43564564563 34634634623 3 Jill 34573474563 78098080807 34634654622 But I want it to …
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52685004
favorite count: 0
has answer: http://stackoverflow.com/a/52685004
upvote count: 1
tagged with: python
tagged with: dictionary
tagged with: indexing
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52685012
type: Question
accepted answer: http://stackoverflow.com/a/52685012
has title: Pandas - Rename only first dictionary match instead of last match
downvote count: 0

http://stackoverflow.com/q/52645557
tagged with: type-conversion
answer count: 1
has answer: http://stackoverflow.com/a/52646256
tagged with: tkinter
has title: Type conversion in python (StringVar to String)
type: UnansweredQuestion
has body: I wanted to convert StringVar into String in Python. Aim : String entered in Entry field (tkinter) must be converted to String and then encoded to get the hash of it. Below is my code: txt1 = StringVar() scantxt = ttk.Entry(win, textvariable = txt1).pack() txt1 = str(txt1.get()).encode() sha256 = hashlib.sha256(txt1) estr = sha256.hexdigest() The result I'm getting is hash of blank text. I don't know where I'm going wrong. Please assist. Thank you for anticipated help.
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92223584
score: 1
type: Question
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/92184109
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52614547
has text: Thank you very much, the sample example helped me a lot to understand what driver means! Will test around with these piece of code! :-)
type: Comment

http://stackoverflow.com/q/52631469
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has body: I'm scraping urls from a site but only the first request needs of selenium and the other don't. Is it possible to turn off Selenium in the middle of scrap process? I want do that, because, as you probably now, Selenium slows down a lot the scrap process. This is the code for the Spider: class StoreSpider(scrapy.Spider): name = 'store' allowed_domains = ['www.store.com.br'] custom_settings = { 'COLLECTION_NAME' : 'store', 'URLS_COLLECTION_NAME' : 'store_urls', 'USES_SELENIUM' : True, 'HEADLESS' : True, 'DOWNLOADER_MIDDLEWARES': { 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90, 'navigator.middlewares.SeleniumMiddleware': 700, } } categories_le = LinkExtractor(restrict_xpaths="//li[@class='h3']/a[not(@id)]") def start_requests(self): urls = [ 'https://www.store.com.br/loja/mapa-do-site', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse_categories)
downvote count: 0
tagged with: selenium
tagged with: scrapy
has title: Scrapy - Disable Selenium after first request
type: Question
has answer: http://stackoverflow.com/a/52633951
upvote count: 2

http://stackoverflow.com/comment/92274872
type: AnswerComment
comment on: http://stackoverflow.com/a/52672362
type: Comment
has text: @JosephNolan I improved my answer; it should cover your use case now, but with less code than you have.
score: 0

http://stackoverflow.com/comment/92160150
type: QuestionComment
has text: I also have pycryptodome install version 3.6.6 should i remove pycrypto?
comment on: http://stackoverflow.com/q/52612685
score: 0
type: Comment

http://stackoverflow.com/comment/92206481
type: QuestionComment
comment on: http://stackoverflow.com/q/52596340
has text: Did an answer below help? If so, feel free to [accept](https://stackoverflow.com/help/accepted-answer), or ask for clarification.
score: 0
type: Comment

http://stackoverflow.com/q/52684066
has answer: http://stackoverflow.com/a/52684088
has body: why append method works on original numbers list and it changed numbers list but I can't reassign numbers list to [4,5,6]? def change(numbers_list): numbers_list.append(4) numbers_list = [4,5,6] numbers = [1,2,3] change(numbers) print(numbers) when code runs this printed: [1,2,3,4] why not [4,5,6]?
score: 0
has comment: http://stackoverflow.com/comment/92308285
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92296283
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Python functions parameter
downvote count: 1
type: Question

http://stackoverflow.com/comment/92490438
has text: Renato: That link is to download something named `pdftotext.exe`, not `textextract.exe`—so I don't understand why you posted it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52730667

http://stackoverflow.com/q/52742553
upvote count: 2
has title: Get timestamp of video frame using VapourSynth ffms2 plugin
tagged with: vapoursynth
score: 2
type: AnsweredQuestion
type: Question
has body: I'm using this snippet as video source to mess with it later: import vapoursynth as vs core = vs.core core.std.LoadPlugin("/usr/local/lib/libffms2.so") video = core.ffms2.Source("videotest.mkv") How can i get timestamp of specified frame or get list of timestamps for every frame?
downvote count: 0
has answer: http://stackoverflow.com/a/52749556
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52749556
favorite count: 0

http://stackoverflow.com/comment/92159792
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52612423
has text: https://stackoverflow.com/questions/21129020/how-to-fix-unicodedecodeerror-ascii-codec-cant-decode-byte

http://stackoverflow.com/comment/92284943
comment on: http://stackoverflow.com/a/52678019
type: AnswerComment
type: Comment
score: 1
has text: Sorry I might not have written that clearly, I will make an edit. I meant to say I have a function which processes one word. This means when I want to process both words, I have to call the function twice.

http://stackoverflow.com/comment/92232090
type: Comment
has text: **UPDATE** I have managed to get data row wise into a list and grouped them in groups of 4 (as i need it). Now how do I keep the elements with values other than ' '?
comment on: http://stackoverflow.com/a/52640352
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92405594
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/52740357
has text: Note: In the current pygame release, `Vector2` is also avaible at `pygame.Vector2` in addition to `pygame.math.Vector2`

http://stackoverflow.com/a/52746594
type: Answer
has body: Provided that the zip object is created correctly, you can either do list(zip_object) or [*zip_object] to get the list.
score: 0
answers question: http://stackoverflow.com/q/52746519

http://stackoverflow.com/comment/92315059
type: AnswerComment
comment on: http://stackoverflow.com/a/52685835
has text: and every thing else just stays the same?
type: Comment
score: 0

http://stackoverflow.com/a/52672910
type: Answer
answers question: http://stackoverflow.com/q/52667854
has body: Looks like I've hit a known issue in pipenv: https://github.com/pypa/pipenv/issues/2596 and I'm not the only person to hit it when installing airflow: https://github.com/pypa/pipenv/issues/2596#issuecomment-427389166 Will wait to see if that issue gets resolved.
accepted answer of: http://stackoverflow.com/q/52667854
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52742410
downvote count: 0
type: Answer
score: 3
upvote count: 3
has body: I've got it working. I needed to run pkg install openssl and then I was able to build and install using the defaults (ie following Attempt #2)
answers question: http://stackoverflow.com/q/52741580

http://stackoverflow.com/q/52652684
tagged with: python
has answer: http://stackoverflow.com/a/52652731
score: -1
tagged with: selenium-chromedriver
linked to: http://stackoverflow.com/q/47944349
tagged with: selenium
downvote count: 1
answer count: 1
has body: I think my question is somehow related to this post Selenium - cannot click on an element inside a modal I click on a an element and it opens a modal table. Then, I would like to select a particular checknox in a long list but Selenium gives me back an error. That's what I did: I tested first with Selenium IDE: first I recorded the operations but when I try to replay them in the log I get this: Running 'Step2_sele' 1.open on /reserve-space/... OK 2.click on css=a[title="Locations"] &gt; span... OK 3.click on linkText=Add/Remove Locations... OK 4.Trying to find xpath=//input[@value='2427']... Failed: Element is not currently visible and may not be manipulated I thought I should have given more time to the element to show up and I wrote this with Python browser = webdriver.Chrome() browser.get(url_res) time.sleep(10) browser.find_element_by_css_selector('a[title="Locations"]&gt;span').click() time.sleep(10) browser.find_element_by_css_selector('a.dynamic-filter-item-add.summary').click() time.sleep(10) browser.find_element_by_xpath("xpath=//input[@value='2427']").click() But I get this other error Traceback (most recent call last): File "bot.py", line 69, in &lt;module&gt; browser.find_element_by_xpath("xpath=//input[@value='2427']").click() File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 393, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 966, in find_element 'value': value})['value'] File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression xpath=//input…
accepted answer: http://stackoverflow.com/a/52652731
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/92242152
has comment: http://stackoverflow.com/comment/92237192
has title: Selenium-python2.7: click on a modal table checkbox (following Selenium IDE)
favorite count: 0
tagged with: selenium-ide
type: Question

http://stackoverflow.com/comment/92343194
has text: @cricket_007: I did what you suggested but I keep getting the same error this time for the `result =` line. I included the exception above.
comment on: http://stackoverflow.com/q/52695236
score: 0
type: Comment
type: QuestionComment

servo
tags question: http://stackoverflow.com/q/52657809
type: Tag
tag name: servo

http://stackoverflow.com/q/52709872
type: Question
score: 3
has answer: http://stackoverflow.com/a/52710621
tagged with: for-loop
answer count: 3
has title: Faster way to combine date, hour, and interval columns for large dataset
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52710455
downvote count: 0
possible better answer: http://stackoverflow.com/a/52709943
has answer: http://stackoverflow.com/a/52709943
favorite count: 0
tagged with: series
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has body: I currently have a dataset of about 1.2 million rows that contains date, hour, and interval (quarter of hour) columns. Delivery Date Delivery Hour Delivery Interval 1-1-2017 1 1 1-1-2017 1 2 1-1-2017 1 3 1-1-2017 1 4 I currently have a for loop that will combine these columns into the one but I am looking for a faster approach as this will take hours to finish running. for i in range(len(df_rt['Delivery Interval'])): hour = int(df_rt['Delivery Hour'][i]) - 1 minute = (int(df_rt['Delivery Interval'][i]) - 1)*15 df_rt['Time'][i] = str(hour) + ':' + str(minute) df_rt['DateTime'] = df_rt['Delivery Date'] + " " + df_rt['Time'] df_rt['DateTime'] = pd.to_datetime(df_rt['DateTime'])
upvote count: 3
has answer: http://stackoverflow.com/a/52710455

http://stackoverflow.com/q/52674498
has answer: http://stackoverflow.com/a/52674694
type: Question
tagged with: scikit-learn
score: 0
answer count: 1
tagged with: python
has body: I have been working on a model using sklearn and a big part of it utilizes the CountVectorizer() function to create a sparse matrix from a set of strings in the training set. ex: vectorizer = CountVectorizer(max_features=3000) sparse_matrix = vectorizer.fit_transform(corpus).toarray() After exporting the model, whats the best way to format the data I would like to create a prediction on to match the feature names created by the training? Should I be exporting (via pickle?) vectorizer.get_feature_names() as well and then use that? Or is there a better way? In other words, if in my training set vectorizer.get_feature_names() = ['apple', 'dog', 'cat'] and I would like to make a prediction on 'hello cat', what should my method for feature extraction on the prediction request be? Correct me if Im wrong, but result of the feature extraction would need to be [0, 0, 1] to match the model. I could also be totally off on my approach here as well, so any help or suggestions are appreciated Thanks!
has title: recreating sparse matrix columns for ML model predictions
type: UnansweredQuestion
tagged with: machine-learning

http://stackoverflow.com/q/52640981
has body: Good morning, I have a string that I need to parse and print the content of two named group knowing that one might not exist. The string looks like this (basically content of /proc/pid/cmdline): """ &lt;some chars with letters / numbers / space / punctuation&gt; /CLASS_NAME:myapp.server.starter.StarterHome /PARAM_XX:value_XX /PARAM_XX:value_XX /CONFIG_FILE:myapp.server.config.myconfig.txt /PARAM_XX:value_XX /PARAM_XX:value_XX /PARAM_XX:value_XX &lt;some chars with letters / numbers / space / punctuation&gt; """ my processes have almost the same pattern, that is: /CLASS_NAME:myapp.server.starter.StarterHome is always present, but /CONFIG_FILE:myapp.server.config.myconfig.txt is NOT always present. I'm using python2 with re module to catch the values. So far my pattern looks like this and I'm able to catch the value I want corresponding to /CLASS_NAME re.compile('CLASS_NAME:\w+\W\w+\W\w+\W(?P&lt;class&gt;\w+)') The because /CONFIG_FILE is present or not, I added the following to myregexp: re.compile(r"""CLASS_NAME:\w+\W\w+\W\w+\W(?P&lt;class&gt;\w+).*? (CONFIG_FILE:\w+\W\w+\W\w+\W(?P&lt;cnf&gt;\w+.txt))? """, re.X) My understanding is that the second part of my rexexp is optional because the whole part is between parenthesis followed by ?. Unfortunately my assumption is wrong as it couldn't catch it I also tried by removing the 1st ? but it didn't help. I gave several tries through PYTHEX to try to understand my regexp but couldn't find a solution. Could anyone have any suggestion to resolve my case?
tagged with: named
favorite count: 0
has answer: http://stackoverflow.com/a/52641104
tagged with: grouping
tagged with: regex
tagged with: python
downvote count: 1
accepted answer: http://stackoverflow.com/a/52641104
type: AnsweredQuestion
score: 3
type: Question
upvote count: 4
has title: regex named group if exist
answer count: 1

http://stackoverflow.com/q/52693042
tagged with: pip
tagged with: python
type: AnsweredQuestion
tagged with: installation
tagged with: pypi
type: Question
has answer: http://stackoverflow.com/a/52693464
score: 0
has title: Python CLI application does not run when installed from PyPI, runs fine when installed locally
answer count: 1
has comment: http://stackoverflow.com/comment/92312899
has comment: http://stackoverflow.com/comment/92312915
accepted answer: http://stackoverflow.com/a/52693464
has body: Say I'm working on a command line application called Example, where its invocation command is example. I wrote a setup.py that looks like this: import setuptools setuptools.setup( name='example', version='1.0', entry_points = { 'console_scripts': [ 'example=example.run:main' ] }, ... ) This file is placed at the same level as a module called example (with its __init__.py and all. There is a run.py inside it, with a main function. When I install this work-in-progress project as a symlink using... pip3 install -e . ... it works fine. I am able to run it from anywhere using the example command. But when I follow these instructions to upload it to PyPI, then install it using... pip3 install example ... it says... Traceback (most recent call last): File "/usr/local/bin/example", line 7, in &lt;module&gt; from example.run import main ModuleNotFoundError: No module named 'example' Of course the project is not actually called example; there's nothing conflicting with its name.

http://stackoverflow.com/comment/92172004
type: Comment
score: 0
has text: Perhaps, however, I am able to run other similar commands to product the same output as the original command itself. Please see my edit, as I describe the latter further. Can you post how you would fix the `Popen` call?
type: AnswerComment
comment on: http://stackoverflow.com/a/52618937

http://stackoverflow.com/a/52622041
downvote count: 0
has body: I believe you need remove missing values and for last row - added double [] for one row DataFrame: df=pd.concat([price.reset_index(drop=True), quantity"a","b","c".dropna(subset=['c']).iloc[[-1]].reset_index(drop=True)], axis=1) print (df) price a b c 0 34 7 5 9.0 Detail: print (quantity"a","b","c".dropna().iloc[[-1]]) a b c 2 7 5 9.0
type: Answer
answers question: http://stackoverflow.com/q/52621628
upvote count: 1
score: 1

http://stackoverflow.com/comment/92188163
type: Comment
type: QuestionComment
has text: Why `False` for `16`? That character is between two `$` characters. Please be explicit about how `\$` means the position is escaped.
comment on: http://stackoverflow.com/q/52627316
score: 0

http://stackoverflow.com/comment/92338380
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52705870
has text: Cannot reproduce your problem under either Python 2.7 or 3.4.5

http://stackoverflow.com/a/52728577
answers question: http://stackoverflow.com/q/52725076
has body: Question: I want to parse the data into column Note: The simple regex will split on - and / also. If you expand the regex to your needs, this could be avoided. import re rc = re.compile(r'(\w+)') with open('C:/Users/DEMO/Documents/statement-9-28-18.csv', 'r') as itxt: for n, line in enumerate(itxt.readline(), 1): # Row 13 and 14 hold the Header if n in [13, 14]: findall = re.findall(rc, line) print("{}".format(findall)) if n &gt;= 16 and n%3 &gt; 0: findall = re.findall(rc, line) print("{}".format(findall)) Output: ['ACCOUNT', 'SERVICE', 'ADDRESS', 'CITY', 'DATE', 'DAY', 'C', 'KWH', 'KWD', 'AMOUNT'] ['RATE', 'CODE', 'CY', 'CUSTOMER', 'NAME', 'MAILING', 'ADDRESS'] ['11111', '22222', '485', 'JOHNSON', 'AVE', 'APT', '1405', 'MIAMI', '09', '26', '18', '28', 'C', '140', '29', '11', 'BAT0123'] ['RS', '1', 'XYZ', 'COMPANY', '485', 'JOHNSON', 'AVE'] ['22222', '33333', '485', 'JOHNSON', 'AVE', 'APT', '3541', 'MIAMI', '09', '26', '18', '28', 'C', '130', '28', '08', 'BAT0123'] ['RS', '1', 'XYZ', 'COMPANY', '485', 'JOHNSON', 'AVE'] ['33333', '44444', '485', 'JOHNSON', 'AVE', 'APT', '4544', 'MIAMI', '09', '26', '18', '28', 'C', '172', '32', '42', 'BAT0123'] ['RS', '1', 'XYZ', 'COMPANY', '485', 'JOHNSON', 'AVE'] ['55555', '66666', '485', 'JOHNSON', 'ST', 'AVE', 'APT', '1111', 'MIAMI', '09', '26', '18', '28', 'C', '243', '39', '81', 'BAT0123'] ['RS', '1', 'XYZ', 'COMPANY', '485', 'JOHNSON', 'AVE'] Tested with Python: 3.4.2
score: 0
type: Answer

http://stackoverflow.com/a/52750167
answers question: http://stackoverflow.com/q/52638844
upvote count: 2
type: Answer
score: 2
has body: I was able to solve it by just changing the kernel. I don't know how kernel affects when your trying to import a module, but it worked for me.
accepted answer of: http://stackoverflow.com/q/52638844
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92361612
type: QuestionComment
has text: "I'm not sure how to use this website": well, welcome to Stack Overflow then! As you are experiencing problems, I'd suggest you *at least* read the introductory [tour] as it mentions the most important features (which is exactly why it was suggested when you first signed up). You may want to browse the [help] and read up on how to ask a good question and how to format posts.
comment on: http://stackoverflow.com/q/52707891
score: 0
type: Comment

http://stackoverflow.com/q/52657899
tagged with: list
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52658092
upvote count: 1
has comment: http://stackoverflow.com/comment/92246410
has comment: http://stackoverflow.com/comment/92246517
type: Question
has answer: http://stackoverflow.com/a/52658065
has body: I'm attempting to replace an item in a list multiple times. The replaceable list already had all letters replaced with blanks, and I am using a reference list to find the proper locations, so I can replace elements of a list without destroying the main list. For example letters_in_word = list(apple) for letter in letters_in_word: letter_location = letters_in_word.index(letter) for elements in replaceable_list: if guess is letter: replaceable_list[letter_location] = guess However, whenever I guess all of the letters one after the other (making a game for school project) only the first of a duplicated letter is placed into the code. Output: _ p _ _ _ or a p _ l e How do I set the code to replace every duplicated item in a list, for any word? Ideally, the result would be: a p p l e or _ p p _ _
has comment: http://stackoverflow.com/comment/92282919
has answer: http://stackoverflow.com/a/52657955
downvote count: 0
has title: Replacing the same element in a list that is repeated
favorite count: 0
has answer: http://stackoverflow.com/a/52676082
answer count: 5
has answer: http://stackoverflow.com/a/52657965
tagged with: python

http://stackoverflow.com/comment/92353679
has text: For me it working nice.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52714052
score: 0

http://stackoverflow.com/a/52630107
type: Answer
answers question: http://stackoverflow.com/q/52629543
upvote count: 2
has comment: http://stackoverflow.com/comment/92194794
score: 2
accepted answer of: http://stackoverflow.com/q/52629543
has comment: http://stackoverflow.com/comment/92194933
type: AcceptedAnswer
downvote count: 0
has body: OK so I will explain You why You have problem here. So hostapd is daemon process (Look at the last d in the name, most linux daemons have it). So You are trying to start this daemon with the os.system. In the documentation I have checked that this function spawns and returns the process return code. But to get the return code the os.system must wait for the daemon to finish. So that's why it hangs here. As a solution. I suggest spawning the daemon with some no waiting function, like os.spawn with the os.P_NOWAIT flag.

http://stackoverflow.com/a/52649195
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52648720
answers question: http://stackoverflow.com/q/52648720
has comment: http://stackoverflow.com/comment/92231351
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/92231222
upvote count: 3
has comment: http://stackoverflow.com/comment/92230768
has comment: http://stackoverflow.com/comment/92230506
has body: How about something like that: class Example: def __init__(self, *args, **kwargs): """This stores the default state then init the instance using this default state""" self.__default_args__ = args self.__default_kwargs__ = kwargs self.init(*args, **kwargs) def do(self): """Do whatever you want """ self.a += self.b - self.t self.t += 1 if self.t == self.b: self.d = True return self.a def init(self, a, b): """Inits the instance to a given state""" self.a = a self.b = b self.t = 0 self.d = False return self def reset(self): """Resets the instance to the default (stored) state""" return self.init(*self.__default_args__, **self.__default_kwargs__)

http://stackoverflow.com/comment/92287064
comment on: http://stackoverflow.com/q/52679191
type: QuestionComment
type: Comment
has text: What is your expected output? Indexes? What have you tried/investigated and why didn't that fulfill your requirements?
score: 1

http://stackoverflow.com/comment/92417865
has text: If I type range = range(0,256) the error too many variables to unpack is displayed
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52737112

http://stackoverflow.com/comment/92373976
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52722106
has text: Thanks for the answer, yet I'm using Python 3 (3.6.5 actually), but I'm using Windows; I'm not using the r prefix, should I use it? And how?

http://stackoverflow.com/comment/92121255
score: 0
has text: There is a gap also in your example the last dot of your data and the first one of your red fitted function are not close enough.
type: AnswerComment
comment on: http://stackoverflow.com/a/52590820
type: Comment

http://stackoverflow.com/comment/92521994
has text: @CristiFati `_system` is a `c_void_p` type that I pass around to the C API, and the `_system` naming is irrelevant to the question. The `XXX_API` in the code is the macro that exposes the C API functions.
comment on: http://stackoverflow.com/q/52726049
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52821649
downvote count: 1
has body: Actual commands to do as the answer by @jwodder. Run the following commands on the root directory. pip install pipenv Then pipenv run pip install pip==18.0 Then pipenv install
score: 21
has comment: http://stackoverflow.com/comment/93503508
has comment: http://stackoverflow.com/comment/93503457
upvote count: 22
has comment: http://stackoverflow.com/comment/92627594
type: Answer
has comment: http://stackoverflow.com/comment/92626809
answers question: http://stackoverflow.com/q/52706769
has comment: http://stackoverflow.com/comment/92626445
has comment: http://stackoverflow.com/comment/92599309

http://stackoverflow.com/comment/92130992
has text: Hi Martin, that is perfect - thank you very much for your help! I have not come across the JSON data before - how did you make that link to the data? As a continuation of my initial query, have you any ideas on how we can then impliment this technique to get the models of each respective car make? Thanks again!
type: AnswerComment
comment on: http://stackoverflow.com/a/52597901
score: 0
type: Comment

http://stackoverflow.com/comment/92216026
has text: Sarthak Negi - the input will be around 10,000 urls. And i might be misunderstanding the definition of a list.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52641121
score: 0

http://stackoverflow.com/comment/92966594
comment on: http://stackoverflow.com/q/52700621
has text: @AllenLavoie I have implemented custom server which serves model predictions via http requests (github updated). I will check it for memory leak before closing the question, but can you please expand your comment as answer, so I will have a good one to choose?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52739188
tagged with: pipenv
downvote count: 0
score: 1
type: Question
upvote count: 1
favorite count: 0
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: I'm trying to figure out how to specify different files for different operating systems in Pipfile. In particular, pytorch has different download links and naively one would specify them as follows [packages] torch = {file = "http://...torch-0.4.1-win_amd64.whl", os_name='nt'} torch = {file = "http://...torch-0.4.1-linux_x86_64.whl", os_name='posix'} This does not work, as toml does allow duplicated keys. Is there a syntax to do this?
tagged with: pipfile
has title: Specifying different `file` for different `os`

http://stackoverflow.com/a/52667625
has comment: http://stackoverflow.com/comment/92288210
has body: There may be an issue with your order of operations in max. You might want to try adding parentheses around 1+r before dividing it by 12.
score: 0
answers question: http://stackoverflow.com/q/52663656
type: Answer

http://stackoverflow.com/comment/92395460
type: QuestionComment
has text: Not sure whether I understand the "merging" right. If you just want to combine each 16x16 pixels, you could resize the image with size factor 1/16 with linear filtering interpolation and then manually resize to duplicate each pixel 16x16 times without any fancy interpolation.
comment on: http://stackoverflow.com/q/52733998
score: 0
type: Comment

http://stackoverflow.com/q/52723824
tagged with: django
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52724306
has answer: http://stackoverflow.com/a/52724306
type: Question
accepted answer: http://stackoverflow.com/a/52724360
score: 0
answer count: 2
has title: How to create a validator for special characters in DJANGO?
has answer: http://stackoverflow.com/a/52724360
has body: my site is live but it has a problem. Whenever someone signs up with a special character in their username then the server gives an error (for the entire site) as the slug cannot display special characters such as @,-,| but django user model lets users sign up with special characters. Is there a way I can throw in a validator error in my signup form. below is my forms.py from django.contrib.auth.models import User from django import forms from captcha.fields import CaptchaField class SignUpForm(forms.ModelForm): captcha = CaptchaField() password = forms.CharField(max_length= 15, widget=forms.PasswordInput) def clean_username(self): data = self.cleaned_data['username'] if not data.islower(): raise forms.ValidationError("Usernames should be in lowercase") return data class Meta: model = User help_texts = { 'username': 'Required. Please only use lower-case alphabets and numbers.', } fields = ['username', 'email', 'password'] views.py class SignUpFormView(View): form_class = SignUpForm template_name = 'home/signup.html' #if there is no sign up yet def get(self,request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) #if going to sig up def post(self,request): form = self.form_class(request.POST) if form.is_valid(): #it takes information but does save it user = form.save(commit = False) #cleaned normalized data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns if it is all correct user = authenticate(username = username, password = password) if user is not None: if user.is_active: login(request, user) return redirect("userprofile:newprofile") return render(request, self.template_name, {'form': form})

http://stackoverflow.com/q/52738575
upvote count: 3
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52738737
has title: get column value based on another column with list of strings in pandas dataframe
has answer: http://stackoverflow.com/a/52738737
downvote count: 0
tagged with: multiple-columns
has answer: http://stackoverflow.com/a/52738642
tagged with: pandas
score: 3
linked to: http://stackoverflow.com/q/36684013
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I tried the link. But it doesnt work for my example given below. I tried the loc[0] for the output. I tried .item(). But none of these help me. &gt;&gt;&gt; df2 = pd.DataFrame({ 'Item':['[Phone]', '[Watch]', '[Pen]', '[Pencil]', '[Knife]'], 'RelatedItem': ['[Phone cover]', '[Watch strap]', '[Pen cap]', '[Pencil lead]', '[fork]'], 'CountinInventory':['20','50','40','80','90']}) &gt;&gt;&gt; df2 Item RelatedItem CountinInventory 0 [Phone] [Phone cover] 20 1 [Watch] [Watch strap] 50 2 [Pen] [Pen cap] 40 3 [Pencil] [Pencil lead] 80 4 [Knife] [fork] 90 &gt;&gt;&gt; df2.loc[df2['Item'] == 'Phone', 'RelatedItem'] Series([], Name: RelatedItem, dtype: object) &gt;&gt;&gt; df2.loc[df2['Item'] == 'Phone', 'RelatedItem', 'CountinInventory'] pandas.core.indexing.IndexingError: Too many indexers I have this data where when I feed Phone, I need to get Phone cover along with the CountinInventory value as my answer. Please advice what mistake am I doing here.
accepted answer: http://stackoverflow.com/a/52738642
type: AnsweredQuestion

http://stackoverflow.com/q/52726745
tagged with: tkinter
has answer: http://stackoverflow.com/a/52763040
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52763040
has title: Use tkinter checkbutton values after window closes
type: Question
has comment: http://stackoverflow.com/comment/92383401
has body: I'm new to tkinter. I'm trying to build a popup form initiated from a script that will offer several checkboxes to set variables I need in the script once the window is closed. I'm fine when the frame is open, but I can't find a way to pass the variables out for later use. In the code below, I'd like to add another button that will set those variables for varPDF and varSHP (global?) and close the window. from tkinter import * class mainwindow(): def __init__(self, master): def setValues(var, entry): if varPDF.get() == True: print('varPDF is 1') else: print('varPDF is 0') if varSHP.get() == True: print('varPDF is 1') else: print('varSHP is 0') print('PDF:', varPDF.get(), ';', 'SHP: ', varSHP.get()) self.master = master window = (self.master) varPDF = BooleanVar() checkbutton = Checkbutton(window, text="PDF", variable=varPDF) checkbutton.grid(column=0, row=0) varSHP = BooleanVar() checkbutton = Checkbutton(window, text="SHP", variable=varSHP) checkbutton.grid(column=0, row=1) button1 = Button(window,text=u"Quit", command=self.end) button1.grid(column=2, row=3) button2 = Button(window,text=u"Show", command=lambda: setValues(varPDF, varSHP)) button2.grid(column=1, row=3) def end(self): self.master.destroy() def main(): root = Tk() window = mainwindow(root) root.mainloop() if __name__ == '__main__': main()
answer count: 1
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92378725

http://stackoverflow.com/q/52654752
has comment: http://stackoverflow.com/comment/92241519
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92241270
has comment: http://stackoverflow.com/comment/92241548
tagged with: tkinter
has title: How do I use tkinter PhotoImage within a class?
answer count: 0
has body: I am making a draughts/checkers game in python, and I have a problem that I can't find a solution for online when creating the pieces. My code is as follows: from tkinter import * board = [] white_pieces = [] black_pieces = [] class GUI(Frame): def __init__(self, master = None): self.game_board() def game_board(self): for y in range(8): for x in range(8): board.append(Button(root, width = 4, height = 2, bg = "#000000" if (x % 2 == 0 and y % 2 != 0) or (y % 2 == 0 and x % 2 != 0) else "#FFFFFF", state = DISABLED)) board[-1].grid(row = y + 1, column = x + 1, sticky = N+E+S+W) root.rowconfigure(x+1, weight = 1) root.columnconfigure(y+1, weight = 1) for i in range(8): Label(root, bg = "#C9C9C9", text = i+1).grid(row = 0, column = i+1, sticky = N+E+S+W) root.rowconfigure(i, weight = 1) for i in range(8): Label(root, width = 2, bg = "#C9C9C9", text = chr(i+97).title()).grid(row = i+1, column = 0, sticky = N+E+S+W) root.columnconfigure(i, weight = 1) class piece(PhotoImage): def __init__(self, position, master = None): self.name = "white.png" self.position = position if __name__ == "__main__": root = Tk() root.title("Draughts") window = GUI(root) black = PhotoImage("black.png") white = PhotoImage("white.png") for i in range(24): if ((i % 8) % 2 == 0 and (i // 8) % 2 != 0) or ((i % 8) % 2 != 0 and (i // 8) % 2 == 0): black_pieces.append(piece([i // 8, i % 8],black)) board[i].config(image = black_pieces[-1], state = NORMAL) else: i += 40 if ((i % 8) % 2 == 0 and (i // 8) % 2 != 0) or ((i % 8) % 2 != 0 and (i // 8) % 2 == 0): white_pieces.append(piece([i // 8, i % 8],black)) board[i].config(image = white_pieces[-1], state = NORMAL) root.mainloop() I am trying to use PhotoImage as the subject of a class (not sure if that's the right way to put it), but it doesn't work. I don't know if what I'm attempting is the right way to go about it, but I want to create 'Pieces' in the squares I need them in for checkers. If I change the image = black_pieces[-1] to bg = "green" in the line…
type: Question
has comment: http://stackoverflow.com/comment/92241235
score: 0
has comment: http://stackoverflow.com/comment/92241041
has comment: http://stackoverflow.com/comment/92241984
tagged with: python-3.x

http://stackoverflow.com/comment/92270682
score: 0
comment on: http://stackoverflow.com/q/52655620
type: Comment
has text: @JamesKPolk I now have a loop sending multiple pieces of bytes instead of just one (divided the command in different parts). Should I still switch to sendall? Send seems to be working
type: QuestionComment

http://stackoverflow.com/comment/92279417
has text: Could you do `numpy.random.seed(0)` at the top and re run your code and re print your desired output? Because `np.random` created random values. And your random values will be different from when I call `np.random` from my console.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52674923

http://stackoverflow.com/q/52726553
tagged with: image
has comment: http://stackoverflow.com/comment/92418883
score: 0
tagged with: colors
has comment: http://stackoverflow.com/comment/92378456
upvote count: 1
downvote count: 1
has body: So I have already been able to read the file and produce an array. I'm struggling finding ways to find the percent of green and blue in an image. #Import Libraries import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from PIL import Image import glob #option comd c and then cmd v to paste path /Users/Gilly/Desktop/Comp 180/images #2 Reads the image of a sunset into an array LOOP list_files=glob.glob("/Users/Gilly/Desktop/Comp 180/images/*.jpg") for i in list_files: img = mpimg.imread(i) print(img) #Plots the image from the array data for i in list_files: imgplot = plt.imshow(img) plt.show() #Calculate % of Green and Blue in the images
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92378572
has title: How to calculate percentage of green and the percentage of blue in the images, array already made, for loop reading the image file
has answer: http://stackoverflow.com/a/52728594
tagged with: percentage
has answer: http://stackoverflow.com/a/52747312
type: Question
answer count: 2
tagged with: arrays

http://stackoverflow.com/comment/92381929
has text: Yeah, "buffer" means "implements [the buffer protocol](https://docs.python.org/3/c-api/buffer.html)", and loosely translates as "raw memory thing", where the raw memory thing is backed by a C level array or struct. In many use cases, it's even more restrictive, meaning bytes-like (in this case, mutable bytes-like). Anything that you can [create a `memoryview` from](https://docs.python.org/3/library/stdtypes.html#memoryview) is a buffer, but it may or may not be bytes-like, mutable, etc.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52724841

http://stackoverflow.com/comment/92357496
type: AnswerComment
has text: This is what I would get. In this screenshot, only the entity with the id "5390493194125312" is unwanted. [Google Datastore screenshot](https://imgur.com/K4V0zLE)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52711493

http://stackoverflow.com/comment/92360716
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52717452
has text: @NinadGaikwad "usually when you use keywords as name of variable it won't give you a SyntaxError" <- It will give you a syntax error every single time for every keyword.
score: 1

http://stackoverflow.com/q/52671142
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/92272444
has comment: http://stackoverflow.com/comment/92272478
tagged with: python
linked to: http://stackoverflow.com/q/379906
has answer: http://stackoverflow.com/a/52671658
has comment: http://stackoverflow.com/comment/92273047
linked to: http://stackoverflow.com/q/42013867
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/92272416
has answer: http://stackoverflow.com/a/70648303
downvote count: 0
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/92272845
has comment: http://stackoverflow.com/comment/92272244
has comment: http://stackoverflow.com/comment/92272211
type: Question
has comment: http://stackoverflow.com/comment/92272345
has comment: http://stackoverflow.com/comment/92272736
has comment: http://stackoverflow.com/comment/92272596
has comment: http://stackoverflow.com/comment/92272164
has comment: http://stackoverflow.com/comment/92272944
linked to: http://stackoverflow.com/q/29219479
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92272295
linked to: http://stackoverflow.com/q/28158099
tagged with: type-conversion
upvote count: 2
has comment: http://stackoverflow.com/comment/92272572
has comment: http://stackoverflow.com/comment/92272614
answer count: 2
possible better answer: http://stackoverflow.com/a/70648303
linked to: http://stackoverflow.com/q/47559522
has comment: http://stackoverflow.com/comment/92272418
has body: I have a dataframe that looks like this with 13000 rows print(df) Date Price Nation 0 01/01/2018 -5.000,73 Spain 1 01/01/2018 15,60 Italy 3 01/01/2018 14,13 Italy 4 01/01/2018 12,53 Spain 5 01/01/2018 16,64 Italy 6 01/01/2018 22,48 Italy 7 01/01/2018 24,30 Italy 8 01/01/2018 24,88 Spain 9 01/01/2018 31,40 Italy 10 01/01/2018 18,74 Italy Price Column is a non-null object I removed all the white spaces and dropped al the empty rows I tried to work only with the price column converting from a Series to a String string=df['Price'].to_string() print(string) 0 -5.000,73 1 15,60 3 14,13 4 12,53 5 16,64 6 22.48 7 24.30 8 24.88 9 31.40 10 18.74 When I tried string=string.strip('.') string=string.replace(',','.') float(string.strip().strip("'")) The system returned me an error message: ValueError: could not convert string to float: '0 -5.000.73\n1 15.60\n3 14.13\n4 12.53\n5 16.64\n6 22.48\n7 24.30\n8 24.88\n9 31.40\n10 The data are loaded from a csv, and the delimiter is , How can I easily convert to a float, considering that \n7, \n10,..., \n160000 are not regularly increased? Why I get this kind of problem? If I open my csv with Jupyter or on excel I cannot see /n32, but only something like this "01/01/2018","16,60","Spain", I know that /n is used for giving a vertical space, but I don't know how to deal with it, I noticed that is related with the index I read this questions, tried other solutions, but none solved my problem: numpy.loadtxt, ValueError: could not convert string to float ValueError: could not convert string to float: '-0,274697\n' How do I parse a string to a float or int in Python? Python convert string to float Python. ValueError could not convert string to float: ValueError: could not convert string to float in Pyspark
has title: ValueError: could not convert string to float: ''20,99''
has comment: http://stackoverflow.com/comment/92272093
tagged with: string
accepted answer: http://stackoverflow.com/a/52671658
favorite count: 0
linked to: http://stackoverflow.com/q/16729210

http://stackoverflow.com/comment/92325753
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52699626
type: Comment
has text: General Algo...iterate your text file line by line and match "min.pop.password". When the condition matches replace it with the string you want

http://stackoverflow.com/a/52599446
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52598788
answers question: http://stackoverflow.com/q/52598788
has body: Sorry if this was confusing – but the GitHub thread you're referring to is still only the spec and proposal, i.e. the planned implementation. The changes will hopefully ship with spaCy v2.1.0 (since some of the changes to the Matcher internals are not fully backwards compatible). While the custom attribute matching isn't implemented yet, the basic improvements to the Matcher engine are already available on the develop branch and in the alpha version via spacy-nightly (pip install spacy-nightly). Those updates likely also resolve the inconsistent behaviour you observed with the callback function.
has comment: http://stackoverflow.com/comment/92166077
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52590752
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92124312
has comment: http://stackoverflow.com/comment/92120378
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92124944
has comment: http://stackoverflow.com/comment/92124796
has title: How to append to a dataframe when using .apply function
downvote count: 0
has comment: http://stackoverflow.com/comment/92123570
has comment: http://stackoverflow.com/comment/92122834
has body: I am trying to append a dataframe M to an empty dataframe Linked_df each time the duration is less than 11 seconds. The following code appends a dataframe: Linked_df=pd.DataFrame() Linked=pd.DataFrame() #for each unique date for unq_date in Unique_Dates: #obtain dataframe of Mi and Ri of a specific date #add a column for index to track orignal index M=Mi.loc[(pd.to_datetime(Mi['EventDate']) == unq_date) ] R=Ri.loc[(pd.to_datetime(Ri['EventDate']) == unq_date) ] #Check if unique date exist in M Linked_df = R.apply(lambda row: create_dur(row['start_DateTime'], M,Linked_df), axis=1) Linked=Linked.append(Linked_df,ignore_index=True) The function called and appends M to dataframe Linked_df : def create_dur(row,M,Linked_df): M['duration']=(M['Event Read Time'] - row).dt.total_seconds() M.loc[M.duration &lt; 0, 'duration'] = (row-M['Event Read Time']).dt.total_seconds() M=M.loc[M.duration &lt; 11] #print(M['duration']) #print(M) row1 = pd.DataFrame(M) #Linked_df=pd.concat([Linked_df, row1], ignore_index=True) Linked_df=Linked_df.append(M,ignore_index=True) print(Linked_df) return Linked_df The output from the function: EventDate Id_str EventTime Event Read Time lat \ 0 2017-11-09 72057594042646832 01:13:24 2017-11-09 01:13:24 -27.73409 1 2017-11-09 72057594042646832 01:13:29 2017-11-09 01:13:29 -27.73200 2 2017-11-09 72057594042646848 01:13:30 2017-11-09 01:13:30 -27.73192 3 2017-11-09 72057594042646864 01:13:32 2017-11-09 01:13:32 -27.73399 4 2017-11-09 72057594042646880 01:13:33 2017-11-09 01:13:33 -27.73398 long Speed Sprung Weight Frame Torque ind_val_Mi duration 0 22.96531 9.0 468.0 88.0 101995 6.0 1 22.97351 36.0 280.0 -4.0 101996 1.0 2 22.97347 36.0 270.0 -10.0 101997 0.0 3 22.96537 0.0 480.0 85.0 101998 2.0 4 22.96537 2.0 489.0 89.0 101999 3.0 EventDate Id_str EventTime Event Read Time lat \ 0 2017-11-09 72057594042646832 01:13:29 2017-11-09 01:13:29 -27.73200 1 2017-11-09 72057594042646848 01:13:30 2017-11-09 01:13:30 -27.73192 2 2017-11-09 72057594042646864 01:13…
has comment: http://stackoverflow.com/comment/92122822
tagged with: pandas
has comment: http://stackoverflow.com/comment/92126413
has comment: http://stackoverflow.com/comment/92125886
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/53747626
answers question: http://stackoverflow.com/q/52624102
score: 2
downvote count: 0
has body: Solution: Use a single file bundled MathJax instead. For your case, I've seen the math render with this bundled. Working example I thought this'd be easy, just either (a) modify mkdocs static server setting or (b) just bundle Mathjax altogether into 1 single .js file, webpack style. For option (a), mkdocs doesn't provide that much customization for its static server... Then I spent a long time on (b). Mathjax makes ajax call to load its extensions and file on its own, so it's incredibly difficult to bundle the whole thing together. Just as I was about to try serving Mathjax statically on another local server, I found this article in Mathjax wiki, checkout the repo, load up one of the dist file and boom, it just works. Be sure to go over to that repo and give it a star! Here's a working example with your string. The mathjax bundle is pretty large (1.9mb) so it'll take a while to load.
upvote count: 2
type: Answer

http://stackoverflow.com/q/52705444
has body: In Django, I have a sidebar navigation menu that has its own include file (let's call it sidebar.html). In sidebar.html, I sometimes load a special menu, depending on which page I am visiting. This special menu is generated from a database, so I need to run something like this in my views: menu = Menu.objects.all() Then I need to pass this variable to the template. However, there are some 30 pages where I need this menu. It seems like a repetitive solution to have the aforementioned line repeated 30 times in my views file. Is there a better way of doing it? I only need the menu variable in sidebar.html, so there is only 1 file where I need it.
has answer: http://stackoverflow.com/a/52705583
type: AnsweredQuestion
has title: Load a variable on many pages without repeating myself
type: Question
answer count: 1
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52705583
tagged with: django

http://stackoverflow.com/a/52725817
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52710165
has body: You could make use of an alternation and a positive and lookahead and lookbehind: (?&lt;=\+) \d+(?=x)|- \d+(?=x) print(re.findall("(?&lt;=\+) \d+(?=x)|- \d+(?=x)", "6x2 + 4x + 5 - 2x2 - 7x + 4 + 87x - 100x")) # [' 4', '- 2', '- 7', ' 87', '- 100'] Regex demo | Python demo Explanation (?&lt;=\+) \d+(?=x) Positive lookbehind to assert what is on the left is a +, then match a space followed by one or more digits. Use a positive lookahead to assert what is on the right side is an x | Or - \d+(?=x) Match -, a space and one or more digits. Then use a positive lookahead to assert what is on the right is an x If you don't want to include the space before the match without the + you could remove it before the digit and add it to the positive lookbehind: (?&lt;=\+ )\d+(?=x)|- \d+(?=x)

http://stackoverflow.com/q/52661149
has title: Is it efficient to join multiple dataframes using chained "join", rather than merge or concat?
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52661785
accepted answer: http://stackoverflow.com/a/52661785
tagged with: concatenation
tagged with: pandas
downvote count: 0
favorite count: 0
has body: Not being an expert in code efficiency (yet) &amp; best pythonic code writing (yet), I would like to ask the experts here if the following code is the best to join dataframes that have a common Date Index, or if merge or concat may be better: data = df1.join(df2).join(df3).join(df4).join(df5).dropna() I used the .dropna() suffix at the end to cancel out rows where a single NaN occurs. NB: the reason why NaN occurs in this dataset is because I have created dataframes that are in fact shifted versions of other dataframes (using .shift(n) ), which means that NaNs creep in at the head of the shifted dataframes. I intend to use this code in many other applications, so wanted to use the best possible methodology (i.e. not make unnecessary use of memory, take too much time to process, use the correct join/merg/concat constructs).
upvote count: 1
tagged with: python
tagged with: merge
type: AnsweredQuestion
tagged with: join
score: 1

http://stackoverflow.com/comment/92279493
comment on: http://stackoverflow.com/q/52674896
type: Comment
type: QuestionComment
score: 0
has text: https://stackoverflow.com/editing-help#comment-formatting Got it thanks!

excel
tags question: http://stackoverflow.com/q/52657191
tags question: http://stackoverflow.com/q/52685699
tags question: http://stackoverflow.com/q/52721944
tags question: http://stackoverflow.com/q/52658117
tags question: http://stackoverflow.com/q/52603258
tags question: http://stackoverflow.com/q/52600935
tag name: excel
tags question: http://stackoverflow.com/q/52604298
tags question: http://stackoverflow.com/q/52713473
tags question: http://stackoverflow.com/q/52673702
tags question: http://stackoverflow.com/q/52647650
tags question: http://stackoverflow.com/q/52694220
tags question: http://stackoverflow.com/q/52647458
tags question: http://stackoverflow.com/q/52592717
tags question: http://stackoverflow.com/q/52733542
tags question: http://stackoverflow.com/q/52680236
tags question: http://stackoverflow.com/q/52669357
tags question: http://stackoverflow.com/q/52601732
tags question: http://stackoverflow.com/q/52725910
tags question: http://stackoverflow.com/q/52681186
tags question: http://stackoverflow.com/q/52741845
type: Tag
tags question: http://stackoverflow.com/q/52600125
tags question: http://stackoverflow.com/q/52630370
tags question: http://stackoverflow.com/q/52710503
tags question: http://stackoverflow.com/q/52712968

http://stackoverflow.com/comment/92339432
type: Comment
comment on: http://stackoverflow.com/a/52705977
has text: Well -- point I'm making is that one *can* use `shell=True` safely, if the string passed as the first element of `cmd` is a constant that was carefully audited by a human, and all elements that could vary are kept out-of-band (and there hasn't been any meddling with environment variables). But yes, avoiding it altogether is indeed the best approach. :)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92156798
type: Comment
has text: True, and that can be optimized further, by searching for pairs of factors, and stopping at the square root. But why bother saving them to a list? Just add them up as you find them.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52610992

http://stackoverflow.com/q/52597841
accepted answer: http://stackoverflow.com/a/52597988
score: 0
answer count: 2
tagged with: python
has title: regex stored in json not parsing
possible better answer: http://stackoverflow.com/a/52598032
has answer: http://stackoverflow.com/a/52598032
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/52597988
type: AnsweredQuestion
type: Question
has body: I have a JSON dict which contains two regular expressions for how I want a string formatted. { "codes": { "ed_code": "r'(\\D{3})(\\d{3})(\\d*)'", "ed_pattern": "'\\1_\\2'" } } In Python, I want to format a string based on the rules inside the config.json file. import json _CONFIG_FILE = "config.json" _CONFIG = json.load(open(_CONFIG)) a="XYZ290290781" code = _CONFIG['codes']['ed_code'] pattern= _CONFIG['codes']['ed_pattern'] ed_format = re.sub(code,pattern,a) Printing ed_format returns exactly what x is. It should return XYZ_290. I'm thinking code and pattern aren't being passed from the JSON file properly. Am I right in thinking this? How can I fix this?
tagged with: regex

http://stackoverflow.com/comment/92192835
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52629454
type: Comment
has text: Nothing in this answer is *wrong*, but it certainly isn't proper application of OOP either. A class that only has a single static method shouldn't be a class. The 3 bullet points are useful information, but the code by itself is downvote-worthy.

http://stackoverflow.com/q/52655536
has body: This question uses Python-3.7 and pandas-0.23.4. I'm currently dealing with financial datasets that I need to only retrieve the data of each trading day between 08:15 to 13:45 Variable Setup To illustrate this, I have a DataFrame variable with DateTimeIndex with continuous minutely frequency declared as the following code: y = ( pd.DataFrame(columns=['x', 'y']) .reindex(pd.date_range('20100101', '20100105', freq='1min')) ) Problem Introduction I want to slice the data from each day between 08:15 to 13:45. The following code seems to work but I don't think it's very Pythonic and it seems to not very memory-efficient considering the double indexing at the end: In [108]: y[y.index.hour.isin(range(8,14))][15:][:-14] Out[108]: x y 2010-01-01 08:15:00 NaN NaN 2010-01-01 08:16:00 NaN NaN 2010-01-01 08:17:00 NaN NaN 2010-01-01 08:18:00 NaN NaN 2010-01-01 08:19:00 NaN NaN ... ... ... 2010-01-04 13:41:00 NaN NaN 2010-01-04 13:42:00 NaN NaN 2010-01-04 13:43:00 NaN NaN 2010-01-04 13:44:00 NaN NaN 2010-01-04 13:45:00 NaN NaN [1411 rows x 2 columns] EDIT: After thoroughly checked the data, the indexing above does not solve the problem because the data still contains the times after 2010-01-01 13:45:00 and before 2010-01-02 08:15:00: In [147]: y[y.index.hour.isin(range(8,14))][15:][:-14].index[300:400] Out[147]: DatetimeIndex(['2010-01-01 13:15:00', '2010-01-01 13:16:00', '2010-01-01 13:17:00', '2010-01-01 13:18:00', '2010-01-01 13:19:00', '2010-01-01 13:20:00', ... '2010-01-01 13:35:00', '2010-01-01 13:36:00', '2010-01-01 13:37:00', '2010-01-01 13:38:00', '2010-01-01 13:39:00', '2010-01-01 13:40:00', '2010-01-01 13:41:00', '2010-01-01 13:42:00', '2010-01-01 13:43:00', '2010-01-01 13:44:00', '2010-01-01 13:45:00', '2010-01-01 13:46:00', # 13:46:00 should be excluded '2010-01-01 13:47:00', '2010-01-01 13:48:00', # this should be excluded '2010-01-01 13:49:00', '2010-01-01 13:50:00', # this should be excluded '2010-01-01 13:51:00', '2010-01-01 13:52:00', # this should be excluded '2…
accepted answer: http://stackoverflow.com/a/52655621
tagged with: pandas
has title: pandas - Pythonic way to slicing DataFrame with DateTimeIndex
favorite count: 0
upvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/52655655
type: AnsweredQuestion
score: 2
tagged with: datetimeindex
has answer: http://stackoverflow.com/a/52655621
has answer: http://stackoverflow.com/a/52655655
tagged with: slice
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/92379580
has text: @Triggernometry, Nice catch! Thank you.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52725593
type: AnswerComment

http://stackoverflow.com/a/52678103
has body: If possible, re-structure your application so that instead of dumping plain-text to a log file you're directly writing structured log information to something like Elasticsearch. Thank me later. That isn't always feasible (e.g. if you don't control the log source). I have a few opinions on your solutions. This feels super brittle. Elasticsearch does not base _id on the properties of a particular document. It's selected based off of existing _id fields that it has stored (and I think also off of a random seed). Even if it could work, relying on an undocumented property is a good way to shoot yourself in the foot when dealing with a team that makes breaking changes even for its documented code as often as Elasticsearch does. This one actually isn't so bad. Elasticsearch supports manually choosing the id of a document. Even if it didn't, it performs quite well for bulk terms queries and wouldn't be as much of a bottleneck as you might think. If you really have so much data that this could break your application then Elasticsearch might not be the best tool. This solution is great. It's super extensible and doesn't rely on a complicated dependence on how the log file is constructed, how you've chosen to index that log in Elasticsearch, and how you're choosing to read it with Python. Rather you just get a document, and if you need to update it then you do that updating. Elasticsearch isn't really a worse point of failure here than before (if ES goes down, your app goes down in any of these solutions) -- you're just doing twice as many queries (read and write). If a factor of 2 kills your application, you either need a better solution to the problem (i.e. avoid Elasticsearch), or you need to throw more hardware at it. ES supports all kinds of sharding configurations, and you can make a robust server on the cheap. One question though, why do you have logs in Elasticsearch that need to be updated with this particular normal/malicious property? If you're the one putting them…
upvote count: 1
has comment: http://stackoverflow.com/comment/92285878
score: 1
has comment: http://stackoverflow.com/comment/92285714
has comment: http://stackoverflow.com/comment/92285856
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/93721308
accepted answer of: http://stackoverflow.com/q/52677832
type: Answer
answers question: http://stackoverflow.com/q/52677832

http://stackoverflow.com/a/52692073
score: 1
downvote count: 0
has body: That's because x is going to be a different element of the list in every loop, so in the first loop it will be DataList[0], in the second it will be DataList[1] and so on. So, when you print(x) after the for block is done, x will still have the last value of DataList. Also, .split() is not collateral, so it'll not affect x itself, it'll return a new list. If you want to store every splitted line in a separate list you need to do it inside the for block, like: splitted_lines = [] for x in DataList: splitted_lines.append(x.split(",")) print splitted_lines
answers question: http://stackoverflow.com/q/52691993
type: Answer
has comment: http://stackoverflow.com/comment/92311163
upvote count: 1

http://stackoverflow.com/comment/92247447
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52653693
type: Comment
has text: To be honest, reading your comments and also the question you linked above, I am beginning to doubt the practical value of the whole validation.

http://stackoverflow.com/q/52740918
has body: I have difficulties to laucnh celery worker. The exemple here works fine and is closed to documentation. My problem is that my real configuration folder construction is like this : djangosite/ |-- package/ | |-- __init__.py | |-- laboratory/ | | |-- __init__.py | | |-- migrations/ | | |-- templates/ | | |-- apps.py | | |-- models.py | | +-- views.py |-- mysite/ | |-- __init__.py | |-- settings.py | |-- urls.py | |-- celery.py | +-- wsgi.py |-- manage.py My app is a subfolder of package when the exemple show an app in folder. __init__ of mysite folder: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py contains: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('celery_app') # This reads, e.g., CELERY_ACCEPT_CONTENT = ['json'] from settings.py: app.config_from_object('django.conf:settings') # For autodiscover_tasks to work, you must define your tasks in a file called 'tasks.py'. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) I launch: celery worker -l info -A mysite and celery cannot find laboratory module: Traceback (most recent call last): File "C:\Python27\Lib\runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "C:\Python27\Lib\runpy.py", line 72, in _run_code exec code in run_globals File "D:\Developpements\VirtualEnv\laboProd\Scripts\celery.exe\__main__.py", line 9, in &lt;module&gt; File "d:\developpements\virtualenv\laboprod\lib\site-packages\celery\__main__.py", line 30, in main main() File "d:\developpements\virtualenv\laboprod\lib\site-packages\celery\bin\celery.py", line 81, in main cmd.execute_from_commandline(argv) File "d:\developpements\virtualenv\laboprod\lib\site-packages\celery\bin\celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "d:\developpements\…
answer count: 1
has answer: http://stackoverflow.com/a/52759521
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92406636
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92406536
has comment: http://stackoverflow.com/comment/92406971
tagged with: celery
type: Question
has title: Celery django : launch worker - ImportError: No module named XXX
score: 0

http://stackoverflow.com/comment/92353551
type: QuestionComment
comment on: http://stackoverflow.com/q/52713886
score: 0
has text: so does the file have a filename/path per file?
type: Comment

http://stackoverflow.com/q/52742370
score: 0
tagged with: spyder
answer count: 1
has answer: http://stackoverflow.com/a/52742830
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has title: ImportError: cannot import name 'fitpack'
has body: pip 18.0 python 3.6 Spyder 3.2.8 OS: Windows 10 Pro Bellow error and not able to run deep-ann.py from sklearn.preprocessing import LabelEncoder, OneHotEncoder Traceback (most recent call last): File "&lt;ipython-input-3-83540d56f55d&gt;", line 1, in &lt;module&gt; from sklearn.preprocessing import LabelEncoder, OneHotEncoder File "C:\Users\virus-attack\Anaconda3\lib\site-packages\sklearn\preprocessing\__init__.py", line 8, in &lt;module&gt; from .data import Binarizer File "C:\Users\virus-attack\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py", line 18, in &lt;module&gt; from scipy import stats File "C:\Users\virus-attack\Anaconda3\lib\site-packages\scipy\stats\__init__.py", line 345, in &lt;module&gt; from .stats import * File "C:\Users\virus-attack\Anaconda3\lib\site-packages\scipy\stats\stats.py", line 171, in &lt;module&gt; from . import distributions File "C:\Users\virus-attack\Anaconda3\lib\site-packages\scipy\stats\distributions.py", line 10, in &lt;module&gt; from ._distn_infrastructure import (entropy, rv_discrete, rv_continuous, File "C:\Users\virus-attack\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 16, in &lt;module&gt; from scipy.misc import doccer File "C:\Users\virus-attack\Anaconda3\lib\site-packages\scipy\misc\__init__.py", line 68, in &lt;module&gt; from scipy.interpolate._pade import pade as _pade File "C:\Users\virus-attack\Anaconda3\lib\site-packages\scipy\interpolate\__init__.py", line 175, in &lt;module&gt; from .interpolate import * File "C:\Users\virus-attack\Anaconda3\lib\site-packages\scipy\interpolate\interpolate.py", line 26, in &lt;module&gt; from . import fitpack ImportError: cannot import name 'fitpack'
tagged with: anaconda
type: Question
has comment: http://stackoverflow.com/comment/92486478
has comment: http://stackoverflow.com/comment/92414033

http://stackoverflow.com/comment/92298954
score: 0
type: Comment
has text: can't do that one by one because there are a lot of examples
type: AnswerComment
comment on: http://stackoverflow.com/a/52684419

google-app-engine-python
type: Tag
tags question: http://stackoverflow.com/q/52672046
tag name: google-app-engine-python

http://stackoverflow.com/q/52614173
type: Question
has answer: http://stackoverflow.com/a/52614722
has answer: http://stackoverflow.com/a/52651098
has comment: http://stackoverflow.com/comment/92162881
has answer: http://stackoverflow.com/a/52614427
has comment: http://stackoverflow.com/comment/92162782
score: -1
downvote count: 2
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/92162805
favorite count: 0
possible better answer: http://stackoverflow.com/a/52651098
has body: I am an extreme novice and have only just started. I want to learn how to loop a specified section of my code. #This program ask you to choose a number between 1 and 20, then tries to #guess it. import random print('Think of a number between 1 and 20, im going to try and guess it.') print('If my guess is too high or low, please tell me and ill guess again.') input() guess=random.randint(1, 20) print('Is this too high, too low, or correct?') print(guess) answer=input() #Until the user answers 'correct' I would #like all of the following to loop: if answer == 'low': print('how about now?') guess=guess+1 print(guess) if answer == 'high': print('how about now?') guess=guess-1 print(guess) if answer == 'correct': print('nice!') print() print('Press CTRL+C to exit')
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52614722
has title: How to loop specific sections of code in Python?

http://stackoverflow.com/comment/137159027
score: 0
type: Comment
type: AnswerComment
has text: Dask now has a `partition_size` kwarg to repartition which does something similar (arguably better) using the size of the data, and without materializing the entire index on one node.
comment on: http://stackoverflow.com/a/56014192

http://stackoverflow.com/comment/92146032
comment on: http://stackoverflow.com/q/52605666
type: Comment
has text: I tried absolute path before and it didn't work, now it does. Thank you very much! Still has me wondering how this works and my method doesn't... The os.path code doesn't give me any output/insight btw. I want to give you credit for helping me.
type: QuestionComment
score: 0

http://stackoverflow.com/a/52691758
upvote count: 2
has body: The files/folders in the Google Cloud repository aren't directly accessible (it's like a bare git repository), you need to first clone the repo then copy the desired files/folders from the cloned repo to their destinations. It might be possible to use a standard Fetching dependencies build step to clone the repo, but I'm not 100% certain of it in your case, since you're not actually doing a build: steps: - name: gcr.io/cloud-builders/git args: ['clone', 'https://github.com/GoogleCloudPlatform/cloud-builders'] If not you may need one (or more) custom build steps. From Creating Custom Build Steps: A custom build step is a container image that the Cloud Build worker VM pulls and runs with your source volume-mounted to /workspace. Your custom build step can execute any script or binary inside the container; as such, it can do anything a container can do. Custom build steps are useful for: Downloading source code or packages from external locations ...
answers question: http://stackoverflow.com/q/52689811
has comment: http://stackoverflow.com/comment/92322089
accepted answer of: http://stackoverflow.com/q/52689811
has comment: http://stackoverflow.com/comment/100030609
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/92398413
has text: Got it. So, how are these 2 backends different? And are there more of these that can be used? If yes, how can I list them out?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52736579
type: Comment

http://stackoverflow.com/q/52693572
accepted answer: http://stackoverflow.com/a/52705740
tagged with: random-walk
favorite count: 0
has body: I have a random walk on a 2D grid with randomly initialised positions. I am looking for a condition, where if the random walk is within some range of the initial positions of the other random walks, it will stop. While I found this easy to implement in the simple case, I am having trouble implementing it in the case of N random walks. This is due to the fact, that the code needs to check for a range of values around every initial position, except for the one, which is around the current random walk. P.S This is my first post on stack overflow. Please, let me know if I was being too vague or did not follow the guidelines for asking questions on here. import numpy.random as rd #importing libraries import numpy as np import matplotlib.pyplot as plt import matplotlib import numpy.ma as ma lsize=100 T=1000 #n of steps N=5 #n of walks xvec=np.zeros(N) yvec=np.zeros(N) xstore=np.zeros(T+1) ystore=np.zeros(T+1) xmat=np.zeros((T+1,N)) ymat=np.zeros((T+1,N)) for i in range(N): #randomly assigns initial position xcor=rd.randint(1,lsize) ycor=rd.randint(1,lsize) xvec[i]=xcor yvec[i]=ycor for i in range(N): xstore[0]=xvec[i] ystore[0]=yvec[i] for j in range(T): A=[0,1,2,3] temp=rd.choice(A) if temp==0: ystore[j+1]=ystore[j]+1 #up xstore[j+1]=xstore[j] elif temp==1: xstore[j+1]=xstore[j]+1 #right ystore[j+1]=ystore[j] elif temp==2: ystore[j+1]=ystore[j]-1 #down xstore[j+1]=xstore[j] elif temp==3: xstore[j+1]=xstore[j]-1 #left ystore[j+1]=ystore[j] xstore[j+1]=np.mod(xstore[j+1], lsize+1) ystore[j+1]=np.mod(ystore[j+1], lsize+1) xmat[:,i]=xstore ymat[:,i]=ystore plt.plot(xmat,ymat) plt.show()
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Stopping condition if a random walk is within a range of randomly initialised values
score: 1
has answer: http://stackoverflow.com/a/52705740
type: Question
tagged with: numpy
downvote count: 0
answer count: 1

http://stackoverflow.com/q/52668642
tagged with: python
has body: I would like to get the container status and restarts of a pod, using python kubernetes. I am currently using list_namespaced_pod to get the pods and the container status, which I interpret as the status of the pod. This works, but is far from an ideal solution. I am looking for something that gives me similar information to kubectl -n $NAMESPACE get pods.
tagged with: status
upvote count: 7
has answer: http://stackoverflow.com/a/52674264
has answer: http://stackoverflow.com/a/67685880
type: Question
type: AnsweredQuestion
score: 7
possible better answer: http://stackoverflow.com/a/67685880
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/52674264
favorite count: 0
has title: Kubernetes: How do I get the status and restarts of a container using python?
tagged with: restart
tagged with: kubernetes

http://stackoverflow.com/q/52629587
accepted answer: http://stackoverflow.com/a/52630980
type: Question
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/92194516
answer count: 2
tagged with: pyqt
has comment: http://stackoverflow.com/comment/92194318
has answer: http://stackoverflow.com/a/52630222
has answer: http://stackoverflow.com/a/52630980
has body: I have searched a lot but I am unable to find a solution for doing this. I have a QListWidget which will populate a list of values. I need to implement a "select all" as default behaviour in the list. I have already used MultiSelection and that works well, but the need is to avoid clicking on each item, in case the user wants to do the update on all items listed. Can someone help me understand how to do this?
tagged with: python
possible better answer: http://stackoverflow.com/a/52630222
has comment: http://stackoverflow.com/comment/92193107
has comment: http://stackoverflow.com/comment/92194715
type: AnsweredQuestion
has title: pyqt : Display All values present in QListWidget as selected to user
score: 0
has comment: http://stackoverflow.com/comment/92194815

mongodb
tags question: http://stackoverflow.com/q/52688382
tags question: http://stackoverflow.com/q/52669536
tags question: http://stackoverflow.com/q/52662009
tags question: http://stackoverflow.com/q/52649322
tag name: mongodb
tags question: http://stackoverflow.com/q/52635168
tags question: http://stackoverflow.com/q/52742173
type: Tag
tags question: http://stackoverflow.com/q/52606202
tags question: http://stackoverflow.com/q/52739448
tags question: http://stackoverflow.com/q/52671209
tags question: http://stackoverflow.com/q/52621207
tags question: http://stackoverflow.com/q/52726337
tags question: http://stackoverflow.com/q/52607737
tags question: http://stackoverflow.com/q/52664136
tags question: http://stackoverflow.com/q/52741194
tags question: http://stackoverflow.com/q/52704386
tags question: http://stackoverflow.com/q/52659981
tags question: http://stackoverflow.com/q/52697707
tags question: http://stackoverflow.com/q/52620395

http://stackoverflow.com/comment/92219310
has text: @jpp but if I want **only** keys why should I use `dict.items`?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52643105
type: AnswerComment

http://stackoverflow.com/q/52738335
type: Question
linked to: http://stackoverflow.com/q/42816124
has body: I am currently using TensorFlow tutorial's first_steps_with_tensor_flow.ipynb notebook to learn TF for implementing ML models. In the notebook, they have used Stochastic Gradient Descent (SGD) to optimize the loss function. Below is the snippet of the my_input_function: def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None): Here, it can be seen that the batch_size is 1. The notebook uses a housing data set containing 17000 labeled examples for training. This means for SGD, I will be having 17000 batches. LRmodel = linear_regressor.train(input_fn = lambda:my_input_fn(my_feature, targets), steps=100) I have three questions - Why is steps=100 in linear_regressor.train method above? Since we have 17000 batches and steps in ML means the count for evaluating one batch, in linear_regressor.train method steps = 17000 should be initialized, right? Is number of batches equal to the number of steps/iterations in ML? With my 17000 examples, if I keep my batch_size=100, steps=500, and num_epochs=5, what does this initialization mean and how does it correlate to 170 batches?
score: 0
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52904530
tagged with: machine-learning
tagged with: python
has title: TensorFlow: Correct way of using steps in Stochastic Gradient Descent
has comment: http://stackoverflow.com/comment/98913842
linked to: http://stackoverflow.com/q/38340311
tagged with: tensorflow

http://stackoverflow.com/a/78033222
answers question: http://stackoverflow.com/q/52701330
score: 1
has body: What I use is a combined index. The first step is to declare the desired index. Then, combine it with the existing index. Now reindex to the combined index and fill in NaNs with interpolation, ffill or any other function. Then reindex again only to the new index. # Create a new time series with minute frequency new_index = pd.date_range(temperature_data.index.min(), temperature_data.index.max(), freq='min') #Create combined index for ffill or interpolation etc. combined_index = new_index.union(temperature_data.index) #Reindex to combined index resampled_ts = temperature_data.reindex(combined_index) # Apply interpolation to fill missing values resampled_ts = resampled_ts.interpolate(method='linear') # Resample the combined time series to minute frequency resampled_ts = resampled_ts.reindex(new_index)
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/52618810
has title: Unable to use Subprocess module to successfully parse and run long command
tagged with: subprocess
upvote count: 2
type: UnansweredQuestion
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52619088
score: 2
has comment: http://stackoverflow.com/comment/92172675
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52618937
tagged with: python
has body: I am attempting to implement port forwarding on my machine by running a series of commands on Mac in terminal that can be found here. I am attempting to run the port mapping commands as listed in the latter link by utilizing subprocess in Python. The command I am attempting to run using subprocess is: echo " rdr pass inet proto tcp from any to any port 80 -&gt; 127.0.0.1 port 8080 " | sudo pfctl -ef - My Python implementation of the above command: from subprocess import Popen, PIPE commands = ['echo', '"rdr pass inet proto tcp from any to any port 80 -&gt; 127.0.0.1 port 8080"\n', '|', 'sudo', 'pfctl', '-ef', '-'] p = Popen(['sudo', '-S']+commands, stdin=PIPE, stderr=PIPE, universal_newlines=True) print(p.communicate('root_password\n')[1])#be able to read password for sudo from stdin However, this Python script does not work, as when I run sudo pfctl -s nat to display all port forwarding rules on my machine my expected output rdr pass inet proto tcp from any to any port = 80 -&gt; 127.0.0.1 port 8080 is not displayed to the shell. However, running echo " rdr pass inet proto tcp from any to any port 80 -&gt; 127.0.0.1 port 8080 " | sudo pfctl -ef - does indeed produce rdr pass inet proto tcp from any to any port = 80 -&gt; 127.0.0.1 port 8080 after running the display command sudo pfctl -s nat. How can my subprocess implementation be improved so that the rule listing is outputted correctly? Edit: oddly, I can run the display command sudo pfctl -s nat using subprocess p = Popen(['sudo', '-S']+'pfctl -s nat'.split(), stdin=PIPE, stderr=PIPE, universal_newlines=True) print(p.communicate(f'myrootpassword\n')[1])) To achieve the same output as sudo pfctl -s nat when run in the shell itself. I am running the command and the Python attempt on macOS Sierra 10.12.5.

http://stackoverflow.com/comment/92236174
comment on: http://stackoverflow.com/a/52651543
type: AnswerComment
score: 0
has text: The index of `dfe` is numeric. The index of `df3` is strings. When you try to append `df3` to `dfe`, it tries to sort the index while it appends, to get the dataframe in the right order. It works, but it warns you that it can't put it in the right order, because it can't sort it. I edited my post with an example of why this makes python unhappy.
type: Comment

http://stackoverflow.com/a/52629885
type: AcceptedAnswer
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/92193737
score: 1
accepted answer of: http://stackoverflow.com/q/52629524
has comment: http://stackoverflow.com/comment/92193623
has body: I performed the test using R just to check if the results are the same and they are: t.test(x=c(99, 99, 22, 77, 99, 55, 44, 33, 20, 9999, 99, 99, 99), alternative = "two.sided", mu = 10, paired = FALSE, var.equal = FALSE, conf.level = 0.95) data: c(99, 99, 22, 77, 99, 55, 44, 33, 20, 9999, 99, 99, 99) t = 1.079, df = 12, p-value = 0.3018 alternative hypothesis: true mean is not equal to 10 95 percent confidence interval: -829.9978 2498.3055 sample estimates: mean of x 834.1538 You can see that the p-value is 0.3. This is a really interesting problem, I have a lot of issues with Hypothesis testing. First of all the sample size influences a lot, if u have a big sample size, lets say 5000 values, minor deviations from the expected value that you are testing will influence a lot the p-value, and so you will reject the null hypothesis most of the times, having small samples does the opposite. And what is happening here is that you have a high variance in the data. If you try to replace your data from [99, 99, 22, 77, 99, 55, 44, 33, 20, 9999, 99, 99, 99] To [99, 99, 99, 99, 100, 99, 99, 99, 99, 100, 99, 100, 100] So it has a really small variance, your p-value will be a lot smaller, even tho the mean of this one is probably closer to 10.
answers question: http://stackoverflow.com/q/52629524

http://stackoverflow.com/comment/92290793
type: Comment
type: QuestionComment
has text: 18-mm-dd is not a valid format because the year must be yyyy so if you have these values in excel its better convert using excel in the yyyy-mm-dd format and than use.
comment on: http://stackoverflow.com/q/52681186
score: 0

http://stackoverflow.com/comment/92339843
has text: `apply_along_axis` makes iteration over many dimensions easier, but not faster. You only need to iterate on one dimension, so `apply_along` won't even help with the simplification.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52702859

http://stackoverflow.com/comment/92345336
has text: if key in dict: return dict[key] == password
comment on: http://stackoverflow.com/q/52709390
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92387519
has text: @Ry- got the point. In fact you can try `x = 2; tuple(x)` to get the same error. `tuple()` is a conversion function, not a wrapping function.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52731195

http://stackoverflow.com/a/52633304
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52633252
score: 1
has body: languages = [...] sentences = [...] for sentence in sentences: for language in languages: if language in sentence: ...
upvote count: 1

http://stackoverflow.com/comment/92385089
comment on: http://stackoverflow.com/a/52729922
has text: This is basically a reimplementation of [`contextlib.nested`](https://docs.python.org/2.7/library/contextlib.html#contextlib.nested), with the same error-prone quirks that led to the removal of `contextlib.nested` in Python 3, particularly the failure to clean up earlier context managers if later context managers fail in `__init__` or `__enter__`.
score: 0
type: Comment
type: AnswerComment

graph
tags question: http://stackoverflow.com/q/52613002
tags question: http://stackoverflow.com/q/52651536
tags question: http://stackoverflow.com/q/52600820
tag name: graph
tags question: http://stackoverflow.com/q/52598496
tags question: http://stackoverflow.com/q/52706635
tags question: http://stackoverflow.com/q/52634731
type: Tag
tags question: http://stackoverflow.com/q/52611997
tags question: http://stackoverflow.com/q/52741742

http://stackoverflow.com/comment/92141495
type: Comment
comment on: http://stackoverflow.com/q/52603503
score: 0
type: QuestionComment
has text: @AayushMahajan check edited question

http://stackoverflow.com/comment/92344627
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52695310
has text: thank you, I adjusted my code accordingly, now it works!
score: 0

http://stackoverflow.com/q/52747073
tagged with: oop
has body: I try to assign variables through function when I create a class instance, but it doesn't work. class Test: def __init__(self, l): self.l = l self.func(self.l) # or I tried self.func(l) self.z = None self.y = None def func(self, l): self.z = l # doesn't work self.y = 123 # doesn't work x = Test('test') print(x.z) # = None print(x.y) # = None Can somebody explain this things, links are welcome to!
possible better answer: http://stackoverflow.com/a/52747521
answer count: 3
score: -2
has answer: http://stackoverflow.com/a/52747106
has comment: http://stackoverflow.com/comment/92418709
accepted answer: http://stackoverflow.com/a/52747106
favorite count: 0
has answer: http://stackoverflow.com/a/52747521
has answer: http://stackoverflow.com/a/52747146
tagged with: python
upvote count: 0
downvote count: 2
has title: Python can't assign object variable
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/92115793
type: QuestionComment
has text: The `ubuntu` image is not xenial, so it does not use glibc 2.23, as in your example. Please show us the `FROM` line you use.
comment on: http://stackoverflow.com/q/52589268
score: 0
type: Comment

http://stackoverflow.com/q/52745750
tagged with: jupyter-notebook
score: 4
tagged with: opencv
has comment: http://stackoverflow.com/comment/130955947
type: UnansweredQuestion
upvote count: 4
answer count: 0
downvote count: 0
favorite count: 0
has title: OpenCV cv2.imshow() function keep running in Jupyter Notebook using python 3
type: Question
tagged with: python
has body: I just start to learn OpenCV in Python and mainly use jupyter notebook. The sample I learnt comes from course https://pythonprogramming.net/loading-images-python-opencv-tutorial/ I load an image using cv2.imread() and want to show it up using cv2.imshow(). The image was shown successfully but the program keeps running and can't be interrupted. May I know why? Please check following codes: import cv2 import numpy as np import matplotlib.pyplot as plt %matplotlib inline img=cv2.imread('sample1.jpg',cv2.IMREAD_GRAYSCALE) cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() # This part of code keeps running.

http://stackoverflow.com/comment/92367682
has text: Not sure where 19800 came from
score: 0
comment on: http://stackoverflow.com/a/52718246
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52603891
type: AnsweredQuestion
score: 1
has body: So I have a list of series as the following: groupdf1 Out[304]: [90-95 9 &gt;100 1 80-90 1 50-80 1 Name: bucket, dtype: int64, 80-90 9 95-100 1 90-95 1 50-80 1 Name: bucket, dtype: int64, 80-90 10 90-95 1 50-80 1 Name: bucket, dtype: int64, 80-90 11 95-100 1 Name: bucket, dtype: int64, 50-80 9 What I'm trying is to create a dataframe like the following: bucket.1 bucket.2 bucket.3 bucket.4 90-95 9 1 1 NaN &gt;100 1 NaN NaN NaN 80-90 1 9 10 11 50-80 1 1 1 NaN 95-100 NaN NaN NaN 1 which is basically merging each of the series on the index. I'm not being able to run it in a loop. I'm getting the following error: groupdf=pd.DataFrame(groupdf1[0]) for i in range(1,len(groupdf1)): groupdf2=pd.DataFrame(groupdf1[i]) groupdf.concat(groupdf2) Traceback (most recent call last): File "&lt;ipython-input-278-4c8876ecdb74&gt;", line 4, in &lt;module&gt; groupdf.concat(groupdf2) File "C:\Users\hp1\Anaconda3\lib\site-packages\pandas\core\generic.py", line 3081, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'concat' Can somebody please help me out here? Thanks.
tagged with: loops
type: Question
possible better answer: http://stackoverflow.com/a/52603922
answer count: 2
has answer: http://stackoverflow.com/a/52603922
upvote count: 1
has title: Merging multiple series in loop in pandas
favorite count: 0
tagged with: series
tagged with: pandas
has answer: http://stackoverflow.com/a/52603913
accepted answer: http://stackoverflow.com/a/52603913
tagged with: python
tagged with: merge
downvote count: 0

http://stackoverflow.com/comment/92175488
type: AnswerComment
has text: Might be the case that you're using python2
type: Comment
comment on: http://stackoverflow.com/a/52620397
score: 0

http://stackoverflow.com/q/52698854
has comment: http://stackoverflow.com/comment/92334326
has comment: http://stackoverflow.com/comment/92324306
has comment: http://stackoverflow.com/comment/92324429
has title: ImportError: bad magic number in 'dateparser': b'\x03\xf3\r\n'
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/55514371
has comment: http://stackoverflow.com/comment/92324299
linked to: http://stackoverflow.com/q/514371
tagged with: python
has body: When I tried to import module dateparser, it gave me this error ImportError: bad magic number in 'dateparser': b'\x03\xf3\r\n' Is there a way to fix this?
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/92324371
accepted answer: http://stackoverflow.com/a/55514371
type: Question

http://stackoverflow.com/q/52609858
accepted answer: http://stackoverflow.com/a/52617863
tagged with: python
has answer: http://stackoverflow.com/a/52610136
tagged with: merge
tagged with: append
answer count: 4
type: AnsweredQuestion
score: 3
tagged with: join
has comment: http://stackoverflow.com/comment/92173349
downvote count: 1
has title: Concat/join/merge multiple dataframes based on row index (number) of each individual dataframes
type: Question
has body: I want to read every nth row of a list of DataFrames and create a new DataFrames by appending all the Nth rows. Let's say we have the following DataFrames: &gt;&gt;&gt; df1 A B C D 0 -0.8 -2.8 -0.3 -0.1 1 -0.1 -0.9 0.2 -0.7 2 0.7 -3.3 -1.1 -0.4 &gt;&gt;&gt; df2 A B C D 0 1.4 -0.7 1.5 -1.3 1 1.6 1.4 1.4 0.2 2 -1.4 0.2 -1.7 0.7 &gt;&gt;&gt; df3 A B C D 0 0.3 -0.5 -1.6 -0.8 1 0.2 -0.5 -1.1 1.6 2 -0.3 0.7 -1.0 1.0 I have used the following approach to get the desired df: df = pd.DataFrame() df_list = [df1, df2, df3] for i in range(len(df1)): for x in df_list: df = df.append(x.loc[i], ignore_index = True) Here's the result: &gt;&gt;&gt; df A B C D 0 -0.8 -2.8 -0.3 -0.1 1 1.4 -0.7 1.5 -1.3 2 0.3 -0.5 -1.6 -0.8 3 -0.1 -0.9 0.2 -0.7 4 1.6 1.4 1.4 0.2 5 0.2 -0.5 -1.1 1.6 6 0.7 -3.3 -1.1 -0.4 7 -1.4 0.2 -1.7 0.7 8 -0.3 0.7 -1.0 1.0 I was just wondering if there is a pandas way of rewriting this code which would do the same thing (maybe by using .iterrows, pd.concat, pd.join, or pd.merge)? Cheers Update Simply appending one df after another is not what I am looking for here. The code should do: df.row1 = df1.row1 df.row2 = df2.row1 df.row3 = df3.row1 df.row4 = df1.row2 df.row5 = df2.row2 df.row6 = df3.row2 ...
has answer: http://stackoverflow.com/a/52617863
upvote count: 4
linked to: http://stackoverflow.com/q/36526282
tagged with: pandas
has answer: http://stackoverflow.com/a/52610215
favorite count: 0
has comment: http://stackoverflow.com/comment/92155201
has comment: http://stackoverflow.com/comment/92172788
has answer: http://stackoverflow.com/a/52610263
has comment: http://stackoverflow.com/comment/92169413
possible better answer: http://stackoverflow.com/a/52610136

http://stackoverflow.com/q/52600305
upvote count: 1
has comment: http://stackoverflow.com/comment/92135274
has body: I have these data exports that are populating every hour in a particular directory, and i'm hoping to have a script that reads all the files and appends them into one master dataframe in Python. Only issue is, since they are populating every hour, I don't want to append existing or already added csv files to the master dataframe. I'm very new to Python, and so far have only been able to load all the files in the directory and append them all, using the below code: import pandas as pd import os import glob path = os.environ['HOME'] + "/file_location/" allFiles = glob.glob(os.path.join(path,"name_of_files*.csv")) df = pd.concat((pd.read_csv(f) for f in allFiles), sort=False) With the above code, it looks into the file_location and imports any files with the name "name_of_files" &amp; uses a wildcard as the tail of each of the files will be different. I could continue to do this, but i'm literally going to have hundreds of files and don't want to import them all and append/concat them each and every hour. To avoid this i'd like to have that master data frame mentioned above and just have new csv files that populate each hour to be automatically appended to that existing master df. Again super new to Python, so not even sure what to do next. Any advice would be greatly appreciated!
score: 1
has comment: http://stackoverflow.com/comment/92171386
type: Question
has comment: http://stackoverflow.com/comment/92135084
downvote count: 0
has comment: http://stackoverflow.com/comment/92298328
has comment: http://stackoverflow.com/comment/92137233
favorite count: 0
has comment: http://stackoverflow.com/comment/92168970
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Appending incoming csv files in Python to a master data frame
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/92116062
score: 1
type: Comment
has text: you can simplify as `any(k in string for k in dictionary)`
comment on: http://stackoverflow.com/a/52590625
type: AnswerComment

http://stackoverflow.com/q/52629538
answer count: 2
has answer: http://stackoverflow.com/a/52631768
tagged with: polygon
downvote count: 0
has title: Optimizing Polygon Search
tagged with: http://stackoverflow.com/tag/r
has body: I split de world in X random polygons. Then I am given a coordinate C1, for instance (-21.45, 7.10), and I want to attribute the right polygon to this coordinate. The first solution is to apply my ‘point_in_polygon’ algorithm (given a set of coordinates that defines a polygon and a coordinate that defines a point, tell me if the point is inside or not) on each polygon until I find the right one. But that is very expensive if I have a lot of points to put in a lot of polygons. An improvement on that relies on the following idea: To optimise the search, I create a grid (a collection) with a step n, k where I already attribute each pair of coordinates such that: for i=-180 to 180 step n for j = -90 to 90 step k grid.add(i,j) Then I create a dictionary, and for each pair in the collection I find the corresponding polygon For each g in grid For each p in polygons If point_in_polygon(g,p) == True my_dict(g) = p Then, when I receive C1, I look for the closest coordinate in my grid, let’s say g1. Thanks to my_dict, I can get quickly p1 = my_dict(g1) Then I compute point_in_polygon(C1, p1) which is likely to be true. If it’s not, I find the closest g which is assigned to a different polygon, and I redo a test. Etc. until I have found the right polygon. Now, the question is: what is the optimal n, k to create the grid? So that I can find the right polygon in the minimum number of steps. I don’t want it too low, because the search of the closest g which is assigned to a different polygon might be expensive. I don’t want it too high as well, because then I might be missing some polygons and then the search never converges. My intuition is that the smallest polygon is going to give the steps. I am not sure if this is a programming problem, a maths problem, or just something I can find empirically, that's why I ask it here. Any inputs appreciated!
tagged with: python
accepted answer: http://stackoverflow.com/a/52630333
favorite count: 0
upvote count: 1
type: AnsweredQuestion
tagged with: algorithm
score: 1
possible better answer: http://stackoverflow.com/a/52631768
has answer: http://stackoverflow.com/a/52630333
type: Question

http://stackoverflow.com/q/52628596
type: Question
score: 0
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has answer: http://stackoverflow.com/a/52628895
has body: I'm pretty new to python, so forgive me if this is a long explanation to a simple problem. I need some help in understanding how to use a dictionary to find matches from csv list, then print the key in a reporting type output. Goal: I have a list of clear text privacy data like Social Security Numbers. I need to compare the hash of that clear text and at the same time, obfuscate the clear text to the last 4 digits (XXX-XX-1245). If there is a match from my clear text hash, to a hash I already have in a CSV lookup, I do a mini report linking demographic information of who the found hash might belong to. Also, because nothing is easy, in the mini report needs to print the obfuscated SPI value. output should look like this if hash I just generated, matches the hash of column 2 in my spreadsheet: user@gmail.com Full Name Another Full Name xxx-xx-1234 location1 location2 Problem: All of the hash, obfuscation, and matching is done and stored in lists and works correctly. I need help figuring out how to print the key from the dictionary with my other columns below without printing the whole set each time in the for-loop. This works outside of my reader: for i in hashes_ssnxxxx: print(i) but I do not know how to take that value and put it in my print statement inside of the reader. clear_text_hash = [] #Where Hash of clear text value found is stored obfuscate_xxxxssn = [] #Where obfuscated SPI found by using re.sub is stored #Zip them in a dictonary to keep the two related hashes_and_ssnxxxx = dict(zip(obfuscate_xxxxssn,clear_text_hash)) book_of_record = open('path\to\bookofrecord.csv', 'rt', encoding='UTF-8') a1 = csv.reader(book_of_record, delimiter=',') for row in a1: hashes = row[2] if hashes in hashes_ssnxxxx.values(): print(row[16], row[6], hashes_ssnxxxx.keys(), row[13], row[35], row[18], row[43]) UPDATE [Solved] using the list comprehension suggested by @tianhua liao all it needed was: if hashes in hashes_ssnxxxx.values(): obfuscate = [k for k,v in hashes_ssnxxxx.it…
has title: Printing Dictionary Key if Values were found in CSV List
has comment: http://stackoverflow.com/comment/92191268
accepted answer: http://stackoverflow.com/a/52628895
tagged with: md5
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: apache-tika

http://stackoverflow.com/comment/92225398
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52646004
score: 0
has text: This makes sense. Thanks @cryptonome

http://stackoverflow.com/q/52729169
has title: plot_date function set xticks for hourly data
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/92383525
answer count: 1
accepted answer: http://stackoverflow.com/a/52734309
tagged with: datetime
tagged with: python
tagged with: plot
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92384077
score: 0
has body: I currently have a function that creates a time series graph from time/date data that is in MM-DD-YYYY HH-MM format. I am unsure as to how to change the x axis ticks such that it displays hours as well as the date as it currently only shows dates. The set_major_locator line I included only returns ticks that have the year even though I have specified the hour_locator and the data is hourly. def graph(region): fig = plt.figure(num=None, figsize=(60, 20), dpi=100, facecolor='w', edgecolor='k') df_da_region = df_da_abv_09[df_da_abv_09['Settlement Point'] == region] df_rt_region = df_rt_abv_09[df_rt_abv_09['Settlement Point Name'] == region] fig = plt.plot_date(x=list(df_da_region['DateTime']), y=list(df_da_region['Settlement Point Price']), xdate = True, fmt="r-", linewidth=0.7) fig = plt.plot_date(x=list(df_rt_region['DateTime']), y=list(df_rt_region['Settlement Point Price']), xdate = True, fmt="g-", alpha=0.5, linewidth=0.7) fig = plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=5)) plt.show()
has comment: http://stackoverflow.com/comment/92383849
type: Question
has answer: http://stackoverflow.com/a/52734309

http://stackoverflow.com/q/52718366
type: Question
has comment: http://stackoverflow.com/comment/92362251
has comment: http://stackoverflow.com/comment/92362117
linked to: http://stackoverflow.com/q/12332975
has comment: http://stackoverflow.com/comment/92362223
has comment: http://stackoverflow.com/comment/92362677
has answer: http://stackoverflow.com/a/52720132
score: 0
answer count: 1
has title: ImportError: No module named <> after installing using python code
has comment: http://stackoverflow.com/comment/92362362
has comment: http://stackoverflow.com/comment/92362215
has comment: http://stackoverflow.com/comment/92362287
has body: Assuming I don't have pandas and numpy installed in my Python, How can I refresh my terminal after successfully install a module. I tried installing these 2 modules using a code in my install.py: try: import pandas as pd except ImportError: from pip._internal import main as pip pip(['install', '--user', 'pandas']) try: import numpy as np,pandas as pd except ImportError: from pip._internal import main as pip pip(['install', '--user', 'numpy']) print "Dependencies installed successfully" Then I import it to my combined.py then imported pandas and numpy from install import * import pandas as pd import numpy as np The installation was successful but after that this error occurs: import pandas as pd ImportError: No module named pandas When I tried to run it, of course pandas and numpy are installed, It doesn't show the error, I think the terminal didn't recognize the module installed. Any Solutions for this?
tagged with: python
linked to: http://stackoverflow.com/q/25384922
has comment: http://stackoverflow.com/comment/92362257
type: UnansweredQuestion

http://stackoverflow.com/comment/92334258
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52703725
has text: I think what you are looking for is breadcrumbs, see this question https://stackoverflow.com/questions/826889/how-to-implement-breadcrumbs-in-a-django-template

pyspark
tags question: http://stackoverflow.com/q/52671564
tags question: http://stackoverflow.com/q/52702282
tags question: http://stackoverflow.com/q/52619099
tags question: http://stackoverflow.com/q/52620464
tags question: http://stackoverflow.com/q/52728680
tags question: http://stackoverflow.com/q/52597455
tags question: http://stackoverflow.com/q/52719122
tags question: http://stackoverflow.com/q/52723755
tags question: http://stackoverflow.com/q/52596370
tags question: http://stackoverflow.com/q/52594878
tags question: http://stackoverflow.com/q/52616254
tags question: http://stackoverflow.com/q/52685609
tags question: http://stackoverflow.com/q/52729792
type: Tag
tags question: http://stackoverflow.com/q/52673621
tags question: http://stackoverflow.com/q/52633549
tags question: http://stackoverflow.com/q/52629332
tags question: http://stackoverflow.com/q/52695236
tags question: http://stackoverflow.com/q/52622076
tags question: http://stackoverflow.com/q/52653974
tags question: http://stackoverflow.com/q/52742287
tags question: http://stackoverflow.com/q/52693510
tags question: http://stackoverflow.com/q/52631288
tags question: http://stackoverflow.com/q/52714588
tags question: http://stackoverflow.com/q/52699765
tags question: http://stackoverflow.com/q/52616773
tags question: http://stackoverflow.com/q/52724260
tags question: http://stackoverflow.com/q/52740868
tags question: http://stackoverflow.com/q/52668017
tags question: http://stackoverflow.com/q/52710822
tags question: http://stackoverflow.com/q/52706238
tags question: http://stackoverflow.com/q/52598366
tags question: http://stackoverflow.com/q/52645253
tags question: http://stackoverflow.com/q/52649030
tags question: http://stackoverflow.com/q/52675628
tags question: http://stackoverflow.com/q/52609143
tags question: http://stackoverflow.com/q/52702407
tags question: http://stackoverflow.com/q/52722315
tags question: http://stackoverflow.com/q/52685346
tags question: http://stackoverflow.com/q/52696414
tag name: pyspark
tags question: http://stackoverflow.com/q/52700395
tags question: http://stackoverflow.com/q/52745335

http://stackoverflow.com/comment/92320059
type: QuestionComment
has text: @U9-Forward But let's not guess and ask the OP. Because if it's `''`, then the ratios are not numbers anymore.
comment on: http://stackoverflow.com/q/52696762
type: Comment
score: 1

http://stackoverflow.com/comment/92310177
has text: Note : you might want to add `d['entry_id']` to `db_entry_ids` in order to avoid duplicates .
type: Comment
comment on: http://stackoverflow.com/a/52691081
score: 0
type: AnswerComment

http://stackoverflow.com/a/52740381
score: 1
answers question: http://stackoverflow.com/q/52740254
downvote count: 1
has body: As proposed by @Matthieu Brucher, you can use the sklearn split test/train function: http://scikit-learn.org/0.16/modules/generated/sklearn.cross_validation.train_test_split.html
upvote count: 2
type: Answer

http://stackoverflow.com/a/52638480
type: Answer
has body: you could try this code. However, could not obtain empty lists import numpy as np import pandas as pd # the data a1 = [np.array([[83, 84]]), np.array([[21, 24], [32, 53],[54, 56]]), np.array([[21,24],[32, 37],[45, 46]]), np.array([]), np.array([])] # create a data frame to store data in df = pd.DataFrame(columns=['pair', 'index', 'difference']) for j, item in enumerate(a1): a = item.ravel() # convert 2d array to 1d array for i in range(len(a)//2): difference = a[i*2+1] - a[i*2] pair = [a[i*2], a[i*2+1]] index = [j, np.where(np.all(item==pair,axis=1))[0]] df.loc[len(df)] = [pair, index, difference] df.sort_values(by='difference', ascending=False, inplace=True) # sort based on diff print(df) pair index difference 2 [32, 53] [1, [1]] 21 5 [32, 37] [2, [1]] 5 1 [21, 24] [1, [0]] 3 4 [21, 24] [2, [0]] 3 3 [54, 56] [1, [2]] 2 0 [83, 84] [0, [0]] 1 6 [45, 46] [2, [2]] 1 a1_sorted = df['pair'].tolist() print(a1_sorted) [[32, 53], [32, 37], [21, 24], [21, 24], [54, 56], [83, 84], [45, 46]]
answers question: http://stackoverflow.com/q/52638053
score: 0

http://stackoverflow.com/q/52600243
type: Question
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/52601120
accepted answer: http://stackoverflow.com/a/52601418
has answer: http://stackoverflow.com/a/52601120
has comment: http://stackoverflow.com/comment/92135019
has comment: http://stackoverflow.com/comment/92135501
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/92135330
score: -3
has body: I have a data frame of some features and corresponding years. Each value of the feature is listed for different years. I need to compare the values of a specific year with that 7 years earlier. So basically I need to define a function that will generate two columns one will give me the value of the feature from the table for a specific year and the other one for the same feature but 7 years earlier. How can I do that? feature year value1 2001 value1 2008 vlaue2 1996 etc e.g. I want to compare value1(2008) with value1(2008 - 7) etc. there should also be some conditional statements as year 2000 can't be compared with (2000-7 =1993) because there is no value for the feature for year (1993) for example.
has answer: http://stackoverflow.com/a/52601418
type: AnsweredQuestion
upvote count: 0
favorite count: 0
has title: Selecting values from the same dataframe but for different years

http://stackoverflow.com/q/52659204
score: 1
has comment: http://stackoverflow.com/comment/92507037
favorite count: 0
has title: Efficient Paste / Composite Masked Image in Pillow / Numpy
has answer: http://stackoverflow.com/a/52670560
type: Question
tagged with: python
upvote count: 1
answer count: 1
tagged with: python-imaging-library
type: UnansweredQuestion
tagged with: numpy
has body: I have two png images: heart40.png (40x40 with transparent background) -- https://i.sstatic.net/lEYof.jpg background40.png (40x40) -- https://i.sstatic.net/AbGTI.jpg The image is partitioned into 8x8-pixel grids and numbered from 1 -- --------------------- | 1 | 2 | 3 | 4 | 5 | --------------------- | 6 | ... |10 | ... |21 | ... |25 | --------------------- I want only selected grids, e.g., (1, 5, 8, 13, 23), from heart40.png to overlay onto the background40.png, result -- https://i.sstatic.net/svF5C.jpg I'm using Pillow (don't really want to switch to another image library unless there is a show-stopper). The following code works -- import numpy as np from math import ceil from PIL import Image, ImageDraw def square_id_to_xy(square_id): grid_count = int(40 / 8) y_id = ceil(square_id / grid_count) x_id = square_id - (grid_count * (y_id-1)) return (x_id-1) * 8, (y_id-1) * 8 if __name__ == '__main__': im = Image.open("heart40.png").convert("RGBA") background_im = Image.open("background40.png").convert("RGBA") mask_im = Image.alpha_composite(background_im, im) show_square_ids = (1, 5, 8, 13, 23) for square_id in range(1, 26): if square_id in show_square_ids: continue x, y = square_id_to_xy(square_id) ImageDraw.Draw(mask_im).rectangle([(x, y), (x+7, y+7)], outline=0, fill=1) background_im.paste(mask_im, (0, 0), mask_im) background_im.save("background_pasted.png") As I'm drawing transparent squares for all grids that I do not want to show, this can be rather inefficient when there are thousands of grids but I only want to show a few of them. So the question is: is there a more efficient way?
has comment: http://stackoverflow.com/comment/92522916
downvote count: 0

http://stackoverflow.com/comment/92139909
has text: I guess they will be lists since they are appended to lower in the code, with the studentNumber being the index?
score: 0
comment on: http://stackoverflow.com/q/52602835
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52663518
has body: According to the Python 3 documentation for subprocess.Popen, the class constructor takes an optional argument text (which is supposed to control whether the file objects stdin, stdout and stderr are opened in text mode). However, when I try setting text=true upon construction of a Popen object, I get the error Failed: TypeError: __init__() got an unexpected keyword argument 'text' and when I look in the source code (I'm using Python 3.6.4), the constructor takes no argument text. What is going on here? Why does the documentation say the constructor takes an optional argument text when it doesn't in the version of subprocess.py that I have?
tagged with: python
type: AnsweredQuestion
tagged with: subprocess
possible better answer: http://stackoverflow.com/a/69917881
accepted answer: http://stackoverflow.com/a/52663589
has answer: http://stackoverflow.com/a/69917881
has title: Python subprocess.Popen doesn't take text argument
upvote count: 17
type: Question
linked to: http://stackoverflow.com/q/53209127
tagged with: python-3.6
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52663589
score: 17
favorite count: 0

http://stackoverflow.com/comment/92300096
type: QuestionComment
comment on: http://stackoverflow.com/q/52683985
has text: Just start the command from Python and retrieve its output. You could also avoid the additional process by replicating the `socat` functionality.
score: 2
type: Comment

http://stackoverflow.com/comment/92241316
score: 0
comment on: http://stackoverflow.com/q/52654805
type: QuestionComment
type: Comment
has text: @ModusTollens Thanks, good to know! New around here...

http://stackoverflow.com/comment/92247844
type: AnswerComment
has text: invalid syntax, but this is what im looking for, can your fix your answer so i can accept it
comment on: http://stackoverflow.com/a/52658655
score: 0
type: Comment

http://stackoverflow.com/comment/130966874
score: 0
type: AnswerComment
has text: "those are two separate problems. The first is solved at the model layer, the latter at the template layer (or form layer in case of a form). "– Willem Van Onsem
type: Comment
comment on: http://stackoverflow.com/a/62257704

http://stackoverflow.com/a/52668930
accepted answer of: http://stackoverflow.com/q/52668701
answers question: http://stackoverflow.com/q/52668701
has comment: http://stackoverflow.com/comment/92267675
has body: Here is my short solution using the list.count() method: array = [[a,b],[a,b,c],[a],[],[],[],[]] print(array.count([])) # 4
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/92209234
type: Comment
comment on: http://stackoverflow.com/a/52636245
has text: Maybe overkill, but if it gets you up and running and you have the memory to spare... why not :)
type: AnswerComment
score: 0

http://stackoverflow.com/q/52641515
upvote count: 1
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/52641714
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/92215765
answer count: 2
possible better answer: http://stackoverflow.com/a/52641673
has comment: http://stackoverflow.com/comment/92215609
downvote count: 0
has comment: http://stackoverflow.com/comment/92226548
has answer: http://stackoverflow.com/a/52641673
favorite count: 0
has answer: http://stackoverflow.com/a/52641714
has body: I'm using a jsondiff library which returns the following result: a = {'TIERS': {delete: ['APP']}} i'm at a loss as to how this is a valid representation of a dict (or JSON for that matter)? shouldnt this fail because delete is not in quotes? however, this seems to come out as a valid dictionary. this is the full library file: https://github.com/ZoomerAnalytics/jsondiff/blob/master/jsondiff/init.py the relevant parts of the library(atleast from what i can gather): def emit_dict_diff(self, a, b, s, added, changed, removed): if s == 0.0: return b elif s == 1.0: return {} else: d = {} if added: d[insert] = added if changed: d[update] = changed if removed: d[delete] = list(removed.keys()) when i use the dump (json.dump output) option for this library the result is: a = '{"TIERS": {"$delete": ["APP"]}}' i can't find anything on this type of syntax and realize this might be googlable, so sorry if this question comes across as lazy. edit: python 3.6+ jsondiff library is used as a=jsondiff.diff(json1,json2,load=True)
has title: A question about python's JSON/dict conversion

http://stackoverflow.com/comment/92328204
comment on: http://stackoverflow.com/q/52700904
type: Comment
type: QuestionComment
score: 1
has text: No: `&` and `|` do *not* short-circuit, since you simply call a function behind the curtains with the two operands evaluated. Of course Numpy/pandas/... can implement this function in a "lazy-functional" way, but if there is no logic around this, it thus does not shortcircuit. Note that `&` and `|` do *not* per se work with booleans: one can return any kind of value.

http://stackoverflow.com/q/52709876
has comment: http://stackoverflow.com/comment/92376065
has comment: http://stackoverflow.com/comment/92371428
has comment: http://stackoverflow.com/comment/92379558
has answer: http://stackoverflow.com/a/52724770
answer count: 3
tagged with: sas
tagged with: regex-lookarounds
has comment: http://stackoverflow.com/comment/92345992
downvote count: 0
accepted answer: http://stackoverflow.com/a/52728011
has comment: http://stackoverflow.com/comment/92370706
favorite count: 0
has comment: http://stackoverflow.com/comment/92371535
has body: Please note: I'm programming in Python (version 3.6), but would also like to port these regexes to SAS as well. The large picture here is that I'm working with a SAS log, and I want to exclude lines printed to the log that are from %include statements. Basically, what I'm trying to accomplish would look like this: 54210 proc sort data=inds out=outds; And the lines that I DON'T want will look like this: 33406 +%global var1 var2 var3; The key is that the 11th character will be a '+', but there will always be a group of numbers to the left followed by a group of spaces, whose length will ultimately be 11 spaces - unless it's an %include line, which I want to exclude. What I have so far is this: ^[0-9]{1,11} (?! {2,10}\+) This has worked to grab what I want exactly from the logs that I've tested, but it's far from right. The easy way out would be using this expression: ^[0-9]{1,11} {3,10} And then add an extra condition that will ignore the line if the 11th character is a '+', but can I do this in a single regex? I came across lookaheads/lookbehinds working on this, but the problem is that the first matched group can vary in length, which moves around where the '+' would be expected - so is there a way that I can match a group within a set length, and then negate the match if it's followed by a character?
possible better answer: http://stackoverflow.com/a/52710500
has title: RegEx how to negate a match based on a character in a specific position
has answer: http://stackoverflow.com/a/52710500
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92370392
has comment: http://stackoverflow.com/comment/92379102
upvote count: 3
tagged with: regex-negation
has comment: http://stackoverflow.com/comment/92379679
has comment: http://stackoverflow.com/comment/92380956
has comment: http://stackoverflow.com/comment/92373094
has answer: http://stackoverflow.com/a/52728011
type: Question
score: 3
has comment: http://stackoverflow.com/comment/92379059

http://stackoverflow.com/comment/92333561
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52673439
has text: Thank you for the help. This is exactly what I wanted the output to look like. Thanks for your help.
score: 1

http://stackoverflow.com/comment/92186607
type: QuestionComment
comment on: http://stackoverflow.com/q/52620992
score: 0
has text: does this help as a solution? https://stackoverflow.com/questions/37227780/flask-session-persisting-after-close-browser
type: Comment

http://stackoverflow.com/q/52658571
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
downvote count: 0
score: 1
type: Question
has body: I'm trying to plot two things: 1) Output after applying each filter (Total 32 outputs in case of "Conv2D(32, (3,3)....) 2) Filter which is learned/generated while learning (Total 32 filters as mentioned above) Below is my code and demo image is: Sample Image First I've just read an image: import cv2 import matplotlib.pyplot as plt %matplotlib inline` plt.imshow(face) cv2.waitKey(0) Ouput of above code Then I created simple 1 layer CNN with Keras: from keras.models import Sequential from keras.layers import Conv2D import numpy as np model = Sequential() model.add(Conv2D(32, (3, 3), input_shape = face.shape, padding='valid', activation = 'relu')) face_batch = np.expand_dims(face, axis=0) conv_face = model.predict(face_batch) def visualize_face(face_batch): face = np.squeeze(face_batch, axis=0) print (face.shape) plt.imshow(face[:,:,31]) The above last line vary from 0 to 31 (total 32 filters) for whichever filter I want to visualize. Then final cell would be: print(np.squeeze(conv_face, axis=0).shape) visualize_face(conv_face) Output of above code So is this a correct way to visualize outputs of filter applied on image? Now come to my second question: I'm trying to plot all those 32 filters which are learned by a model while getting those outputs. So can anyone help me with my query? Thank you in advance :)
tagged with: filter
tagged with: layer
upvote count: 1
favorite count: 0
has title: CNN Layer Visualization
answer count: 0

http://stackoverflow.com/comment/92285080
comment on: http://stackoverflow.com/a/52677983
has text: Thank you very much........, sir
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92451204
has text: Hi eanderson, using dir(), I was able to find the host attribute of the server. I also used the Python inbuilt getattr() to display it's value. Thank you very much!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52752545
type: Comment

http://stackoverflow.com/q/52688301
downvote count: 3
has answer: http://stackoverflow.com/a/60700978
score: -3
answer count: 2
upvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52688421
has title: global name error in class python program
accepted answer: http://stackoverflow.com/a/52688421
type: Question
type: AnsweredQuestion
has body: Define a class Circle, whose objects are initialized with radius as it's attribute. Ensure that the object creation raises RadiusInputError, a user defined exception, when the input radius is not a number. For e.g : Circle('hello') -> RadiusInputError : 'hello' is not a number Below code i have written and throwing error: class circle: def __init__(self,r): self.r=r try: if isinstance(r,str): raise RadiusInputError("error ") else: print(r) except RadiusInputError as error: print(error) circle("Hello") Error seeing as: except RadiusInputError as error: NameError: global name 'RadiusInputError' is not defined
possible better answer: http://stackoverflow.com/a/60700978

http://stackoverflow.com/comment/92243550
comment on: http://stackoverflow.com/q/52655948
score: 0
type: QuestionComment
type: Comment
has text: Your code is vulnerable to directory traversal. The user can send `path=../../../../etc/shadow` to modify your passwords, for example.

http://stackoverflow.com/q/52671308
tagged with: series
has comment: http://stackoverflow.com/comment/92273463
has title: Counting the number of consecutive values that meets a condition (Pandas Dataframe)
tagged with: pandas
has answer: http://stackoverflow.com/a/60080363
has body: So I created this post regarding my problem 2 days ago and got an answer thankfully. I have a data made of 20 rows and 2500 columns. Each column is a unique product and rows are time series, results of measurements. Therefore each product is measured 20 times and there are 2500 products. This time I want to know for how many consecutive rows my measurement result can stay above a specific threshold. AKA: I want to count the number of consecutive values that is above a value, let's say 5. A = [1, 2, 6, 8, 7, 3, 2, 3, 6, 10, 2, 1, 0, 2] We have these values in bold and according to what I defined above, I should get NumofConsFeature = 3 as the result. (Getting the max if there are more than 1 series that meets the condition) I thought of filtering using .gt, then getting the indexes and using a loop afterwards in order to detect the consecutive index numbers but couldn't make it work. In 2nd phase, I'd like to know the index of the first value of my consecutive series. For the above example, that would be 3. But I have no idea of how for this one. Thanks in advance.
has comment: http://stackoverflow.com/comment/92272552
linked to: http://stackoverflow.com/q/52629219
tagged with: python
has comment: http://stackoverflow.com/comment/92311662
has comment: http://stackoverflow.com/comment/92273927
favorite count: 0
possible better answer: http://stackoverflow.com/a/60080363
has comment: http://stackoverflow.com/comment/92989017
answer count: 5
has answer: http://stackoverflow.com/a/52672007
has answer: http://stackoverflow.com/a/52672358
type: AnsweredQuestion
upvote count: 9
has answer: http://stackoverflow.com/a/55123198
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92311442
has comment: http://stackoverflow.com/comment/92311501
type: Question
score: 9
tagged with: numpy
linked to: http://stackoverflow.com/q/52717996
has answer: http://stackoverflow.com/a/70109523
downvote count: 0
accepted answer: http://stackoverflow.com/a/52672358
has comment: http://stackoverflow.com/comment/92958084
has comment: http://stackoverflow.com/comment/92311978

http://stackoverflow.com/a/52617815
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52610645
has body: There is no way to get coverage.py 4.5.1 to do this. The 5.0 development switched the data storage to SQLite, so we should be able to add a feature to periodically flush the coverage data to the database.
upvote count: 2

http://stackoverflow.com/comment/92336150
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52704493
has text: how do I close the question by accepting the answer? Sorry im a beginner in stackoverflow ._. @Alexis

http://stackoverflow.com/a/52677793
has comment: http://stackoverflow.com/comment/101376907
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/126017053
has comment: http://stackoverflow.com/comment/107359319
accepted answer of: http://stackoverflow.com/q/52677479
has body: It appears this is a rather simple solution. After poking around the c++ examples, the realsense sdk provides a function known as get_distance(x,y) where it will return the depth distance according to the x,y coords. Note that this function in python is exactly the same but must be called from the depth frame and the x and y must be cast to integer pipeline = rs.pipeline() config = rs.config() profile = pipeline.start(config) frames = pipeline.wait_for_frames() while True: depth_frame = frames.get_depth_frame() zDepth = depth_frame.get_distance(int(x),int(y))
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/101360521
answers question: http://stackoverflow.com/q/52677479
type: Answer

http://stackoverflow.com/q/52626698
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92188378
tagged with: matplotlib
has title: Python heatmap and colorbar colors are different
score: 0
has comment: http://stackoverflow.com/comment/92189436
tagged with: pandas
has comment: http://stackoverflow.com/comment/92189523
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52628745
accepted answer: http://stackoverflow.com/a/52628745
tagged with: seaborn
has body: I'm using matplotlib and seaborn to create a heatmap of my correlation matrix with specific colors representing dataranges. I am facing an issue where my colorbar does not represent the full spectrum of colors in the heatmap. edit: The issue lies with the colorbar in the range -0.5 to -0.3. The color here should be "royal blue." The correct color is represented in the heatmap but not the colorbar. Here is my code for the heatmap: from matplotlib import colors cmap = colors.ListedColormap(["navy", "royalblue", "lightsteelblue", "beige", "peachpuff", "salmon", "darkred"]) bounds = [-1, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 1] norm = colors.BoundaryNorm(bounds, cmap.N) This is applied to my data, corr_matrix. #Generate mask for correlation matrix mask = np.zeros_like(corr_matrix, dtype=np.bool) mask[np.triu_indices_from(mask)] = True #print the correlation matrix fig, ax = plt.subplots() sns.heatmap(corr_matrix, annot=True, fmt='.4f', cmap=cmap, norm=norm, mask=mask, cbar=True, ax=ax, cbar_kws=dict(ticks=[-1, -0.5, -0.3, -0.1, +0.1, +0.3, +0.5, +1])) ax.set_title('Correllation Matrix') ax.set_yticklabels(ax.get_yticklabels(), rotation="horizontal") plt.show() Thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/92188965
type: AnsweredQuestion

http://stackoverflow.com/q/52601848
score: 0
tagged with: while-loop
answer count: 1
has answer: http://stackoverflow.com/a/52602043
tagged with: newtons-method
accepted answer: http://stackoverflow.com/a/52602043
tagged with: python
type: AnsweredQuestion
has title: Newton's method check in python
type: Question
has body: So this is my code for Newton's Method using a while loop, z is a complex argument : def which_root_z4(z , n): # function which takes 2 arguments; z and n fz = z ** 4 - 1 # defining f(z) dfz = 4 * z ** 3 # defining the first derivative of f(z) while n &gt; 0: # this block will continue looping until n = 0 z = z - fz / dfz #T he Newton-Raphson formula return which_root_z4(z, n-1) # after each iteration, the function begins again with the new value of z and n-1 return z I need to modify it such that it can check whether the function is going to converge or not, by testing to see if the distance to one of the roots is &lt; 0.25. I have no idea how to do this The roots of the equation are 1, -1 , i , i Thanks

http://stackoverflow.com/comment/92305476
has text: Please see [Why may I not upload images of code on SO when asking a question?](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question)
comment on: http://stackoverflow.com/q/52689004
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52676798
accepted answer: http://stackoverflow.com/a/52676944
type: AnsweredQuestion
has title: Image derivative - Sobel filters in Python SciPy
tagged with: sobel
tagged with: scipy
type: Question
has body: I'm reading the book "Programming Computer Vision with Python" by Jan Erik Solem, final draft (CC licence) is available here. On page 34 the result of applying the Sobel filters to an image is shown, see Fig 1.10, also shown below. When I run the code in the book, the image of the gradient magnitude, i.e. panel (d), looks reversed, see below. My question is, is this just because the author inverted the image, or is there some other reason? The Python code, adapted from the book with additions for plotting, is listed below. These are the image generated with the code in the book. Python Code from PIL import Image from numpy import * from pylab import * from scipy.ndimage import filters im = array(Image.open('empire.jpg').convert('L')) # Sobel derivative filters imx = zeros(im.shape) filters.sobel(im,1,imx) imy = zeros(im.shape) filters.sobel(im,0,imy) magnitude = sqrt(imx**2+imy**2) figure(figsize=(12,4)) gray() subplot(1,4,1) title('Oiginal') axis('off') imshow(im) subplot(1,4,2) title('imx') axis('off') imshow(imx) subplot(1,4,3) title('imy') axis('off') imshow(imy) subplot(1,4,4) title('magnitude') axis('off') imshow(magnitude) savefig('sobel.png') show() The image used in the example code
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52676944
tagged with: python

http://stackoverflow.com/comment/92351312
has text: nope, here protocol only refer to layer-4 protocol in OSI model. http is layer-7, it is a service.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52712618

http://stackoverflow.com/a/52592412
answers question: http://stackoverflow.com/q/52592140
type: Answer
has body: Suppress printing the empty dict {} by testing its length to be not zero. Assuming dd to be your dictionary. if len(dd.keys())&gt;0: [print(key, value[0][0]) for key, value in dd.items()] gives d2otag1p96 0 k43tbb7nic 0 90yuipi22i 18 for dd = dict({u'd2otag1p96': [[0, 20]], u'k43tbb7nic': [[0, 20]], u'90yuipi22i': [[18, 2]]}) and nothing for dd = dict{}
upvote count: 1
has comment: http://stackoverflow.com/comment/92119870
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92120143

http://stackoverflow.com/comment/92352061
type: QuestionComment
comment on: http://stackoverflow.com/q/52713154
has text: @KlausD. How does that impact here ? because, even from python interactive i could able to import requests successfully.
score: 0
type: Comment

http://stackoverflow.com/q/52615130
has answer: http://stackoverflow.com/a/52616235
answer count: 2
has comment: http://stackoverflow.com/comment/92164645
has answer: http://stackoverflow.com/a/52616240
tagged with: string
favorite count: 0
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/92165370
has comment: http://stackoverflow.com/comment/92164636
has body: I am trying to create an expression that will give me an output of yes for strings, 6,7,8 and an output of no for 9 &amp; 10. Any advice would be greatly appreciated! #The regular expression is ' ^&lt;[^&lt;&gt;]*&gt;$ ' print ( 'The regular expression used for 5 strings was "^&lt;[^&lt;&gt;]*&gt;$"' ) string6 = '&lt;an xml tag&gt;' string7 = '&lt;an xml tag&gt;, &lt;/closetag&gt;' string8 = '&lt;with attribute="77"&gt;' string9 = '&lt;opentag&gt;&lt;closetag&gt;' string10 = '&lt;/closetag&gt;' if re.search( r'^&lt;[^&lt;&gt;]*,&gt;$',string6 ) : print( "yes" ) else: print("no") if re.search( r'^&lt;[^&lt;&gt;]*,&gt;$',string7 ) : print( "yes" ) else: print("no") if re.search(r'^&lt;[^&lt;&gt;]*&gt;$',string8): print("yes") else: print("no") if re.search(r'^&lt;[^&lt;&gt;]*&gt;$',string9): print("yes") else: print("no") if re.search(r'^&lt;[^&lt;&gt;]*&gt;$',string10): print("yes") else: print("no") This is the result: yes no yes no yes I am trying to get: yes yes yes no no
tagged with: python
has title: Regular Expression with strings in Python
tagged with: regex
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92164616
has comment: http://stackoverflow.com/comment/92166232
has comment: http://stackoverflow.com/comment/92164868
has comment: http://stackoverflow.com/comment/92166648
score: 0

http://stackoverflow.com/comment/92188646
type: Comment
has text: Before you return `return completelinks`.
comment on: http://stackoverflow.com/q/52623178
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92411404
type: AnswerComment
comment on: http://stackoverflow.com/a/52743187
type: Comment
has text: This does not leverage pandas or dataframes at all.
score: 0

plotnine
tags question: http://stackoverflow.com/q/52625307
tag name: plotnine
tags question: http://stackoverflow.com/q/52663306
tags question: http://stackoverflow.com/q/52591265
tags question: http://stackoverflow.com/q/52647531
type: Tag

http://stackoverflow.com/comment/92324593
score: 0
type: QuestionComment
has text: Can you show relevant code were you call both your initializer, as well as the training loop?
type: Comment
comment on: http://stackoverflow.com/q/52698444

http://stackoverflow.com/comment/92275108
score: 1
has text: Ah did not see a blank in this. Sorry, string = string.replace('.', '')
type: AnswerComment
comment on: http://stackoverflow.com/a/52671658
type: Comment

http://stackoverflow.com/q/52704327
favorite count: 0
upvote count: 2
tagged with: pyqtgraph
type: AnsweredQuestion
score: 2
has title: How to insert a 3d GLViewWidget into a window containing 2d PyQtGraph plots
tagged with: opengl
tagged with: matplotlib
type: Question
has body: I am trying to port some plotting code from matplotlib to pyqtgraph for performance improvement. The pyqtgraph examples give separate examples of 2d plots and 3d plots, but I have not been able to find a sample of a 3d plot embedded as a subplot in a 2d plot window. I have tried embedding a GLViewWidget into a GraphicsWindow as shown below. What happens is that I can get multiple 2d plots or multiple 3d GLViewWidgets embedded, but not both together. As soon as I add 2d widgets to the layout, they dominate completely and I cannot see the 3d widgets. I have also tried adding a QGroupBox widget, with its own layout, and adding the 3d widget to that, even trying to set the minimum Width of the group box and the 3d widget, none of those seemed to help. I am using Anaconda 3: pyqt 5.6.0 py37ha878b3d_6 pyqtgraph 0.10.0 py37h28b3542_3 python 3.7.0 from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg import pyqtgraph.opengl as gl app = QtGui.QApplication([]) win = pg.GraphicsWindow(title="A 2d plot window") p1 = pg.PlotWidget() # try adding a 3d plot glvw = gl.GLViewWidget() z = pg.gaussianFilter(np.random.normal(size=(50,50)), (1,1)) p13d = gl.GLSurfacePlotItem(z=z, shader='shaded', color=(0.5, 0.5, 1, 1)) glvw.addItem(p13d) # get a layout layoutgb = QtGui.QGridLayout() win.setLayout(layoutgb) layoutgb.addWidget(glvw, 0, 0) # layoutgb.addWidget(p1, 0, 1) ### uncommenting this line causes #the plot widget to appear and the 3d widget to disappear QtGui.QApplication.instance().exec_()
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/53795923
tagged with: python
accepted answer: http://stackoverflow.com/a/53795923

http://stackoverflow.com/q/52730567
has comment: http://stackoverflow.com/comment/92386453
score: 1
tagged with: cython
upvote count: 1
has answer: http://stackoverflow.com/a/52746887
has comment: http://stackoverflow.com/comment/92387099
type: Question
has title: How to compile with Cython using a custom version of Python
has comment: http://stackoverflow.com/comment/92389683
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92386866
favorite count: 0
has comment: http://stackoverflow.com/comment/92386294
type: UnansweredQuestion
has body: When I compile a script using Cython, Python 3.6 is used to generate all the necessary files. How can one use a conda environment running Python version 3.5 to compile a Cython .pyx file on Windows?
tagged with: python

http://stackoverflow.com/q/52661673
accepted answer: http://stackoverflow.com/a/52661690
linked to: http://stackoverflow.com/q/23691133
score: 4
has body: My dataframe: df1 group ordercode quantity 0 A 1 B 3 1 C 1 E 2 D 1 I have formed each group bygroupby function. I need to extract the data by using group number. My desired ouput. In:get group 0 out: ordercode quantity A 1 B 3 or group ordercode quantity 0 A 1 B 3 any suggestion would be appreciated.
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has title: Selecting groups fromed by groupby function
has answer: http://stackoverflow.com/a/52661799
linked to: http://stackoverflow.com/q/52663926
has answer: http://stackoverflow.com/a/52661690
tagged with: python
has answer: http://stackoverflow.com/a/52661747
tagged with: indexing
has comment: http://stackoverflow.com/comment/92253931
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92253446
linked to: http://stackoverflow.com/q/52475010
linked to: http://stackoverflow.com/q/20109391
possible better answer: http://stackoverflow.com/a/52661747
type: Question
upvote count: 4

http://stackoverflow.com/comment/92305002
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52679951
has text: @West I added an example that interests you.
type: AnswerComment

http://stackoverflow.com/comment/92334941
score: 0
comment on: http://stackoverflow.com/q/52703014
type: Comment
type: QuestionComment
has text: Can you provide a pointer to a 10-bit video file that we can use to demonstrate a solution to your problem?

http://stackoverflow.com/a/52593476
upvote count: 2
answers question: http://stackoverflow.com/q/52593372
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52593372
type: Answer
has body: If every new row have fixed width 5 , you can using reshape pd.DataFrame(df.values.reshape(-1,5),columns=['addr','family','mask_addr','email','attempts']) Out[580]: addr family mask_addr email attempts 0 3705824725 2 4294967295 abc@xyz.com 0 1 3705824825 4 4294967625 sdf@xyz.com 0 Update df.columns=df.columns.str.split('_',1).str[1] df.melt().assign(newrow=lambda x : x.groupby(x['variable']).cumcount() ).pivot('newrow','variable','value') Out[596]: variable email failed_attempts ip_addr ip_family ip_mask_addr newrow 0 abc@xyz.com 0 3705824725 2 4294967295 1 sdf@xyz.com 0 3705824825 4 4294967625
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92122021

http://stackoverflow.com/q/52724149
has answer: http://stackoverflow.com/a/52724408
favorite count: 0
tagged with: python-3.x
has body: I have a problem I have a site which displays users but it displays users not in a straight line but in an inverted pyramid. It could be because I am using django-filter app but it shouldnt create a problem as such. The profiles right at the end (especially in the mobile view) overlap and drag. It gets worse as profiles increase. Is it possible to align the profiles or user list in a straight line? Please find below my code. filters.py(for djang-filters app) import django_filters from userprofile.models import UserProfiles class UserProfilesFilter(django_filters.FilterSet): class Meta: model = UserProfiles fields = ['gender', 'age', 'Nationality','preference', 'Country', 'City'] views.py @login_required def profiles_list(request): filter = UserProfilesFilter(request.GET, queryset = UserProfiles.objects.all().order_by('-pub_date')) return render(request,"userprofile/user_list.html", {'filter': filter}) user_list.html {% extends 'base.html' %} {% block content %} {% load static %} {% load bootstrap %} {% csrf_token %} {% for profile in filter.qs %} {{ profile.user }} Gender: {{ profile.gender }} Country: {{ profile.Country }} Description: {{ profile.summary }} Preferences: {{ profile.preference }} {% endfor %} loading... {% endblock %}
accepted answer: http://stackoverflow.com/a/52724408
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
answer count: 1
downvote count: 0
has title: How to display user_list in a indented line from the server in Django?

jupyterhub
tags question: http://stackoverflow.com/q/52622358
tags question: http://stackoverflow.com/q/52699818
tags question: http://stackoverflow.com/q/52597178
tag name: jupyterhub
type: Tag

http://stackoverflow.com/comment/92200074
type: Comment
type: QuestionComment
has text: Good to hear! Dictionaries being insertion ordered in Python 3.6 is an implementation detail found in the CPython implementation. It became a guarantee in Python 3.7
score: 1
comment on: http://stackoverflow.com/q/52633144

http://stackoverflow.com/a/52630844
answers question: http://stackoverflow.com/q/52630471
score: 0
has body: It seems like you're calling output() inside output2(), but your output() function has no return values. def output2(): x = soup.find_all("h1") l = [] for i in range(1): l.append(output()) In addition, your output2() function doesn't return anything either, which is why myData = ['Col1',[output2()]] is giving you col1 [none].
type: Answer

http://stackoverflow.com/comment/93728266
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52702261
has text: Androgaurd has some memory leak issues. When a 4MB file was analysed, it is consuming ~2GB of memory.

http://stackoverflow.com/q/52743352
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I want to take both the argmax and max along an axis of a scipy.sparse matrix X &gt;&gt;&gt; type(X) scipy.sparse.csr.csr_matrix &gt;&gt;&gt; idx = X.argmax(axis=0) &gt;&gt;&gt; maxes = X.max(axis=0) I don't want to have to compute the max twice, but I can't use the same approach to this as if X were a np.ndarray. How can I apply the indices from argmax to X?
score: 3
has comment: http://stackoverflow.com/comment/92417721
has title: Take the max along an axis of a sparse matrix after already calculating the argmax along that axis
tagged with: scipy
type: Question
linked to: http://stackoverflow.com/q/40357335
downvote count: 0
tagged with: sparse-matrix
upvote count: 3
has comment: http://stackoverflow.com/comment/92416034
answer count: 1
has comment: http://stackoverflow.com/comment/92416536
has answer: http://stackoverflow.com/a/52744014

http://stackoverflow.com/a/52635115
has comment: http://stackoverflow.com/comment/92205730
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52634085
has body: There might be many shorter ways to reach the goal. But you can try steps below. First, separate rows containing NaN values and store it in t. I assume NaN can also happen only in either lat or lon. You can improve it. t = df.loc[df.lat.isnull() | df.lon.isnull()] t lat lon 2 NaN NaN Drop rows with NaN values from df df.dropna(inplace=True) df lat lon 0 51.954974 5.857131 1 51.955014 5.860725 3 51.954168 5.866390 4 51.954889 5.868611 - Do your job to df here. - Then finally arrange back dataframe t to the original dataframe df. df = df.append(t).sort_index() df lat lon name 0 51.954974 5.857131 Metamorfosenallee 1 51.955014 5.860725 Burgemeester Matsersingel 2 NaN NaN NaN 3 51.954168 5.866390 Burgemeester Matsersingel 4 51.954889 5.868611 Batavierenweg
answers question: http://stackoverflow.com/q/52634085
has comment: http://stackoverflow.com/comment/92206265
has comment: http://stackoverflow.com/comment/92204185
type: Answer
has comment: http://stackoverflow.com/comment/92204169
has comment: http://stackoverflow.com/comment/92205781
has comment: http://stackoverflow.com/comment/92203958
has comment: http://stackoverflow.com/comment/92205516
score: 0

http://stackoverflow.com/comment/92285710
type: Comment
has text: I forgot to mention I'm using the version sitting on pull request https://github.com/priba/nmp_qc/blob/b59efc524827d62ec46f8c85c19849c30fadb652/models/MPNN.py edited the main post just now
score: 0
comment on: http://stackoverflow.com/q/52677861
type: QuestionComment

http://stackoverflow.com/a/52724439
answers question: http://stackoverflow.com/q/52723340
upvote count: 3
downvote count: 1
has body: There are many ways to smooth a curve (rolling mean, GAM, smoothing spline etc.), my favorite one is the Savitzky–Golay method. It works as follows: after having regressed a small window around a data point y onto a polynomial (with least squares), it uses this polynomial to get the estimation of your data point ^y. Then the window is shifted forward by one data point. import numpy as np import matplotlib.pyplot as plt from scipy.signal import savgol_filter x = np.linspace(0,5,150) y = np.cos(x) + np.random.random(150) * 0.15 yhat = savgol_filter(y, 49, 3) plt.plot(x,y) plt.plot(x,yhat, color='red') plt.show() Note that rolling mean can't work in your case with a perimeter as low as 20, since the outlier point will have a non-negligible weight (5%) and will always induce a big bias...
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/92375498

http://stackoverflow.com/q/52605370
has comment: http://stackoverflow.com/comment/92145112
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52607707
tagged with: python
has comment: http://stackoverflow.com/comment/92148399
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52607707
has title: python beautifulsoup web scraping issue
score: 0
has comment: http://stackoverflow.com/comment/92145316
answer count: 1
has body: page = requests.get("http://www.freejobalert.com/upsc-recruitment/16960/#Engg-Services2019") c = page.content soup=BeautifulSoup(c,"html.parser") data=soup.find_all("tr") for r in data: td = r.find_all("td",{"style":"text-align: center;"}) for d in td: link =d.find_all("a") for li in link: span = li.find_all("span",{"style":"color: #008000;"}) for s in span: strong = s.find_all("strong") for st in strong: dict['title'] = st.text for l in link: dict["link"] = l['href'] print(dict) It is giving {'title': 'Syllabus', 'link': 'http://www.upsc.gov.in/'} {'title': 'Syllabus', 'link': 'http://www.upsc.gov.in/'} {'title': 'Syllabus', 'link': 'http://www.upsc.gov.in/'} I am expecting: {'title': 'Apply Online', 'link': 'https://upsconline.nic.in/mainmenu2.php'} {'title': 'Notification', 'link': 'http://www.freejobalert.com/wp-content/uploads/2018/09/Notification-UPSC-Engg-Services-Prelims-Exam-2019.pdf'} {'title': 'Official Website ', 'link': 'http://www.upsc.gov.in/'} Here i want all "Important Links" means "Apply online","Notification","official website" and it's link for each table. but it is giving me "Syllabus" in title instead with repeting links.. please have a look into this..

http://stackoverflow.com/comment/92169625
type: QuestionComment
comment on: http://stackoverflow.com/q/52617318
score: 4
has text: Take a sheet of [graph paper](https://en.wikipedia.org/wiki/Graph_paper) (one with bigger squares), draw a small grid, say 5x7, label the axes and fill in some of the "pixels". Then try to draw the same thing rotated the way you want. Observe what algorithm you use to produce the result. (or even better, imagine you had to instruct a friend over the phone, to generate the rotated image. What would you tell them to do step, by, step.?)
type: Comment

http://stackoverflow.com/comment/92123758
score: 0
type: QuestionComment
type: Comment
has text: You may want `df.astype()`: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html
comment on: http://stackoverflow.com/q/52594458

http://stackoverflow.com/comment/92217684
has text: I am using 3.6.5. If I enter \t it returns '\\t' . if i enter '\t' it returned "'\\t'"
comment on: http://stackoverflow.com/q/52642355
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52601904
has title: I am trying to create a new column to bin values of a time column of a dataframe in python based on time range
type: Question
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/52601941
type: UnansweredQuestion
has body: Time column values: 09:11:00,10:11:00...NAT pd.cut(df_master['time_colum`enter code here`n'],bins= ['09:11:00','11:44:00','13:55:00','16:28:00'], labels= ['Morning','Afternoon','Evening']) TypeError Traceback (most recent call last) &lt;ipython-input-102-c66025f961bf&gt; in &lt;module&gt;() ----&gt; 1 pd.cut(df_master['Sent at_time'],bins=['09:11:00','11:44:00','13:55:00','16:28:00'], labels=['Morning','Afternoon','Evening']) C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\reshape\tile.py in cut(x, bins, right, labels, retbins, precision, include_lowest, duplicates) 225 bins = np.asarray(bins) 226 bins = _convert_bin_to_numeric_type(bins, dtype) --&gt; 227 if (np.diff(bins) &lt; 0).any(): 228 raise ValueError('bins must increase monotonically.') 229 C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\function_base.py in diff(a, n, axis) 1944 op = not_equal if a.dtype == np.bool_ else subtract 1945 for _ in range(n): -&gt; 1946 a = op(a[slice1], a[slice2]) 1947 1948 return a TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('&lt;U8') dtype('&lt;U8') dtype('&lt;U8')
tagged with: python

http://stackoverflow.com/comment/92359766
has text: This seems to hang - it has been running for about 20 minutes.
type: AnswerComment
comment on: http://stackoverflow.com/a/52716668
score: 0
type: Comment

http://stackoverflow.com/comment/92418156
score: 0
comment on: http://stackoverflow.com/a/52746704
type: Comment
type: AnswerComment
has text: `a[-1]` is like `a[len(a)-1]`; it is the last value in the list. `a[:-1]` is a copy of the whole list up until the last element, which is excluded from the copy.

http://stackoverflow.com/comment/92412824
has text: Nearly got it working with the following changes : //div[contains(@class, "question-summary narrow")]/div' and div[contains(@class, "votes")]//span/text()', I removed "//" infront of the div inside the loop and put "/div" at the end of the xpath before the loop, it's almost perfect but leaves every second row blank. I saw a solution to this somewhere else so i'll mark this question as solved.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52742371
score: 1

http://stackoverflow.com/a/52593305
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52592977
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52592977
type: Answer
has body: In the first place, FormLayout is a layout, that is, a class that is responsible for positioning the widgets within a window, so it is irrelevant for these cases. On the other hand, closeEvent() should never be invoked, that is a function that serves to handle the closed window event. Going to the point the accept method is called when Ok is pressed, so it is the right place to get the values so it must be stored in a variable, and then returned in the get_output() method: pyformlayout.py import sys from PyQt5 import QtWidgets app = QtWidgets.QApplication(sys.argv) class Dialog(QtWidgets.QDialog): def __init__(self, dinput): super(Dialog, self).__init__() self.createFormGroupBox(dinput) buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) mainLayout = QtWidgets.QVBoxLayout(self) mainLayout.addWidget(self.formGroupBox) mainLayout.addWidget(buttonBox) self.setWindowTitle("Form Layout") def createFormGroupBox(self, dinput): layout = QtWidgets.QFormLayout() self.linedit1 = QtWidgets.QLineEdit('TestName') self.combox1 = QtWidgets.QComboBox() self.combox1.setToolTip('Hello') self.combox1.addItems(['India','France','UK','USA','Germany']) self.spinbox1 = QtWidgets.QSpinBox() for text, w in zip(dinput, (self.linedit1, self.combox1, self.spinbox1)): layout.addRow(text, w) self.formGroupBox = QtWidgets.QGroupBox("Form layout") self.formGroupBox.setLayout(layout) def accept(self): self._output = self.linedit1.text(), self.combox1.currentText(), self.spinbox1.value() super(Dialog, self).accept() def get_output(self): return self._output And in the file main.py I get the value if only the ok button has been pressed: main.py import pyformlayout as pyfl # Staring Functions for Execution dinput = ['LastName','Country','Age'] # Call the UI and get the inputs dialog = pyfl.Dialog(dinput) if dialog.exec_() == pyfl.Dialog.Accepted: name, item, value = dial…

http://stackoverflow.com/comment/92387008
score: 0
type: Comment
has text: Right, you’ll need to rewrite the rest of it too since findAll is giving you a result set and not a single element. But the reason you were getting just the first tag is because the find function only returns the first match it sees.
comment on: http://stackoverflow.com/a/52730963
type: AnswerComment

http://stackoverflow.com/comment/92268751
comment on: http://stackoverflow.com/q/52668844
type: QuestionComment
type: Comment
has text: @KirilS. Thanks - although there is another thing I will need to wait for. The CC forms need to be loaded such that ` ` turns into ` `. What EC condition would this be?
score: 0

http://stackoverflow.com/comment/92241996
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52655162
score: 2
has text: "I want to avoid reading and searching each line if possible" but think of the possibilities if you do. Read line by line and build up the object tree in memory as you do. That may simplify things considerably.

http://stackoverflow.com/comment/92204876
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52635572
has text: This is known as the [bin packing problem](https://en.wikipedia.org/wiki/Bin_packing_problem). The [greedy solution](https://en.wikipedia.org/wiki/Bin_packing_problem#First-fit_algorithm) works well enough for most applications.
type: Comment

http://stackoverflow.com/comment/92215037
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52640287
has text: If you are using a recent enough python version: `print(f'the number is {number}')`

http://stackoverflow.com/comment/92164470
comment on: http://stackoverflow.com/q/52614955
has text: @CharlesDuffy , how can I do count checksum of a downloaded file /of original file with python?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52737771
answers question: http://stackoverflow.com/q/52737693
score: 0
has comment: http://stackoverflow.com/comment/92400738
type: Answer
has body: It's a nested list, so you can call the first element [0] and get the list inside the list, then call the first element of that: First element of [["01","10","01"]] is ["01","10","01"] and first element of ["01","10","01"] is 01. dynamic_arrayList = [ ] hexdec = input("Enter even number "); strArray = [hexdec[idx:idx+2] for idx in range(len(hexdec)) if idx%2 == 0] dynamic_arrayList.append(strArray) print(dynamic_arrayList[0][0])

http://stackoverflow.com/q/52738169
tagged with: python
has title: Setting several corenlp_options in the StanfordDependencyParser with NLTK, Python
has answer: http://stackoverflow.com/a/52742419
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/13883277
type: Question
tagged with: stanford-nlp
tagged with: nltk
has comment: http://stackoverflow.com/comment/92440588
has body: I am trying to set several options for the StanfordDependencyParser that I am using with NLTK: from nltk.parse.stanford import StanfordDependencyParser os.environ['CLASSPATH'] = "path/to/stanford-parser-3.9.1-models.jar" sdp = StanfordDependencyParser('path/to/stanford-parser-3.9.1-models.jar', corenlp_options=['-retainTmpSubcategories', '-originalDependencies']) However, I get raise OSError('Java command failed : ' + str(cmd)) OSError: Java command failed : ['C:\\Program Files\\Java\\jdk-11\\bin\\java.exe', '-mx1000m', '-cp', '\\stanford-parser.jar', 'edu.stanford.nlp.parser.lexparser.LexicalizedParser', '-model', 'edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz', '-sentences', 'newline', '-outputFormat', 'conll2007', '-encoding', 'utf8', ['-retainTmpSubcategories', '-originalDependencies'], 'C:\\Users\\...'] (I removed some of the paths to make it clearer.) If I only use sdp = StanfordDependencyParser('path/to/stanford-parser-3.9.1-models.jar', corenlp_options=['-retainTmpSubcategories']) or sdp = StanfordDependencyParser('path/to/stanford-parser-3.9.1-models.jar', corenlp_options=['-originalDependencies']) it works well... I also looked at the nltk code, the _execute function which is used to compute the commande line def _execute(self, cmd, input_, verbose=False): encoding = self._encoding cmd.extend(['-encoding', encoding]) if self.corenlp_options: cmd.append(self.corenlp_options) Does this mean that I can only put 1 single option in the corenlp_options argument?? Thank you for your help!!
upvote count: 1
answer count: 1
duplicate of: http://stackoverflow.com/q/13883277
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52615187
downvote count: 0
has comment: http://stackoverflow.com/comment/135966526
has body: Using concat with groupby and first: pd.concat([df1, df2, df3], 1).groupby(level=0, axis=1).first() A B C D id name place qty unit 0 a b c d 1 Tom NY 2 10 1 a b c d 2 Ron TK 3 15 2 a b c d 3 Don Lon 5 90 3 a b c d 4 Sam Hk 4 49
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52614977
score: 2

http://stackoverflow.com/comment/92391299
comment on: http://stackoverflow.com/q/52731296
score: 0
type: Comment
has text: Relevant: [simple-digit-recognition-ocr-in-opencv-python](https://stackoverflow.com/questions/9413216/simple-digit-recognition-ocr-in-opencv-python?rq=1)
type: QuestionComment

int
tags question: http://stackoverflow.com/q/52607943
type: Tag
tags question: http://stackoverflow.com/q/52600484
tags question: http://stackoverflow.com/q/52605786
tag name: int

http://stackoverflow.com/comment/92261301
comment on: http://stackoverflow.com/a/52665790
score: 1
has text: https://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#flip
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52730332
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52730909
score: 0
possible better answer: http://stackoverflow.com/a/52730375
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/52730375
tagged with: python
has title: I'm trying to scrape data from the at the races website but the scraper is not returning any results
has body: from selenium import webdriver driver = webdriver.Chrome() login_url = 'http://www.attheraces.com/racecard/Wolverhampton/6-October-2018/1715' driver.get(login_url) html = driver.execute_script("return document.documentElement.outerHTML") sel_soup = BeautifulSoup(html, 'html.parser') print(sel_soup.findAll("sectionals-time")) When I run the last line of the script it just returns [] It is a dynamic website as far as I am aware, so when you go to this site and scroll down to results, you click the sectional times tab, then right click the first sectional time for the first listed horse and inspect. this then shows me the class attribute as "sectionals-time" so I'm struggling to understand why it's not producing the sectional times for the horses. Any advice and help much appreciated.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52730909
tagged with: selenium
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/92386509
has comment: http://stackoverflow.com/comment/92386570

http://stackoverflow.com/comment/92399615
has text: That would be `sum(score[x] for x in word)`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52737330
type: AnswerComment

http://stackoverflow.com/comment/92304280
type: AnswerComment
has text: I think the edit solves it, possibly even without changing the X to strings, but just using the order argument.
type: Comment
comment on: http://stackoverflow.com/a/52688240
score: 0

http://stackoverflow.com/a/52619483
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52619372
has comment: http://stackoverflow.com/comment/92176305
answers question: http://stackoverflow.com/q/52619372
has comment: http://stackoverflow.com/comment/92175141
has body: try like this.. df = pd.read_csv("data.csv", usecols=['Sample_A','Sample_D']).fillna('') print(df) Selecting all of the rows and some columns, It is possible to select all of the rows by using a single colon. &gt;&gt;&gt; df.loc[:, ['Sample_A','Sample_D']] Your answer from the dataset you provided: &gt;&gt;&gt; data2 = {'Num': ['Value_1','Value_2','Value_3','Value_4','Value_5'], ... 'Sample_A': [0,1,0,0,1], ... 'Sample_B':[0,0,1,0,0], ... 'Sample_C':[1,0,0,0,1], ... 'Sample_D':[0,0,1,1,0]} &gt;&gt;&gt; df2 = pd.DataFrame(data2) &gt;&gt;&gt; df2.set_index('Num').loc[:, ['Sample_A','Sample_D']] Sample_A Sample_D Num Value_1 0 0 Value_2 1 0 Value_3 0 1 Value_4 0 1 Value_5 1 0 ===================================== &gt;&gt;&gt; df3 = df2.loc[:, samples] &gt;&gt;&gt; df3 Sample_A Sample_D Sample_E 0 0 0 NaN 1 1 0 NaN 2 0 1 NaN 3 0 1 NaN 4 1 0 NaN OR &gt;&gt;&gt; df3 = df2.reindex(columns=samples) &gt;&gt;&gt; df3 Sample_A Sample_D Sample_E 0 0 0 NaN 1 1 0 NaN 2 0 1 NaN 3 0 1 NaN 4 1 0 NaN
type: Answer
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/92281605
has text: Thanks @nandneo! I see what you changed and wasn't even close to that so appreciate it! I ran what you gave me and I get several lines such as: File "C:\Users\jason\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen return opener.open(url, data, timeout)" At the end it says "urllib.error.HTTPError: HTTP Error 429: Rate" Which I think means I'm requesting from the url too frequently?
type: Comment
comment on: http://stackoverflow.com/a/52675904
score: 0
type: AnswerComment

http://stackoverflow.com/q/52743265
favorite count: 0
has answer: http://stackoverflow.com/a/52746792
has body: I've started remote debugging with visual studio code but I cant get it to work. Both the remote and the local development PC both running version 4.1.3 of ptvsd. The remote machine has the script : import ptvsd ptvsd.enable_attach() #Enable the below line of code only if you want the application to wait untill the debugger has att$ #ptvsd.wait_for_attach() import random guesses_made = 0 name = input('Hello! What is your name?\n') number = random.randint(1, 20) print('Well, {0}, I am thinking of a number between 1 and 20.'.format(name)) while guesses_made &lt; 6: guess = int(input('Take a guess: ')) guesses_made += 1 if guess &lt; number: print('Your guess is too low.') if guess &gt; number: print('Your guess is too high.') if guess == number: break if guess == number: print('Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)) else: print('Nope. The number I was thinking of was {0}'.format(number)) The local computer is : import ptvsd ptvsd.enable_attach(address = ('192.34.98.197',3000)) #Enable the below line of code only if you want the application to wait untill the debugger has attached to it #ptvsd.wait_for_attach() import random guesses_made = 0 name = input('Hello! What is your name?\n') number = random.randint(1, 20) print('Well, {0}, I am thinking of a number between 1 and 20.'.format(name)) while guesses_made &lt; 6: guess = int(input('Take a guess: ')) guesses_made += 1 if guess &lt; number: print('Your guess is too low.') if guess &gt; number: print('Your guess is too high.') if guess == number: break if guess == number: print('Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)) else: print('Nope. The number I was thinking of was {0}'.format(number)) I've added the entries into launch.json : { "name": "Attach (Remote Debug)", "type": "python", "request": "attach", "localRoot": "${workspaceRoot}", "remoteRoot": "/home/pi/testdebug/", "port": 3000, "secret": "my_secret", "host":"localhost" }, This…
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/52760636
upvote count: 2
accepted answer: http://stackoverflow.com/a/52746792
type: Question
tagged with: debugging
tagged with: visual-studio-code
has title: Error running Remote debugging with "ptvsd"
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/92112765
comment on: http://stackoverflow.com/q/52588733
score: 1
has text: It may be that JavaScript isn't executed. You can also try your luck with https://html.python-requests.org
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52641373
type: Answer
has comment: http://stackoverflow.com/comment/92217232
accepted answer of: http://stackoverflow.com/q/52641263
answers question: http://stackoverflow.com/q/52641263
type: AcceptedAnswer
score: 0
has body: Use numpy.select: m1 = df['close'] &gt; df['sma_10'] m2 = df['close'] &lt; df['sma_10'] m3 = df['close'] == df['sma_10'] df['Indicator'] = np.select([m1, m2, m3], ['BUY','SELL','NEUTRAL'], 'ERROR')

http://stackoverflow.com/q/52686968
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/23013220
has body: I have one question:I want to test "select" and "input".can I write it like the code below: original code: 12 class Sinaselecttest(unittest.TestCase): 13 14 def setUp(self): 15 binary = FirefoxBinary('/usr/local/firefox/firefox') 16 self.driver = webdriver.Firefox(firefox_binary=binary) 17 18 def test_select_in_sina(self): 19 driver = self.driver 20 driver.get("https://www.sina.com.cn/") 21 try: 22 WebDriverWait(driver,30).until( 23 ec.visibility_of_element_located((By.XPATH,"/html/body/div[9]/div/div[1]/form/div[3]/input")) 24 ) 25 finally: 26 driver.quit() # #测试select功能 27 select=Select(driver.find_element_by_xpath("//*[@id='slt_01']")).select_by_value("微博") 28 element=driver.find_element_by_xpath("/html/body/div[9]/div/div[1]/form/div[3]/input") 29 element.send_keys("杨幂") 30 driver.find_element_by_xpath("/html/body/div[9]/div/div[1]/form/input").click() 31 driver.implicitly_wait(5) 32 def tearDown(self): 33 self.driver.close() I want to test Selenium "select" function.so I choose sina website to select one option and input text in textarea.then search it .but when I run this test,it has error: Traceback (most recent call last): File "test_sina_select.py", line 32, in tearDown self.driver.close() File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 688, in close self.execute(Command.CLOSE) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 319, in execute response = self.command_executor.execute(driver_command, params) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 376, in execute return self._request(command_info[0], url, body=data) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 399, in _request resp = self._conn.request(method, url, body=body, headers=headers) File "/usr/lib/python2.7/site-packages/urllib3/request.py", line 68, in request **urlopen_kw) File "/usr/lib/python2.7/site-packages/urllib3/request.…
has comment: http://stackoverflow.com/comment/92301591
has comment: http://stackoverflow.com/comment/92315704
has title: MaxRetryError: HTTPConnectionPool: Max retries exceeded (Caused by ProtocolError('Connection aborted.', error(111, 'Connection refused')))
has answer: http://stackoverflow.com/a/52701504
score: 12
answer count: 3
tagged with: urllib3
accepted answer: http://stackoverflow.com/a/52701504
has answer: http://stackoverflow.com/a/65409484
favorite count: 0
has comment: http://stackoverflow.com/comment/104460072
tagged with: python
upvote count: 13
has comment: http://stackoverflow.com/comment/92303184
possible better answer: http://stackoverflow.com/a/52728415
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92315706
linked to: http://stackoverflow.com/q/47999568
has answer: http://stackoverflow.com/a/52728415
linked to: http://stackoverflow.com/q/45985008
tagged with: selenium
tagged with: python-requests

http://stackoverflow.com/q/52687337
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/92302385
has answer: http://stackoverflow.com/a/52688045
accepted answer: http://stackoverflow.com/a/52688045
type: Question
score: 3
linked to: http://stackoverflow.com/q/41015779
has body: Is there a correct way to start an infinite task from Django Framework? I need to run a MQTT Client (based on Paho) and a Python PID implementation. I want to use Django as "Orhestrator" because I want to start daemons only if django it's running. I use django becasue of it's simplicity for creating Rest API and ORM layer. The only way I've found (here on github) it's to modify the __init__.py including here my external module --> How to use paho mqtt client in django?. This it's not suitable for me beacause it start the daemons on every django manage task. Has anyone already solved this problem? Thank you in advance.
tagged with: python-daemon
has title: Django how to run external module as Daemon
upvote count: 3
has comment: http://stackoverflow.com/comment/92305575
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/92149393
comment on: http://stackoverflow.com/a/52607078
has text: @Andersson I overwrote that bit of code. My version control is nonexistent, sorry.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52620128
type: Answer
has body: Use zip to combine corresponding list entries and then .count &gt;&gt;&gt; age_baby = [ 2, 1, 3, 1, 4, 2, 4, 1, 1, 3, 4, 2, 2, 3] &gt;&gt;&gt; first_name_baby = "T, S, R, T, O, A, L, S, F, S, Z, U, S, P".split(', ') &gt;&gt;&gt; list(zip(first_name_baby, age_baby)).count(('S', 1)) 2 Alternatively, you could use numpy. This would allow a solution very similar to what you have tried: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; age_baby = np.array(age_baby) &gt;&gt;&gt; first_name_baby = np.array(first_name_baby) &gt;&gt;&gt; &gt;&gt;&gt; np.count_nonzero((first_name_baby == 'S') &amp; (age_baby == 1)) 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52619999
upvote count: 2

http://stackoverflow.com/q/52593967
tagged with: listview
has body: In my listview I want to display several fields from two models containing a many-to-many field. I can display the correct values from one table, but then I cannot access the other table with the many-to-manyfield. Models.py class Books(models.Model): title = models.CharField(max_length=100) class Author(models.Model): book = models.ManyToManyField(Books) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=200) Views.py class BooksListView(ListView): context_object_name = 'booklist' model = Author template_name = 'Books/books_list.html' Book_list.html {% for books in booklist %} &lt;h5&gt;&lt;li class="list-group-item list-group-item-light""&gt; {{books.book.all}}:{{books.first_name}} {{books.last_name}}&lt;/li&gt;&lt;/h5&gt; {% endfor %} The first and lastname are displayed properly, but the books.book.all ()i know this is the wrong query) returns a queryset containing the title (which is what I need, but this is in format &lt;QuerySet [&lt;Books: Book Title&gt;]&gt;. But books.book.title doesnt seem to work. What I want to display is "booktitle - firstname lastname", and because I am using two tables, I need a many-to-many relationship. Any thoughts?
score: 0
has comment: http://stackoverflow.com/comment/92122811
accepted answer: http://stackoverflow.com/a/52595015
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: display model fieldnames in Django listview
tagged with: django-models
type: Question
has comment: http://stackoverflow.com/comment/92122845
answer count: 1
has answer: http://stackoverflow.com/a/52595015

conv-neural-network
tags question: http://stackoverflow.com/q/52662153
tags question: http://stackoverflow.com/q/52664626
tags question: http://stackoverflow.com/q/52658571
tags question: http://stackoverflow.com/q/52736269
tags question: http://stackoverflow.com/q/52695805
type: Tag
tags question: http://stackoverflow.com/q/52634553
tags question: http://stackoverflow.com/q/52663982
tags question: http://stackoverflow.com/q/52656293
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/52733216
tags question: http://stackoverflow.com/q/52702431
tags question: http://stackoverflow.com/q/52614786
tags question: http://stackoverflow.com/q/52625358
tags question: http://stackoverflow.com/q/52632647
tags question: http://stackoverflow.com/q/52619166

http://stackoverflow.com/comment/92336180
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52704580
score: 0
has text: People will find it easier to answer if you can post a small sample of your input (and then make the output you're currently getting and the output you want to get correspond to that input). That way people can paste it into their code and make sure their solution is doing what you want.

http://stackoverflow.com/comment/92403011
comment on: http://stackoverflow.com/a/52738702
score: 1
type: AnswerComment
has text: @Bazingaa It would work if you make `db` a variable of the class and then use `StepStatusManager.db` instead of `self.db` in the decorator, similarly to the case for `@classmethod`
type: Comment

http://stackoverflow.com/q/52732174
has title: problem with using merge_asof from Pandas
has body: I have these two dataframes: DF1= Inflow 0 9810998109 1 5591255912 2 7394273942 3 7866678666 4 1820118202 5 9812198109 6 9810998101 7 4304043040 8 9810998121 DF2= Inflow mi_to_zcta5 0 3371433756 11.469054 1 1790118201 24.882142 I'd like to do an operation where I can merge these two dataframes based in the 'Inflow' column. Sort of like trying to recreate a VLookUp Excel function with approximate matching (like its shown in this question). But I get a failure each time. The line I've been trying to use for this purpose is this one: test = pd.merge_asof(DF1, DF2, on = 'mi_to_zcta5') I've tried using the additional settings like 'allow_exact_matches' set to 'False' but I've not succeeded. This is the error I get: return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5280) File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5126) File "pandas\_libs\hashtable_class_helper.pxi", line 1210, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20523) File "pandas\_libs\hashtable_class_helper.pxi", line 1218, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20477) KeyError: 'mi_to_zcta5' I'd like to get a dataframe with 10 rows, with the "Inflow" column and an additional column of 'mi_to_zcta5' with the correspondant nearest value (if that's possible). Just like one would do in VLookUp in excel using approximate match. Thanks in advance!
score: 0
accepted answer: http://stackoverflow.com/a/52733192
answer count: 1
tagged with: pandas
linked to: http://stackoverflow.com/q/46357897
has comment: http://stackoverflow.com/comment/92389805
tagged with: python
tagged with: merge
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92391234
has comment: http://stackoverflow.com/comment/92390745
has answer: http://stackoverflow.com/a/52733192
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92389779
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92389633

http://stackoverflow.com/q/52637307
downvote count: 0
has body: I was going through bokeh tutorial from their official website: https://hub.mybinder.org/user/bokeh-bokeh-notebooks-tkmnntgc/notebooks/tutorial/00%20-%20Introduction%20and%20Setup.ipynb and attempted to get a similar plot for crime rates in USA cities from wikipedia data of 2009. But, I stuck with some problems. First of all I searched related questions and they quite did not meet my problems. Related questions: Choosing order of bars in Bokeh bar chart Questions 1. How go get values at top of the vertical bars? 2. How to get the values sorted by y-axis values instead of x-label indices? The code is given here: import pandas as pd import requests from bokeh.io import output_notebook, show output_notebook() from bokeh.models import ColumnDataSource, HoverTool from bokeh.plotting import figure from bokeh.transform import factor_cmap url = "https://en.wikipedia.org/wiki/List_of_United_States_cities_by_crime_rate" response = requests.get(url) df = pd.read_html(response.content)[1] df = df.iloc[2:] df.columns = ['State', 'City', 'Population', 'Total_violent', 'Murder', 'Rape', 'Robbery', 'Assault', 'Total_property', 'Burglary', 'Larceny', 'Motor_theft', 'Arson'] df.index = df.index - 2 # Reset index numbers df.index = df.City # rename index df.index.name = 'index' # Change data type and sort df['Murder'] = df['Murder'].apply(pd.to_numeric, errors='coerce') df = df.sort_values(by='Murder', ascending=True) # first and last 10 df = pd.concat([df.head(10), df.tail(10)]) df.index = range(20) # create low_high column df['low_high'] = ['low']*10 + ['high']*10 # create group of two x-axes group = df.groupby(by=['low_high', 'City']) # from group get source source = ColumnDataSource(group) # from group get figure p = figure(plot_width=800, plot_height=300, title="Murder in US city per 100,000 people in 2009", x_range=group, toolbar_location=None, tools="") # plot labels p.xgrid.grid_line_color = None p.xaxis.axis_label = "Cities" p.yaxis.axis_label = "Murder" p.xaxis.major_label_o…
has answer: http://stackoverflow.com/a/52637619
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: holoviews
tagged with: python
accepted answer: http://stackoverflow.com/a/52637619
type: AnsweredQuestion
has title: Bokeh plot sort bar plot by values not by index
score: 1
tagged with: bokeh
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/33135531

http://stackoverflow.com/comment/111862760
type: Comment
has text: I was able to solve this by replacing TestCase with TransactionTestCase, now my tests work fine...but they take more time now. xD It used to take around a second earlier..now it's 70 seconds
comment on: http://stackoverflow.com/a/59547818
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92340270
type: Comment
score: 0
type: QuestionComment
has text: So you want to convert this CSV file into a TSV file?
comment on: http://stackoverflow.com/q/52707006

http://stackoverflow.com/comment/92379539
type: QuestionComment
comment on: http://stackoverflow.com/q/52726807
score: 2
has text: But there's no `localfile` module in `folder1` directory. You should rather use absolute imports: `from app.web.localfile import ...` and run you script like `python -m app.web.folder1.current_file`.
type: Comment

http://stackoverflow.com/comment/92181633
comment on: http://stackoverflow.com/a/52620963
score: 0
type: Comment
has text: @IljaEverilä load_only is awsome... i appreciate it.. T_T thanks, thanks..
type: AnswerComment

http://stackoverflow.com/q/52729412
downvote count: 0
has comment: http://stackoverflow.com/comment/123336091
favorite count: 0
has comment: http://stackoverflow.com/comment/98976420
has title: Jupyter lab: is it possible to display output only in a separate view
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
answer count: 0
has body: I've been working with Jupyter notebooks quite a while but right now, I'm switching to Jupyter lab. I really like it, especially the possibility to create a new view for my outputs and hide the output from the main notebook. However, once you run the same cell again, the output in the main notebook is no longer hidden. Is there a possibility to rerun a cell by hiding its output in the main notebook and showing it only in the new view?
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/117178119
type: Question
tagged with: jupyter-lab
has comment: http://stackoverflow.com/comment/115741587

http://stackoverflow.com/comment/118808510
type: Comment
has text: @p.luck: Correct: FIX -> Stunnel -> Trading venue
comment on: http://stackoverflow.com/a/52637363
score: 1
type: AnswerComment

http://stackoverflow.com/q/52729628
score: 0
has title: How to write a string interpreter that will execute a series of turtle movement commands in python?
tagged with: python
has body: I am working on a project where I want to take in a string such as "F100&lt;30S30" F100 would move the turtle forward by 100, &lt;30 would rotate the turtle 30 degrees, and S30 would draw a circle with the radius of 30. I can get the program to interpret one command, for example F100, but I cannot get it to interpret a long string as shown above. What ways can I go about interpreting this. Thank you.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92384460
type: UnansweredQuestion
upvote count: 1
downvote count: 1
tagged with: interpreter
type: Question
has answer: http://stackoverflow.com/a/52729810
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92392496
type: Comment
comment on: http://stackoverflow.com/a/52733717
score: 0
type: AnswerComment
has text: why reshape starts from -1?

http://stackoverflow.com/q/52620712
has comment: http://stackoverflow.com/comment/92211661
answer count: 0
has title: How to add user to a group in admin
type: Question
has comment: http://stackoverflow.com/comment/92175145
has comment: http://stackoverflow.com/comment/92211414
score: 0
has comment: http://stackoverflow.com/comment/92211097
has body: Since the default django admin group form does not have field for selecting users in a group. I Wrote down some codes which i got online to add the selected users field.Everything is working just fine. Until i tried saving the group form i created, I get this error 'Group' object has no attribute 'user_set' class GroupAdminForm(forms.ModelForm): class Meta: model=group exclude=[] users=forms.ModelMultipleChoiceField(queryset=User,objects.all(),widget=FilteredSelectMultiple('users',False),required=False) def __int__(self,*args,**kwargs): super(GroupAdminForm,self).__int__(*args,**kwargs) if self.instance.pk: self.fields['users'].initial=self.instance.user_set.all() def save_m2m(self): self.instance.user_set.set(self.cleaned_data['users']) def save(self,*args,*kwargs): instance= super(GroupAdminForm,self).save() self.save_m2m() return instance I am getting this error 'Group' object has no attribute 'user_set' . I donot know on how to go about resolving this problem . Please help . I am navies in django. Help Hlep please
has comment: http://stackoverflow.com/comment/92175214
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python

http://stackoverflow.com/q/52628766
type: Question
tagged with: email-attachments
accepted answer: http://stackoverflow.com/a/52665116
answer count: 1
downvote count: 0
score: 1
tagged with: exchangelib
tagged with: email
tagged with: python
favorite count: 0
upvote count: 1
type: AnsweredQuestion
tagged with: attachment
has title: How can I send attachments in an email reply?
has body: I'm using the exchangelib package to connect to Exchange. I need to send attachments in a reply. When I send a normal message I add the attachment to the Message object like this: message = Message() message.account = account message.subject = 'subject' message.body = 'text' message.to_recipients = [Mailbox(email_address='example@gmail.com')] message.cc_recipients = ['example2@gmail.com'] for attachment in attachments or []: with open(attachment['path'], 'rb') as f: file = FileAttachment(name=attachment['file_name'], content=f.read()) message.attach(file) and to send a reply: reply = message.reply( subject='Re: subject', body='texto', to_recipients=['example@gmail.com'] ) This works, but I don't now how to add attachments to the reply. I tried to set the attributes "attachments" and "attach" but the object doesn't have them.
has answer: http://stackoverflow.com/a/52665116

http://stackoverflow.com/q/52684900
has comment: http://stackoverflow.com/comment/92314805
type: UnansweredQuestion
tagged with: selenium
tagged with: headless
tagged with: iceweasel
type: Question
has comment: http://stackoverflow.com/comment/92300227
tagged with: raspberry-pi
has body: Edit: This does not seem to be a duplicate because none of the suggestions in the answers of the post linked fix the error. Here is the geckodriver.log after running the script: 1538960169585 mozrunner::runner INFO Running command: "/usr/bin/firefox" "-marionette" "--headless" "-foreground" "-no-remote" "-profile" "/tmp/rust_mozprofile.xicOi27i6laa" 1538960178656 Marionette INFO Listening on port 2828 ^G[Child 17792] ###!!! ABORT: Aborting on channel error.: file /build/firefox-esr-YKrXxr/firefox-esr-52.9.0esr/ipc/glue/MessageChannel.cpp, line 2152 [Child 17792] ###!!! ABORT: Aborting on channel error.: file /build/firefox-esr-YKrXxr/firefox-esr-52.9.0esr/ipc/glue/MessageChannel.cpp, line 2152 I'm unable to create webdriver instance running python 3.5 on a headless Raspberry Pi 3 B+. I have run sudo apt-get install python-pip iceweasel xvfb pip install pyvirtualdisplay selenium to install dependencies. When I run a basic script to create a selenium WebDriver, though, I get a WebDriverException: Message: connection refused message. My code: from selenium import webdriver from pyvirtualdisplay import Display display = Display(visible=0, size=(800, 600)) display.start() profile = webdriver.FirefoxProfile() profile.native_events_enabled = False driver = webdriver.Firefox(profile) Error message: Traceback (most recent call last): File "simpletest", line 10, in &lt;module&gt; driver = webdriver.Firefox(firefox_profile=profile) File "/home/pi/.local/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 174, in __init__ keep_alive=True) File "/home/pi/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/home/pi/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/pi/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.…
answer count: 1
has title: selenium WebDriverException: "connection refused" occuring on headless Pi
has answer: http://stackoverflow.com/a/54456069
score: 0
linked to: http://stackoverflow.com/q/47920639
tagged with: python

http://stackoverflow.com/q/52618757
linked to: http://stackoverflow.com/q/28894172
downvote count: 0
type: UnansweredQuestion
favorite count: 0
linked to: http://stackoverflow.com/q/904928
type: Question
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/92171745
has answer: http://stackoverflow.com/a/52618902
has title: datetime.strptime formatting
tagged with: python-3.x
upvote count: 3
has answer: http://stackoverflow.com/a/52618855
answer count: 3
has body: My datetime in my CSV file is like the following: 2011/1/1 0:00 2011/1/1 0:30 2011/1/1 1:00 when I run: date = datetime.strptime(row[0], '%Y/%m/%d %H:%M') I get datetime output as: [datetime.datetime(2011, 1, 1, 0, 0)] [datetime.datetime(2011, 1, 1, 0, 30)] How can i format it to the original datetime?
has answer: http://stackoverflow.com/a/52618999
has comment: http://stackoverflow.com/comment/92171744
tagged with: python-datetime

web-services
type: Tag
tags question: http://stackoverflow.com/q/52710492
tags question: http://stackoverflow.com/q/52599641
tag name: web-services

http://stackoverflow.com/q/52694844
has comment: http://stackoverflow.com/comment/92319750
tagged with: python
has title: What is the difference between Django ORM and Flask-Sqlalchemy in using filter?
tagged with: sqlalchemy
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/92316242
has comment: http://stackoverflow.com/comment/92316435
tagged with: flask-sqlalchemy
has answer: http://stackoverflow.com/a/52694907
has comment: http://stackoverflow.com/comment/92316590
score: 0
has body: Hi friends all around the world ,There is a problem which is perplexing me for days .When I used Django I used obj=User.objects.filter(uname=username,pwd=password) the User is a class to migrate to MySQL But when I used Flask-Sqlalchemy obj = User.query.filter(User.uname == username, User.pwd == password).first() I need to do this to realize login. I think there is somethings different between Django and Flask. I know the "=" is assigning operator and the "==" is relational operator. It's appreciate that you can help me , Thank you !
has comment: http://stackoverflow.com/comment/92316406
has comment: http://stackoverflow.com/comment/92316425
has comment: http://stackoverflow.com/comment/92316491
tagged with: django-orm
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2128505

http://stackoverflow.com/a/52662940
upvote count: 2
answers question: http://stackoverflow.com/q/52662781
has body: Do not use .loc. With .loc you access a group of rows and columns by label(s) or a boolean array.
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92325337
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52699358
has text: Indeed, it is stored in `f.__defaults__`
score: 0

http://stackoverflow.com/q/52688818
score: 0
accepted answer: http://stackoverflow.com/a/52689037
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/92304903
has body: I have a column which contains values like this 04-04-2007 14-03-2008 14-03-2008 2011-10-10 00:00:00 2011-10-10 00:00:00 27-04-2012 27-04-2012 28-03-2014 2014-03-28 00:00:00 2017-03-31 00:00:00 2017-03-31 00:00:00 2018-04-02 00:00:00 As can be seen, few values are datetime and few are string. I want all to be converted to datetime. pd.to_datetime(df['Event Date'], format='%d-%m-%Y') throws an error when it encounters datetime type values
tagged with: datetime
tagged with: python
type: AnsweredQuestion
type: Question
has title: Pandas: convert all values of a column to datetime when the column values are mix of string and datetime
has answer: http://stackoverflow.com/a/52689037

http://stackoverflow.com/comment/92123916
type: Comment
has text: I would appreciate it, I've been reading up about QP, lasso and other possible methods all day and now my brain is tired
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52589230

http://stackoverflow.com/q/52637493
has comment: http://stackoverflow.com/comment/92208121
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92208342
has title: Keras: Save Model In Suitable Format for Google Cloud ML Engine (missing functions)
answer count: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/92208906
type: Question
has comment: http://stackoverflow.com/comment/92208898
tagged with: python
has body: I'm trying to deploy a recently trained Keras model on Google Cloud ML Engine. I googled around to see what format the saved model needs to be for ML Engine and found this: import keras.backend as K import tensorflow as tf from keras.models import load_model, Sequential from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model import tag_constants, signature_constants from tensorflow.python.saved_model.signature_def_utils_impl import predict_signature_def # reset session K.clear_session() sess = tf.Session() K.set_session(sess) # disable loading of learning nodes K.set_learning_phase(0) # load model model = load_model('model.h5') config = model.get_config() weights = model.get_weights() new_Model = Sequential.from_config(config) new_Model.set_weights(weights) # export saved model export_path = 'YOUR_EXPORT_PATH' + '/export' builder = saved_model_builder.SavedModelBuilder(export_path) signature = predict_signature_def(inputs={'NAME_YOUR_INPUT': new_Model.input}, outputs={'NAME_YOUR_OUTPUT': new_Model.output}) with K.get_session() as sess: builder.add_meta_graph_and_variables(sess=sess, tags=[tag_constants.SERVING], signature_def_map={ signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature}) builder.save() However, in Keras 2.1.3, keras.backend no longer seems to have clear_session(), set_session(), or get_session(). What's the modern way of handling this issue? Do those functions live elsewhere now? Thanks!
score: 0
tagged with: tensorflow

http://stackoverflow.com/comment/92383828
comment on: http://stackoverflow.com/q/52723458
has text: Error also appears
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52633209
accepted answer: http://stackoverflow.com/a/52633653
type: AnsweredQuestion
score: 1
tagged with: pyside2
upvote count: 1
has title: change label style temporary (imitate button)
type: Question
tagged with: qlabel
has body: I need to ask you guys for advice, as I'm running out of ideas. I'm working onclickable label. I have already done some "clickable label" class and handled mouseover event - which changes the label border and returns to the normal state when the mouse leaves. Now I want it to have a custom glow effect on the label, but I want it to return to normal state after, let's say 0.5 s from a click. I want my label with an image to imitate button. time.sleep does not work nice, especially with spamming clicks it freezes application main thread. Hope I am not reinventing the wheel but as far as I know that's the way to go. Heres the sample code, any answer is appreciated. from PySide2.QtWidgets import QLabel, QSizePolicy, QGraphicsDropShadowEffect from PySide2.QtGui import QPixmap from PySide2.QtCore import (Signal, QEvent, QObject, QRect) class ClickableLabel(QLabel): def __init__(self, pic_path, width, height, border_color, click_function): super(ClickableLabel, self).__init__() # Setting the picture path and setting pixmap to label self.pic_path = pic_path self.pixmap = QPixmap(self.pic_path) self.setPixmap(self.pixmap) # Set the size self.setFixedSize(width, height) # Enable tracking and assign function self.setMouseTracking(True) self.click_function = click_function # Set default if border_color is None: self.border_color = 'lightblue' else: self.border_color = border_color def mouseMoveEvent(self, event): # event.pos().x(), event.pos().y() self.setStyleSheet("border: 1px solid " + str(self.border_color) + ";") def leaveEvent(self, event): # event.pos().x(), event.pos().y() self.setStyleSheet("border: None") def mousePressEvent(self, event): self.click_function() effect = QGraphicsDropShadowEffect(self) effect.setOffset(0, 0) effect.setBlurRadius(20) effect.setColor(self.border_color) self.setGraphicsEffect(effect)
has answer: http://stackoverflow.com/a/52633653
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52623197
favorite count: 0
tagged with: python
tagged with: merge
score: 2
possible better answer: http://stackoverflow.com/a/52623751
type: AnsweredQuestion
tagged with: join
upvote count: 2
has answer: http://stackoverflow.com/a/52623297
has body: I have 2 dataframes like so: import pandas as pd data1 = {'Col1':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], 'Col2':[3.409836, 2.930693, 2.75, 3.140845, 2.971429, 2.592593, 2.6, 3.1875, 2.857143, 0.714286]} df1 = pd.DataFrame(data1, columns=['Col1', 'Col2']) data2 = {'Col1':['B', 'F', 'I'], 'Col2':[23.45, 32.57, 19.85]} df2 = pd.DataFrame(data2, columns=['Col1', 'Col2']) I want to modify the values of Col2 in df1 with the values from df2. This is my code to do that: for i in range(len(df2)): for j in range(len(df1)): if df2['Col1'][i]==df1['Col1'][j]: df1['Col2'][j]=df2['Col2'][i] The code works: But the problem is, this code would be slow for large dataframes as it has complexity O(len(df1)*len(df2)). How do I merge the 2 dataframes in a faster, more efficient way? I tried merging the dataframes using outer join, but it does not produce the correct result - it keeps both values: pd.merge(df1, df2, how='outer') An inner join produces a blank dataframe, a left join produces the same dataframe as df1, and a right join produces the same dataframe as df2.
accepted answer: http://stackoverflow.com/a/52623297
type: Question
has title: How to modify the values in a dataframe based on the values from another dataframe in an efficient way?
tagged with: dataframe
has answer: http://stackoverflow.com/a/52623751
answer count: 2
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/92413245
type: Comment
has text: If whatever doesn't yield still isn't cooperating after monkey patching and you can't change that, you'll have to put that code on a different thread. If you _do_ have control over it, you can try to locate the hot code and put some `gevent.sleep(0)` in it to see if that's the issue
type: QuestionComment
comment on: http://stackoverflow.com/q/52744234
score: 0

http://stackoverflow.com/comment/92353269
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52713859
has text: try result = [i for i in rows]
type: Comment

http://stackoverflow.com/comment/92155158
has text: Could you add your solution as an edit to my question?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52610316
type: AnswerComment

http://stackoverflow.com/a/52671658
accepted answer of: http://stackoverflow.com/q/52671142
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92273991
has comment: http://stackoverflow.com/comment/92274742
score: 4
answers question: http://stackoverflow.com/q/52671142
type: Answer
has comment: http://stackoverflow.com/comment/92287254
has comment: http://stackoverflow.com/comment/92275108
upvote count: 4
has comment: http://stackoverflow.com/comment/92273928
has comment: http://stackoverflow.com/comment/92274105
downvote count: 0
has comment: http://stackoverflow.com/comment/92274798
has body: strip() only removes leading and trailing characters. You can achieve that by using replace() instead: string = "-5.000,73" string = string.replace('.', '') string = string.replace(',', '.') # float(string.strip().strip("'")) float(string) string.strip(s[, chars]) Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on. More information can be found here Also, I'm not sure why you are trying to strip apostrophe's as well, but the syntax for that should be string.replace(''', ''); I would wait until you are done stripping characters to convert it too a float using float(). On a side note, you can use print statements in your code to see what is going wrong. As soon as I pasted your original code. It was apparent that the first period was not being removed from the string.
has comment: http://stackoverflow.com/comment/92290297

http://stackoverflow.com/comment/92401161
comment on: http://stackoverflow.com/a/52738194
has text: Yes it does. Try it!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92167668
type: QuestionComment
comment on: http://stackoverflow.com/q/52616591
has text: Rather than `from_records`, have you tried using the built-in [`pd.from_json()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html) function? It may handle the formatting more easily.
score: 0
type: Comment

http://stackoverflow.com/comment/92333814
score: 0
has text: You have to use `os.path.isfile()` to get only files. I suggest you to study [The Python Standard Library](https://docs.python.org/3/library/)
comment on: http://stackoverflow.com/q/52703454
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52661915
answer count: 1
score: 1
has body: I have my very simple GUI built with tkinter containing a progress bar which should show program activity during long processing function. As I understand I have to use threads as tkinter is single threaded so I wrote following code: def start(self): self.root.progressbar.start(interval=5) try: path = tk.filedialog.asksaveasfilename(initialfile='log.txt', filetypes=[("Text file", "*.txt")], initialdir='~/Desktop') if path: filtering_thread = FilteringThread(self.comparator) filtering_thread.run() self.root.progressbar.stop() self.comparator.log_matches(path) else: messagebox.showinfo("Error", "Choose path to save result.") except FileNotFoundError as e: messagebox.showinfo("Error", str(e)) And here is my FilteringThread implementation: class FilteringThread(Thread): def __init__(self, comparator): Thread.__init__(self) self.comparator = comparator def run(self): import time for _ in range(5): time.sleep(1) print("IN THREAD") As for now it just mimics the behavior of a real function but the idea stays the same. I should see in the console that it prints "IN THREAD" 5 times while to progress bar should bounce around the GUI. But it doesn't work: could anyone point me an error that I am making? I am running out of ideas.
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
tagged with: multithreading
has answer: http://stackoverflow.com/a/52661980
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52661980
has title: Function execution freezes GUI despite using Threads
type: Question
downvote count: 0

http://stackoverflow.com/comment/92390977
comment on: http://stackoverflow.com/q/52728756
type: Comment
type: QuestionComment
has text: since it's a windows system \\ should be ok. original_dir = 'datasets/catsvdogs'. it seems like 'cats' in original_dir got removed by the time the error occurred. 'datasets/vdogstrain\\cat.0.jpg'
score: 0

http://stackoverflow.com/comment/92142135
comment on: http://stackoverflow.com/q/52597454
score: 0
has text: f2py wraps the call automatically so that you don't see the `n1in` argument. Unless you have a specific motivation to have it removed, I don't see a specific direction. If you want a library that is callable by Fortran as well with "assumed shape arrays", you can define another routine that has the calling convention you wish.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92313426
type: QuestionComment
comment on: http://stackoverflow.com/q/52693294
score: 0
has text: *"have I not already risked the cyclic garbage collector kicking in"* Yes, of course you have. If that's a problem, you either shouldn't be using a WeakSet or you shouldn't be dropping all references to `obj2` and `obj3`.
type: Comment

http://stackoverflow.com/comment/92311052
has text: Apparently you have fixed the problem since (and likely due to) my previous comment—so it now looks like it would work.
type: Comment
comment on: http://stackoverflow.com/a/52691506
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92396750
has text: I don't know about virtualenv, but if you might consider "packaging" your app as a docker image
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52734619
type: QuestionComment

header
type: Tag
tags question: http://stackoverflow.com/q/52602654
tag name: header
tags question: http://stackoverflow.com/q/52688527

http://stackoverflow.com/comment/92267114
has text: `itertools.product()` would have been my answer too. But I have a feeling the criteria is not as simple as `(3, 6, 10)` given the latest series of comments.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52668623
type: AnswerComment

http://stackoverflow.com/comment/92641622
comment on: http://stackoverflow.com/a/52750981
has text: or in short, i just want to know which timeseries information each of the color is representing or what information does a particular color convey?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92224627
comment on: http://stackoverflow.com/q/52646106
score: 0
type: Comment
type: QuestionComment
has text: I didn't downvote but I don't see a question here nor do I understand your requirement. You might want to rewrite that question and maybe post some sample data with the expected output (of the csv in question as the title implies).

http://stackoverflow.com/a/52705740
answers question: http://stackoverflow.com/q/52693572
has comment: http://stackoverflow.com/comment/92369016
has comment: http://stackoverflow.com/comment/92340362
has comment: http://stackoverflow.com/comment/92367549
accepted answer of: http://stackoverflow.com/q/52693572
has comment: http://stackoverflow.com/comment/92369019
has body: It's a well-asked question apart from the fact that you could have defined "within some range of the initial positions of the other random walks" better. I will assume that you mean some distance in x or y or some distance criterion in the x,y plane. The following outlines a solution for a distance criterion in x only, but the extension to other criteria is straightforward. Basically you want a checking criterion at the end of you inner for-loop: distance_in_x = np.mod(np.abs(xvec - xstore[j+1]), lsize) distance_in_x[i] = np.inf # effectively mask that position if np.any(distance_in_x &lt;= min_distance_in_x): break This assumes that you have defined min_distance_in_x somewhere above. The basic trick is that you mask the distance to origin of the walk itself by adding infinity to it. Similarly, you could also just add min_distance_in_x to ensure that the check in the following line never picks up that origin. Edit For a square around the origin of starting points, the script becomes: import numpy.random as rd import numpy as np import matplotlib.pyplot as plt import matplotlib import numpy.ma as ma lsize=100 T=1000 #n of steps N=10 #n of walks xvec=np.zeros(N) yvec=np.zeros(N) xmat=np.full((T+1,N), np.nan) ymat=np.full((T+1,N), np.nan) min_distance_in_x = 3 min_distance_in_y = 3 # randomly assigns initial position for i in range(N): xcor=rd.randint(1,lsize) ycor=rd.randint(1,lsize) xvec[i]=xcor yvec[i]=ycor # walk for i in range(N): xstore=np.full(T+1, np.nan) ystore=np.full(T+1, np.nan) xstore[0]=xvec[i] ystore[0]=yvec[i] for j in range(T): A=[0,1,2,3] temp=rd.choice(A) if temp==0: ystore[j+1]=ystore[j]+1 #up xstore[j+1]=xstore[j] elif temp==1: xstore[j+1]=xstore[j]+1 #right ystore[j+1]=ystore[j] elif temp==2: ystore[j+1]=ystore[j]-1 #down xstore[j+1]=xstore[j] elif temp==3: xstore[j+1]=xstore[j]-1 #left ystore[j+1]=ystore[j] xstore[j+1]=np.mod(xstore[j+1], lsize+1) ystore[j+1]=np.mod(ystore[j+1], lsize+1) distance_in_x = np.abs(xvec - xstore[j+1]) distance_in_x[i]…
has comment: http://stackoverflow.com/comment/92339297
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92340089
has comment: http://stackoverflow.com/comment/92367664
has comment: http://stackoverflow.com/comment/92339411
score: 0
has comment: http://stackoverflow.com/comment/92339197
has comment: http://stackoverflow.com/comment/92339887
type: Answer

http://stackoverflow.com/comment/92416080
type: Comment
comment on: http://stackoverflow.com/a/52743441
type: AnswerComment
has text: @OfficialThrowaway No, `TimeDistributed` does not make copies of the given layer or model, it only applies it over a dimension. Actually, it cannot possibly make `N` copies, since `N` is unknown (it can be different for each input). Only one instance of the small model is created, with `small_model()`, and passed to `TimeDistributed`, which will "broadcast it" to the whole input.
score: 0

http://stackoverflow.com/q/52742984
tagged with: glm
has comment: http://stackoverflow.com/comment/92411533
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/92416759
tagged with: http://stackoverflow.com/tag/r
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92411588
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/28747019
tagged with: logistic-regression
type: Question
linked to: http://stackoverflow.com/q/31671860
has comment: http://stackoverflow.com/comment/92411612
has body: I'm getting completely different results when I run a logistic regression in R from when I run it in Python on the same data. The intercepts and coefficients are very different from each other I've seen this same problem posted here, however the solution there is that for the given data set, the X and Y variables exhibit perfect separation, however in my own data there is no perfect separation. Here's a reproducible example in R: x_examp &lt;- c(1,4,7,9,13,17,22,25,29,30,35,40,44,47,50) y_examp &lt;- c(1,1,1,1,0,1,0,0,1,0,0,0,0,0,0) mod = glm(y_examp ~ x_examp, family = 'binomial') summary(mod) which gives these coefficients (the estimates): Coefficients: Estimate Std. Error z value Pr(&gt;|z|) (Intercept) 3.15324 1.75197 1.800 0.0719 . x_examp -0.16534 0.07996 -2.068 0.0387 * And here's an logistic regression in Python using the same data: x_examp = np.array([1,4,7,9,13,17,22,25,29,30,35,40,44,47,50]) x_examp = x_examp.reshape(-1, 1) y_examp = np.array([1,1,1,1,0,1,0,0,1,0,0,0,0,0,0]) from sklearn.linear_model import LogisticRegression LR = LogisticRegression() LR.fit(x_examp, y_examp) print('intercept:', LR.intercept_) print('coefficient:', LR.coef_[0]) which returns: intercept: [ 1.11232593] coefficient: [-0.08579351] Given that the standard error is calculated using the predicted values, which in turn depend on the coefficients, the standard error will differ from that calculated in R, and z-statistics and corresponding probability will also differ. Clearly the results are very different, does anyone know why this is the case, and which one is correct?
duplicate of: http://stackoverflow.com/q/28747019
linked to: http://stackoverflow.com/q/37873564
has comment: http://stackoverflow.com/comment/92411402
has title: Different Logistic Regression results with R and Python
score: 0

http://stackoverflow.com/q/52719781
has comment: http://stackoverflow.com/comment/92365975
tagged with: python
has comment: http://stackoverflow.com/comment/92368262
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92364933
tagged with: integration
has answer: http://stackoverflow.com/a/52720192
has title: Integrating over a region to find probability
has comment: http://stackoverflow.com/comment/92364991
type: Question
has comment: http://stackoverflow.com/comment/92365914
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92365048
has body: I have a joint PDF p(x,y), where 0&lt;x&lt;1, 0&lt;y&lt;1. I want to find the probability to land in certain region in the parameter space. The parameter space is divided as the following picture: The division is governed by a list flist. Points where flist[i][j] = 1 are painted yellow, flist[i][j]=-1 are painted purple and flist[i][j]=0 are painted turquoise. The space division is discrete, i.e. there is no function g(x,y) that returns 1,-1,0, but rather the list flist was calculated with finite resolution, in a way not relevant to the question. The list flist was not generated by the probability distribution. It is an independent thing, used just to get the separation of the parameter space. Now, given the PDF p(x,y), I want to find the probability to land on the yellow zone. I need to integrate over the yellow zone in order to find this value. The thing is, I don't have a formula for the curve that separates the yellow region from the rest. I am afraid of using heavy machine learning tools, since I am not familiar with them. Is there a simpler way, using the list flist, to integrate over the yellow region?

http://stackoverflow.com/a/52694134
score: 0
type: AcceptedAnswer
has body: As far as I understood, this seems like the code you want: total = 0 def process_order(x_list): global total for x in x_list: print(f"You filled an order for {x[1]} {x[0]} for a total of {x[1]* x[2]}") total = total + x[1] * x[2] return x = [("oranges", 4, 3.22),("gummy bears",1,1.99),("sour bites", 3, 2.33), ("antacid", 1, 5.33)] process_order(x) print("Total price: ${:.2f}".format(total)) Output: You filled an order for 4 oranges for a total of 12.88 You filled an order for 1 gummy bears for a total of 1.99 You filled an order for 3 sour bites for a total of 6.99 You filled an order for 1 antacid for a total of 5.33 Total price: $27.19 You need to define total as a global variable to get a overall total of the prices. Also, you can iterate through the list in python, as for list_element in list. If you want to make a function, it needs return statement at the end. In this case, what you have to do is to add each prices to global variable, and print out the process for each items, there's no need to return something.
accepted answer of: http://stackoverflow.com/q/52694063
type: Answer
answers question: http://stackoverflow.com/q/52694063
has comment: http://stackoverflow.com/comment/92314997
has comment: http://stackoverflow.com/comment/92315043

http://stackoverflow.com/a/52675074
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/92280730
has comment: http://stackoverflow.com/comment/92279705
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92280703
has comment: http://stackoverflow.com/comment/92280016
answers question: http://stackoverflow.com/q/52675027
type: Answer
accepted answer of: http://stackoverflow.com/q/52675027
has comment: http://stackoverflow.com/comment/92279589
has body: This github issue suggests you should set the sqs client in the top-level once (rather than in the function): sqs = boto3.client('sqs', region_name=S3_BUCKET_REGION, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) def consume_msgs(): # code to process message

http://stackoverflow.com/comment/92287882
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52679322
has text: You need to convert your strings to numbers. Since it seems this code comes up a lot, may I ask where you got that from? Maybe one can edit it such that not every other week someone falls into that trap.

http://stackoverflow.com/comment/92408175
type: QuestionComment
has text: @chepner oops, missed it. The loop still looks wonky. I can't see that they want to print the entire list all those times.
score: 0
comment on: http://stackoverflow.com/q/52741624
type: Comment

http://stackoverflow.com/a/74314321
has body: if you require the slideshow cell editing functionality you can either set it in the metadata as explained in this question, or you can switch from Lab to Notebook by going Help &gt;&gt; Launch Classic Notebook. re: However, this doesn’t give me the slideshow cell editing functionality I need in the notebook.
type: Answer
answers question: http://stackoverflow.com/q/52677085
score: 0

querying
type: Tag
tag name: querying
tags question: http://stackoverflow.com/q/52596100

http://stackoverflow.com/comment/92159493
comment on: http://stackoverflow.com/q/52612487
type: Comment
type: QuestionComment
has text: Your indentation is messed up, `reps` is being defined inside the function. Also you want to replace an empty string with `%%25` which doesn't make any sense, and the replacement of `%%` must be done first or it'll run on the other replacements.
score: 0

http://stackoverflow.com/q/52606329
answer count: 1
downvote count: 0
has body: I am trying to get the value from a variable and pass it into xlsxwriter filename. Here is my code: company_code = 'XXX' workbook = xlsxwriter.Workbook('Funddata_'+(company_code)+'_%s.xlsx' %timestr) worksheet = workbook.add_worksheet() My output file name I am getting is Funddata__201810.xlsx but I am trying to get Funddata_XXX_201810.xlsx
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92259832
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52607596
upvote count: 2
tagged with: xlsxwriter
has title: how to pass a variable value to a file naming string in xlsxwriter
has comment: http://stackoverflow.com/comment/92149211
accepted answer: http://stackoverflow.com/a/52607596
type: Question

http://stackoverflow.com/comment/92353690
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52714009
has text: You cannot slice a file object directly, but you can use `itertools.islice` to do so.

http://stackoverflow.com/comment/92406361
score: 1
has text: maybe use the parameter 'a', instead of 'w'. The values will be replaces if you use `open("file.txt","w") `. Use `open("file.txt","a")`
comment on: http://stackoverflow.com/a/52740234
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92378180
type: QuestionComment
has text: You should reconsider your approach for this problem altogether. Dynamic variable names are almost always a glaring design flaw.
comment on: http://stackoverflow.com/q/52724963
score: 0
type: Comment

http://stackoverflow.com/comment/92388090
type: QuestionComment
type: Comment
has text: If `/to` is an argument to the process being started, it should have quotes around it when passed to `subprocess` as one of the arguments. Similar to what's in my answer to the question [cmd to run exe not working from Python](https://stackoverflow.com/questions/32150690/cmd-to-run-exe-not-working-from-python) which shows an example of passing them.
comment on: http://stackoverflow.com/q/52730667
score: 0

http://stackoverflow.com/comment/92403913
type: Comment
has text: @MohamedThasinah you're wellcome. Maybe you should add "email" tag to the question.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52739475

http://stackoverflow.com/comment/92160428
type: QuestionComment
type: Comment
has text: Indeed, the code has many discrepancies with your documentation...very very old
comment on: http://stackoverflow.com/q/52612693
score: 0

http://stackoverflow.com/comment/92315367
score: 0
comment on: http://stackoverflow.com/q/52694251
type: QuestionComment
has text: Possible duplicate of [Python - Decode UTF-16 file with BOM](https://stackoverflow.com/questions/22459020/python-decode-utf-16-file-with-bom)
type: Comment

http://stackoverflow.com/comment/92268342
score: 0
type: Comment
type: QuestionComment
has text: If *you* have created the site, why do you need to crawl it or download anything from it?!
comment on: http://stackoverflow.com/q/52669276

http://stackoverflow.com/comment/92376269
type: Comment
has text: I was able to crack a few but the count did not increase even after running hashcat over night.
comment on: http://stackoverflow.com/a/52706289
score: 0
type: AnswerComment

http://stackoverflow.com/a/52705064
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52704777
has body: Vectorized solution using open grids We could use two open range/grid arrays for N simulating the same behavior as the iterators - I = np.arange(N) mask = (I[:,None] - c)**2 + (I - c)**2 &lt; r_0**2/dh2 out = np.where(mask,phi_0,0) For a generic range on the two loops For the generic case where we would iterate through two loops that extend till say M and N respectively, we could make use of np.ogrid to create those open grids and then use on the same lines - I,J = np.ogrid[:M,:N] mask = (I - c)**2 + (J - c)**2 &lt; r_0**2/dh2 For a generic number of loops For a generic number of loops, simply create as many variables as the number of loops. Hence, for three loops : for i in range(M): for j in range(N): for k in range(P): , we would have : I,J,K = np.ogrid[:M,:N,:P] , then use I,J,K instead of i,j,k respectively for element-wise operations like we have here. Alternative to replace last step for this specific case Last step could also be implemented with elementwise multiplication by scaling to phi_0 with mask as the else part is setting to 0s - out = mask*phi_0
answers question: http://stackoverflow.com/q/52704777
type: Answer
downvote count: 0
score: 7

http://stackoverflow.com/comment/130503709
type: Comment
type: QuestionComment
has text: Can the moderators please find out who voted this down, and take away their voting rights please?
comment on: http://stackoverflow.com/q/52688527
score: 0

http://stackoverflow.com/a/52721074
score: 0
answers question: http://stackoverflow.com/q/52720583
type: Answer
has body: This should get you the timedelta you need- from datetime import datetime a="060453" b="135309" a = datetime.strptime(a,'%H%M%S') b = datetime.strptime(b,'%H%M%S') print(b-a)

http://stackoverflow.com/comment/92187999
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52627238
has text: That's not how type hinting works, and your sample code throws a `TypeError`. That's for a reason; the syntax is used for *static type checking*, not dynamic type checking.

web-scraping
tags question: http://stackoverflow.com/q/52638934
tags question: http://stackoverflow.com/q/52728333
tags question: http://stackoverflow.com/q/52647129
tags question: http://stackoverflow.com/q/52745495
tags question: http://stackoverflow.com/q/52730256
tags question: http://stackoverflow.com/q/52679150
tags question: http://stackoverflow.com/q/52688518
tags question: http://stackoverflow.com/q/52679502
tags question: http://stackoverflow.com/q/52741194
tags question: http://stackoverflow.com/q/52669276
tags question: http://stackoverflow.com/q/52606752
tags question: http://stackoverflow.com/q/52588759
tags question: http://stackoverflow.com/q/52701358
tags question: http://stackoverflow.com/q/52593742
tags question: http://stackoverflow.com/q/52679582
tags question: http://stackoverflow.com/q/52658754
tags question: http://stackoverflow.com/q/52641465
tags question: http://stackoverflow.com/q/52626682
tags question: http://stackoverflow.com/q/52705564
tags question: http://stackoverflow.com/q/52730924
tags question: http://stackoverflow.com/q/52690994
tags question: http://stackoverflow.com/q/52675837
tags question: http://stackoverflow.com/q/52593716
tags question: http://stackoverflow.com/q/52667008
tags question: http://stackoverflow.com/q/52591299
tags question: http://stackoverflow.com/q/52690615
tags question: http://stackoverflow.com/q/52595907
tags question: http://stackoverflow.com/q/52604717
tags question: http://stackoverflow.com/q/52696433
tags question: http://stackoverflow.com/q/52604157
tags question: http://stackoverflow.com/q/52707117
tags question: http://stackoverflow.com/q/52695732
tags question: http://stackoverflow.com/q/52622909
tags question: http://stackoverflow.com/q/52619754
tags question: http://stackoverflow.com/q/52648227
tags question: http://stackoverflow.com/q/52662818
tags question: http://stackoverflow.com/q/52653224
tags question: http://stackoverflow.com/q/52642938
tags question: http://stackoverflow.com/q/52687372
tags question: http://stackoverflow.com/q/52742399
tags question: http://stackoverflow.com/q/52623178
tags question: http://stackoverflow.com/q/52652313
tags question: http://stackoverflow.com/q/52681511
tags question: http://stackoverflow.com/q/52726555
tags question: http://stackoverflow.com/q/52674180
tags question: http://stackoverflow.com/q/52591846
tags question: http://stackoverflow.com/q/52659057
tags question: http://stackoverflow.com/q/52713230
tags question: http://stackoverflow.com/q/52685458
tags question: http://stackoverflow.com/q/52721822
tag name: web-scraping
tags question: http://stackoverflow.com/q/52657610
tags question: http://stackoverflow.com/q/52676925
tags question: http://stackoverflow.com/q/52675659
tags question: http://stackoverflow.com/q/52744591
tags question: http://stackoverflow.com/q/52594688
tags question: http://stackoverflow.com/q/52728529
tags question: http://stackoverflow.com/q/52617523
tags question: http://stackoverflow.com/q/52702421
type: Tag
tags question: http://stackoverflow.com/q/52689873
tags question: http://stackoverflow.com/q/52627163
tags question: http://stackoverflow.com/q/52693854
tags question: http://stackoverflow.com/q/52667677
tags question: http://stackoverflow.com/q/52594179
tags question: http://stackoverflow.com/q/52684338
tags question: http://stackoverflow.com/q/52693786
tags question: http://stackoverflow.com/q/52687155
tags question: http://stackoverflow.com/q/52738492
tags question: http://stackoverflow.com/q/52721709
tags question: http://stackoverflow.com/q/52741739
tags question: http://stackoverflow.com/q/52685754
tags question: http://stackoverflow.com/q/52654022
tags question: http://stackoverflow.com/q/52683320
tags question: http://stackoverflow.com/q/52730332
tags question: http://stackoverflow.com/q/52733657
tags question: http://stackoverflow.com/q/52649992
tags question: http://stackoverflow.com/q/52629888
tags question: http://stackoverflow.com/q/52641121
tags question: http://stackoverflow.com/q/52630438

snappy
type: Tag
tags question: http://stackoverflow.com/q/52656972
tag name: snappy

http://stackoverflow.com/comment/92281686
comment on: http://stackoverflow.com/q/52674893
has text: As you've noticed, a `Session` is not thread safe. A scoped session might help, but that depends on your app.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52597678
score: 0
tagged with: pandas
has title: Append only unlike data from one .csv to another .csv
answer count: 1
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/92130068
has body: I have managed to use Python with the speedtest-cli package to run a speedtest of my Internet speed. I run this every 15 min and append the results to a .csv file I call "speedtest.csv". I then have this .csv file emailed to me every 12 hours, which is a lot of data. I am only interested in keeping the rows of data that return less than 13mbps Download speed. Using the following code, I am able to filter for this data and append it to a second .csv file I call speedtestfilteronly.csv. import pandas as pd df = pd.read_csv('c:\speedtest.csv', header=0) df = df[df['Download'].map(lambda x: x &lt; 13000000.0,)] df.to_csv('c:\speedtestfilteronly.csv', mode='a', header=False) The problem now is it appends all the rows that match my filter criteria every time I run this code. So if I run this code 4 times, I receive the same 4 sets of appended data in the "speedtestfilteronly.csv" file. I am looking to only append unlike rows from speedtest.csv to speedtestfilteronly.csv. How can I achieve this? I have got the following code to work, except the only thing it is not doing is filtering the results to &lt; 13000000.0 mb/s: Any other ideas? import pandas as pd df = pd.read_csv('c:\speedtest.csv', header=0) df = df[df['Download'].map(lambda x: x &lt; 13000000.0,)] history_df = pd.read_csv('c:\speedtest.csv') master_df = pd.concat([history_df, df], axis=0) new_master_df = master_df.drop_duplicates(keep="first") new_master_df.to_csv('c:\emailspeedtest.csv', header=None, index=False)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52597758
has comment: http://stackoverflow.com/comment/92130785
type: Question

http://stackoverflow.com/comment/92403677
has text: Also, this `if user in obj.likes.all()` is terribly innefficient. You want `if obj.likes.filter(user_id=user.id).exists()` instead.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52736004
type: QuestionComment

http://stackoverflow.com/comment/92836148
type: AnswerComment
has text: @abhikrishnan Read the Qt docs and the examples of Qt and PyQt, in addition to the thousands of SO answer.
type: Comment
comment on: http://stackoverflow.com/a/52737656
score: 0

http://stackoverflow.com/comment/92264245
type: QuestionComment
score: 0
has text: You shouldn't be gluing values from your request directly into your SQL. You're inviting [SQL injection](https://xkcd.com/327/).
comment on: http://stackoverflow.com/q/52667206
type: Comment

http://stackoverflow.com/comment/92186572
comment on: http://stackoverflow.com/a/52626594
score: 0
type: AnswerComment
type: Comment
has text: Also how do I get the the value within the list to use it later on?

http://stackoverflow.com/a/52681216
has body: Here is how I will approach it: import pandas as pd from io import StringIO import numpy as np s = '''Site Year Action Measurement A 2014 1 100 A 2015 0 150 A 2016 0 300 A 2017 0 80 B 2014 0 200 B 2015 1 250 B 2016 1 60 B 2017 0 110 ''' ss = StringIO(s) df = pd.read_csv(ss, sep=r"\s+") df_maintain = df[df.Action==1]'Site', 'Year' df_maintain.reset_index(drop=True, inplace=True) df_maintain def find_last_maintenance(x): df_temp = df_maintain[x.Site == df_maintain.Site] gap = [0] for ind, row in df_temp.iterrows(): if (x.Year &gt;= row['Year']): gap.append(x.Year - row['Year'] + 1) return gap[-1] df['Gap'] = df.apply(find_last_maintenance, axis=1) df = df[df.Gap !=0] This generates the desired output.
type: Answer
has comment: http://stackoverflow.com/comment/92291013
has comment: http://stackoverflow.com/comment/92322782
has comment: http://stackoverflow.com/comment/92292808
answers question: http://stackoverflow.com/q/52681048
score: 0

http://stackoverflow.com/comment/92239817
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52654116
has text: I understand that you press twice Ctrl+f, why do you do it ?, if the popup is open and press Ctrl+f Should another popup open or just do nothing?
score: 0

http://stackoverflow.com/q/52686639
has title: tensorflow lstm convert to tensor tpu model?
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/55166711
type: AnsweredQuestion
type: Question
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/55166711
has body: what issue can be? from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Input, LSTM, Dense def create_model(): # create a small LSTM network model = Sequential() model.add(LSTM(20, input_shape=(X.shape[1], X.shape[2]), return_sequences=True)) model.add(LSTM(20, return_sequences=True)) model.add(LSTM(10, return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(4, return_sequences=False)) model.add(Dense(4, kernel_initializer='uniform', activation='relu')) model.add(Dense(1, kernel_initializer='uniform', activation='relu')) import tensorflow as tf tf.logging.set_verbosity(tf.logging.DEBUG) tf.keras.backend.clear_session() model=create_model() tpu_model = tf.contrib.tpu.keras_to_tpu_model( model, strategy=tf.contrib.tpu.TPUDistributionStrategy( tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER))) WARNING:tensorflow:tpu_model (from tensorflow.contrib.tpu.python.tpu.keras_support) is experimental and may change or be removed at any time, and without warning. ValueError: Fetch argument cannot be interpreted as a Tensor. (Tensor Tensor("lstm_13/kernel:0", shape=(79, 320), dtype=float32_ref) is not an element of this graph.)
tagged with: python

http://stackoverflow.com/comment/92269305
comment on: http://stackoverflow.com/q/52669705
has text: I put `import cv2` in the beginning of my code
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52708422
answers question: http://stackoverflow.com/q/52708273
score: 4
has body: Here is one potential work-around: headers = pd.read_csv('%sdt.dat'%s, delim_whitespace=True, nrows=0).columns[1:] dat = pd.read_csv('%sdt.dat'%s, delim_whitespace=True, header=None, skiprows=1, names=headers) alternatively, you could fix the columns with some post-processing: col_mapper = {old:new for old, new in zip(dat.columns, dat.columns[1:])} dat = dat.iloc[:, :-1].rename(col_mapper, axis=1)
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/92263161
type: QuestionComment
comment on: http://stackoverflow.com/q/52665888
score: 0
has text: Could you update your question to include your code as text, not as an image? It's difficult to help when the code isn't easily accessible.
type: Comment

http://stackoverflow.com/comment/92296303
score: 0
has text: I would remove the OP's original code form your answer.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52684181

http://stackoverflow.com/comment/92210349
type: Comment
comment on: http://stackoverflow.com/a/52638507
has text: I try the code you send but when check df = pd.DataFrame(df_All['Category'].map(dict(zip(s,s.index.get_level_values(1))))) it missing the count
type: AnswerComment
score: 0

http://stackoverflow.com/q/52632693
has body: I'm trying to write a small Python program to check whether an SSH server allows a password authentication. Here is the current plan: import base64 import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('ssh.example.com', username='strongbad', password='thecheat') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print('... ' + line.strip('\n')) client.close() The idea is to grep the output or to later put a try catch block around the connect statement. My problem however is that some of the systems that I run the program on have access via a RSA key that is stored under ~/.ssh. And in these cases, the connect will simply succeed (which I want to avoid). So, here is the question: Does anybody know any way to force Paramiko (or another SSH client) to use passwords? Thanks
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52633640
upvote count: 10
type: Question
score: 10
tagged with: paramiko
accepted answer: http://stackoverflow.com/a/52633640
downvote count: 0
tagged with: ssh
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/10670217
tagged with: python
has title: Force password authentication (ignore keys in .ssh folder) in Paramiko in Python

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/52605067

http://stackoverflow.com/comment/92298421
type: Comment
has text: thanks! so to clarify, it is not necessary that a python function must have a returned value and that it is also not necessary for a python function to have input arguments then?
comment on: http://stackoverflow.com/a/52685383
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92118119
type: AnswerComment
comment on: http://stackoverflow.com/a/52591564
score: 0
has text: Note: sets don't preserve the order! Which means in this case it might not be a viable solution, as you cannot guarantee to get the desired output as specified in the question.
type: Comment

http://stackoverflow.com/q/52671829
has answer: http://stackoverflow.com/a/52671896
has comment: http://stackoverflow.com/comment/92273570
has body: Basically, I am trying to generate a random 4 digit number and then split that number and assign each digit to a separate variable. I'm new to python and I honestly have no idea what I am doing, I got the create random number code from the internet as well as the code to split the string so I can't really self diagnose the problem. Any help is appreciated! from random import * number = randint(1000,9999) strnumber = str(number) a,b,c,d = strnumber.split([strnumber[i:i+1] for i in range(0, len(strnumber), 1)]) print(a) print(b) print(c) print(d) The Error message is as follows: Traceback (most recent call last): File "D:\Documents HDD\Python\Mastermind Task.py", line 4, in a,b,c,d = strnumber.split([strnumber[i:i+1] for i in range(0, len(strnumber), 1)]) TypeError: must be str or None, not list Edit: Okay, I promise I'm not a complete idiot, I simply copied the wrong thing into the post, I have fixed the rather embarrassing typos.
favorite count: 0
has answer: http://stackoverflow.com/a/52677053
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92273537
has answer: http://stackoverflow.com/a/52672478
has answer: http://stackoverflow.com/a/52671957
upvote count: 2
answer count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92273450
score: 1
downvote count: 1
type: Question
tagged with: string
has comment: http://stackoverflow.com/comment/92273483
has answer: http://stackoverflow.com/a/52671953
has title: Trying to split a string but I keep getting this error: "Type Error: must be str or None, not list"

http://stackoverflow.com/a/52712649
answers question: http://stackoverflow.com/q/52712513
has body: You might be overthinking it. Try this. from dateutil.parser import parse import csv def get_julian(_date): # _date is holding 20150926T104044Z the_date = parse(_date) julian_start = parse('19000101T000000Z') julian_days = (the_date - julian_start).days return julian_days with open('filename.csv') as f: csv_reader = csv.reader(f) for row in csv_reader: # Column 2, right? row[1] = get_julian(row[1]) # Do things and stuff with your corrected data.
has comment: http://stackoverflow.com/comment/92351472
has comment: http://stackoverflow.com/comment/92351573
type: Answer
has comment: http://stackoverflow.com/comment/92351636
has comment: http://stackoverflow.com/comment/92351449
score: 0
has comment: http://stackoverflow.com/comment/92351531
has comment: http://stackoverflow.com/comment/92351603
has comment: http://stackoverflow.com/comment/92351526
accepted answer of: http://stackoverflow.com/q/52712513
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92351520

http://stackoverflow.com/comment/92443544
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52747703
type: Comment
has text: Thanks for the suggestions, will this work when my sample names are not sequential like Sample A, B, C, D etc? I have over 300 samples and the names are like a bar code. example xx27-03-A10X and xx27-7A-73F0

http://stackoverflow.com/comment/92191308
has text: What's the `tensorflow-gpu` version you're testing this on? I tested `tensorflow-gpu` on 1.4.0 and the latest one, both on a `cpu-only`. None of them worked, as expected.
score: 0
comment on: http://stackoverflow.com/a/52627105
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52605549
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/52605625
accepted answer: http://stackoverflow.com/a/52605625
tagged with: pandas
has title: Assigning dataframe id based on id in another dataframe
downvote count: 0
answer count: 1
has body: I have two dataframes called dataframe A and dataframe B A id| column1 |column2 3 | 439 | 2398 41| 498 | 34 2 | 233 | 43 B column1 |column2 439 | 2398 498 | 56 233 | 43 I would like to assign an id column to dataframe B based on the ids in dataframe A. If a row is present in dataframe A and in dataframe B, I would like to assign the corresponding id from dataframe A to dataframe B. If a row in dataframe B is not in dataframe A I would like to assign "None" to that cell in the id column in B. That is, I would like to have B id | column1 |column2 3 | 439 | 2398 None| 498 | 56 2 | 233 | 43 Question: How do I assign the ids from dataframe A to dataframe B based on the columns in dataframe B?
favorite count: 0
tagged with: python-3.x
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/q/52650938
has title: Failed to establish a new connection error using Python requests Errno -2 Name or service unknown
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
has body: I am trying to make a request to an API with Python. I am able to make the request with curl without issue but I have something wrong with my Python request. Why does this code, import requests from requests.auth import HTTPBasicAuth emailadd = 'user123@example.com' domain = 'example.com' spantoken = 'omitted' def checkUserLicensed(useremail): url = ('https://api.spannigbackup.com/v1/users/' + useremail) print(url) response = requests.get(url, auth=(domain,spantoken)) print(response) checkUserLicensed(emailadd) Return this error requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.spannigbackup.com', port=443): Max retries exceeded with url: /v1/users/user123@example.com (Caused by NewConnectionError('&lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7f73ca323748&gt;: Failed to establish a new connection: [Errno -2] Name or service not known'))
type: Question
upvote count: 4
tagged with: api
downvote count: 0
score: 4
favorite count: 0

http://stackoverflow.com/comment/92196055
type: QuestionComment
has text: That said, in the guide for using Django with EB, it clearly says you need to install Django using pip command under "Set Up a Python Virtual Environment with Django" https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html
comment on: http://stackoverflow.com/q/52630920
score: 0
type: Comment

http://stackoverflow.com/comment/92338956
comment on: http://stackoverflow.com/a/52705987
type: AnswerComment
score: 0
has text: Thank you, I'll add an extension to my initial post for clarity to check if I've asked it properly.
type: Comment

http://stackoverflow.com/q/52637220
score: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52637255
accepted answer: http://stackoverflow.com/a/52637282
answer count: 3
tagged with: python
type: AnsweredQuestion
has title: Diificulty in reading dataframe
has body: I have a csv file as follows: [8:3:1978] LOG [Sale:internals.py:makeSaleEntry:0] Entered with productid= 2327, storeid= 146, No.OfUnits= 1 [19:1:2007] LOG [Sale:internals.py:makeSaleEntry:1] Entered with productid= 1908, storeid= 202, No.OfUnits= 11 [22:4:2001] LOG [Sale:internals.py:makeSaleEntry:2] Entered with productid= 3072, storeid= 185, No.OfUnits= 16 [22:12:1915] LOG [Sale:internals.py:makeSaleEntry:3] Entered with productid= 1355, storeid= 177, No.OfUnits= 1 [19:8:1963] LOG [Sale:internals.py:makeSaleEntry:4] Entered with productid= 2235, storeid= 35, No.OfUnits= 16 [16:11:1997] LOG [Sale:internals.py:makeSaleEntry:5] Entered with productid= 1439, storeid= 141, No.OfUnits= 26 and I have read the file using a dataframe df. df = pd.read_csv('a.txt') I want to access the dataframe line-by-line and print in another csv file the productid, storeid and No.OfUnits as follows: 2327,146,1 1908,202,11 3072,185,16 1355,177,1 2235,35,16 1439,141,26 My piece of code is: for i, row in df.iterrows(): strr = "" for j, column in row.iteritems(): seq = column.split('= ') strr = strr + seq[1] + "," file = open("a.csv", "a") file.write(strr[:-1]+"\n") file.close() This code is working fine except it ignores writing the first line (2327,146,1). Please suggest changes.
type: Question
has answer: http://stackoverflow.com/a/52637395
has answer: http://stackoverflow.com/a/52637255
has answer: http://stackoverflow.com/a/52637282

http://stackoverflow.com/q/52726406
tagged with: pickle
upvote count: 1
downvote count: 1
has body: I'm working with a project and somewhere down the line my I have to uninstall and reinstall numpy to fix a problem, but then this happened Traceback (most recent call last): File "ori2.py", line 3, in &lt;module&gt; import numpy as np File "/home/tsoi/Documents/environments/testvenv/my_venv/lib/python3.6/site-packages/numpy/__init__.py", line 142, in &lt;module&gt; from . import add_newdocs File "/home/tsoi/Documents/environments/testvenv/my_venv/lib/python3.6/site-packages/numpy/add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "/home/tsoi/Documents/environments/testvenv/my_venv/lib/python3.6/site-packages/numpy/lib/__init__.py", line 8, in &lt;module&gt; from .type_check import * File "/home/tsoi/Documents/environments/testvenv/my_venv/lib/python3.6/site-packages/numpy/lib/type_check.py", line 11, in &lt;module&gt; import numpy.core.numeric as _nx File "/home/tsoi/Documents/environments/testvenv/my_venv/lib/python3.6/site-packages/numpy/core/__init__.py", line 38, in &lt;module&gt; from . import numeric File "/home/tsoi/Documents/environments/testvenv/my_venv/lib/python3.6/site-packages/numpy/core/numeric.py", line 43, in &lt;module&gt; import pickle File "/home/tsoi/Documents/environments/testvenv/Traffic-rec/pickle.py", line 1 from ~/Documents/environments/testvenv/my_venv/lib/python3.6/site-packages/numpy import numpy as np ^ SyntaxError: invalid syntax I have also tried import sys sys.path.append('~/Documents/environments/testvenv/my_venv/lib/python3.6/site-packages/numpy') when importing numpy but the same error occured, This hasn't happened before and it's been annoying for me. This is the part of my code that I think is relevant to this problem: from __future__ import print_function #from comet_ml import Experiment import numpy as np import tensorflow as tf import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPool…
has comment: http://stackoverflow.com/comment/92378078
linked to: http://stackoverflow.com/q/36250353
has comment: http://stackoverflow.com/comment/92388392
has comment: http://stackoverflow.com/comment/92378076
type: Question
score: 0
answer count: 1
tagged with: virtualenv
has title: SyntaxError: invalid syntax when importing numpy
favorite count: 0
tagged with: python
tagged with: module
duplicate of: http://stackoverflow.com/q/36250353
has answer: http://stackoverflow.com/a/52726463
type: UnansweredQuestion

http://stackoverflow.com/comment/92144268
type: AnswerComment
type: Comment
has text: I think I understand what you mean, Python will evaluate it but will not put that block in run time but as evaluation is done, function called two times right ?
comment on: http://stackoverflow.com/a/52604959
score: 0

http://stackoverflow.com/comment/92282935
comment on: http://stackoverflow.com/q/52676963
has text: Yup, just realized that now :p it was so simple, thanks!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92199961
comment on: http://stackoverflow.com/q/52633208
score: 0
has text: You want to look into something called [formsets](https://docs.djangoproject.com/en/2.1/topics/forms/formsets/), which is what Django provides for you to work with multiple forms on the same page, specifically with creating multiple instances of the same object type. Feel free to share some of your view/form initialization code, and we can provide more details to help you achieve your goal.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52668962
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52668208
answers question: http://stackoverflow.com/q/52668208
type: Answer
upvote count: 2
has body: Required link is hidden and also located inside an iframe. Try below to locate it: WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("tvPlayer_1")) try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "ytp-title-link"))) print(element.get_attribute('href')) finally: driver.quit()
has comment: http://stackoverflow.com/comment/92268714

http://stackoverflow.com/a/70162485
answers question: http://stackoverflow.com/q/52612393
downvote count: 0
score: 1
has body: i just made up some values for metric1 and metric2. but see code below. import pandas as pd import numpy as np df = pd.DataFrame([['A', '201809' ,234, 567], ['B', '201809' ,105, 640], ['C', '201808' ,250, 700], ['A', '201808' ,200, 267], ['B', '201809' ,57, 654], ['C', '201807' ,205, 620], ['A', '201807' ,234, 567], ['B', '201808' ,110, 640], ['C', '201808' ,275, 700], ['A', '201807' ,150, 267], ['B', '201807' ,57, 654], ['C', '201809' ,205, 620] ], columns=['dimension','month','metric1','metric2']) df2 = pd.melt(df, id_vars=['dimension', 'month'], value_vars=['metric1', 'metric2']) pd.pivot_table(df2, values=['value'], index=['dimension'], columns=['month', 'variable'], aggfunc=np.sum)
upvote count: 1
type: Answer

http://stackoverflow.com/comment/92278303
comment on: http://stackoverflow.com/a/52674332
type: AnswerComment
score: 0
has text: But still I think you are right. The file just doesn't exist. The error message indicates that quite clearly (assuming OP copy/pasted it exactly).
type: Comment

http://stackoverflow.com/q/52745431
tagged with: python
has body: Lets say i have the pandas dataframe below. How can i subtract one month from Var2 when Var0 is equal to b. I would like to do this conditionally, rather than creating a new data-set with just the var0 b values,subtracting and then re-merging. Var2 is in pandas datetime. Var0 Var1 Var2 x 76.27 2018-05 x 93.38 2018-06 a 73 2018-05 a 74.33 2018-05 b 184.08 2018-03 b 184.08 2018-02 c 67.26 2018-06 c 67.18 2018-07
type: AnsweredQuestion
has title: Conditional Subtract Dates
type: Question
possible better answer: http://stackoverflow.com/a/52745516
has answer: http://stackoverflow.com/a/52745499
has answer: http://stackoverflow.com/a/52745516
score: 0
answer count: 2
tagged with: pandas
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52745499

http://stackoverflow.com/comment/92247736
has text: My confusion was not so much about formatters and locators as the label's text property. I gather from your explanation that that property is completely dynamic and is never respected on its own, only used as a placeholder after each redraw. Will keep that in mind. Thanks.
comment on: http://stackoverflow.com/a/52656386
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92299087
comment on: http://stackoverflow.com/a/52685798
score: 0
type: AnswerComment
has text: Am getting the value as **/Date(1539205200000)/** from json
type: Comment

http://stackoverflow.com/comment/92271499
type: Comment
has text: @artomason Will do. Thank you guys for the help.
comment on: http://stackoverflow.com/a/52670782
score: 0
type: AnswerComment

http://stackoverflow.com/a/52667743
score: 0
answers question: http://stackoverflow.com/q/52667343
type: Answer
has body: You can inform that the answer is undefined when the divisor is 0, and you should use normal functions, not named lambdas in python. from pynverse import inversefunc from math import pi,sqrt def Z(x): # Can define these globally if necessary. R = 20 C = 5 * 10**-9 L = 5 * 10**-4 return sqrt(R**2 + (1/(2*pi*C*x) - 2*pi*L*x)**2)) try: inversefunc(Z, y_values=0) except ZeroDivisionError: print("answer is undefined")

http://stackoverflow.com/a/52664139
has body: The recursive call in the login function starts reading the file from the beginning because the file is opened again. You need to read the entire file, searching for a match, and then make the final decision at the end of the loop. You can only return early if the function finds the requested user name.
downvote count: 0
answers question: http://stackoverflow.com/q/52664071
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/92178865
type: Comment
has text: Yes I know. In my example x0, y0 etc.. are real values, given by the mouse event, which work if I draw the canvas with `self.canvas.draw()`, but it dosen't work if I use `self.canvas.drawRectangle([x0, y0, x1, y1])`. Did you test it?
comment on: http://stackoverflow.com/a/52608704
type: AnswerComment
score: 0

http://stackoverflow.com/q/52596553
tagged with: python
accepted answer: http://stackoverflow.com/a/52596869
type: AnsweredQuestion
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/92128003
type: Question
has body: I am attempting to understand some of the example code from machinelearningmastery.com but the slice notation is throwing me off... For starters with my code I am attempting to make a simple regression type ML algorithm with some data from a CSV file: import pandas as pd McheLrn = pd.read_csv('C:/Users/data.csv', index_col='Date', parse_dates=True) McheLrn['month'] = McheLrn.index.month McheLrn['date'] = McheLrn.index.strftime('%d') McheLrn['hour'] = McheLrn.index.strftime('%H') McheLrn['Day_of_week'] = McheLrn.index.dayofweek McheLrn.head() This will output: OSAT kWh month date hour Day_of_week Date 2013-01-01 06:00:00 10.4 16.55 1 01 06 1 2013-01-01 06:15:00 10.4 16.55 1 01 06 1 2013-01-01 06:30:00 10.4 16.05 1 01 06 1 2013-01-01 06:35:00 10.4 16.05 1 01 06 1 2013-01-01 06:45:00 10.4 17.20 1 01 06 1 Not sure if I am using the correct terminology, but the dependent variable is kWh (Y variable) and all other are independent variables for my X variables... With the code below what is throwing me off is the slice notation X = array[:,0:2] Y = array[:,2] And I am not sure if I have my X &amp; Y variables correctly selected. # Decision Tree Regression import pandas from sklearn import model_selection from sklearn.tree import DecisionTreeRegressor dataframe = McheLrn array = dataframe.values X = array[:,0:2] Y = array[:,2] seed = 7 kfold = model_selection.KFold(n_splits=90, random_state=seed) model = DecisionTreeRegressor() scoring = 'neg_mean_squared_error' results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring) print(results.mean())
has comment: http://stackoverflow.com/comment/92128124
has comment: http://stackoverflow.com/comment/92127887
tagged with: data-science
has answer: http://stackoverflow.com/a/52596869
tagged with: pandas
has title: Python slice notation
has comment: http://stackoverflow.com/comment/92128031
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92128029
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92127981
has comment: http://stackoverflow.com/comment/92128268

http://stackoverflow.com/a/52643916
type: Answer
has comment: http://stackoverflow.com/comment/92225836
upvote count: 1
answers question: http://stackoverflow.com/q/52643774
downvote count: 0
score: 1
has body: import pandas as pd df = pd.DataFrame({'col1': ['abc', 'def', 'tre'], 'col2': ['foo', 'bar', 'stuff']}) d = {'col1': [0, 2], 'col2': [1]} x = 0 [f"{df.loc[x, 'col1']} is great" for ci, vali in d.items() for indi in vali] which gives you: ['abc is great', 'abc is great', 'abc is great'] is this what you're looking for? Also you can do loop thru x range [f"{df.loc[i, 'col1']} is great" for ci, vali in d.items() for indi in vali for i in range(2)] #output ['abc is great', 'def is great', 'abc is great', 'def is great', 'abc is great', 'def is great']

http://stackoverflow.com/q/52745085
has comment: http://stackoverflow.com/comment/92415120
tagged with: collatz
score: 0
has comment: http://stackoverflow.com/comment/92415374
tagged with: dynamic-programming
answer count: 1
has title: Using recursion and memoization with collatz
has answer: http://stackoverflow.com/a/52746281
has comment: http://stackoverflow.com/comment/92414879
tagged with: memoization
has body: Unchecked Theorem (Collatz): all the numbers to which this sequence of functions is applied, end in 1.Of the numbers between 1 and 1000000, to which corresponds the longest sequence? How can I use memoization so the operation doesn't take so long and know the largest sequence from 1-1,000,000 ? def Collatz(n, arr): arr.append(n) if n == 1: return arr elif n % 2 == 0: return Collatz(n / 2, arr) elif n % 2 == 1: return Collatz((3 * n) + 1, arr)
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52746281
type: Question
tagged with: recursion

keras
tags question: http://stackoverflow.com/q/52640036
tags question: http://stackoverflow.com/q/52695534
tags question: http://stackoverflow.com/q/52649850
tags question: http://stackoverflow.com/q/52703096
tags question: http://stackoverflow.com/q/52636328
tags question: http://stackoverflow.com/q/52736517
tags question: http://stackoverflow.com/q/52627739
tags question: http://stackoverflow.com/q/52595477
tags question: http://stackoverflow.com/q/52636127
tags question: http://stackoverflow.com/q/52671481
tags question: http://stackoverflow.com/q/52742283
tags question: http://stackoverflow.com/q/52619535
tags question: http://stackoverflow.com/q/52656293
tags question: http://stackoverflow.com/q/52695421
tags question: http://stackoverflow.com/q/52723253
tags question: http://stackoverflow.com/q/52735895
tags question: http://stackoverflow.com/q/52681601
tags question: http://stackoverflow.com/q/52620964
tags question: http://stackoverflow.com/q/52621995
tags question: http://stackoverflow.com/q/52733216
tags question: http://stackoverflow.com/q/52702431
tags question: http://stackoverflow.com/q/52712301
tags question: http://stackoverflow.com/q/52656737
tags question: http://stackoverflow.com/q/52591862
tags question: http://stackoverflow.com/q/52663701
tags question: http://stackoverflow.com/q/52713614
tags question: http://stackoverflow.com/q/52710671
tags question: http://stackoverflow.com/q/52609798
tags question: http://stackoverflow.com/q/52730778
tags question: http://stackoverflow.com/q/52697996
tags question: http://stackoverflow.com/q/52613977
tags question: http://stackoverflow.com/q/52653497
tags question: http://stackoverflow.com/q/52678048
tags question: http://stackoverflow.com/q/52723753
tags question: http://stackoverflow.com/q/52647743
tags question: http://stackoverflow.com/q/52740744
tags question: http://stackoverflow.com/q/52745754
tags question: http://stackoverflow.com/q/52641501
tags question: http://stackoverflow.com/q/52679712
tags question: http://stackoverflow.com/q/52684581
tags question: http://stackoverflow.com/q/52594650
tags question: http://stackoverflow.com/q/52657421
tags question: http://stackoverflow.com/q/52685774
tags question: http://stackoverflow.com/q/52737412
tags question: http://stackoverflow.com/q/52691566
tags question: http://stackoverflow.com/q/52673987
tags question: http://stackoverflow.com/q/52708821
tags question: http://stackoverflow.com/q/52691569
tags question: http://stackoverflow.com/q/52618700
tags question: http://stackoverflow.com/q/52616287
tags question: http://stackoverflow.com/q/52647115
tags question: http://stackoverflow.com/q/52615715
tags question: http://stackoverflow.com/q/52653320
tags question: http://stackoverflow.com/q/52724006
tags question: http://stackoverflow.com/q/52625358
tags question: http://stackoverflow.com/q/52712782
tags question: http://stackoverflow.com/q/52733761
tags question: http://stackoverflow.com/q/52637493
tags question: http://stackoverflow.com/q/52734928
tags question: http://stackoverflow.com/q/52708764
tags question: http://stackoverflow.com/q/52598959
tags question: http://stackoverflow.com/q/52718451
tags question: http://stackoverflow.com/q/52664110
tags question: http://stackoverflow.com/q/52642756
tags question: http://stackoverflow.com/q/52627196
tags question: http://stackoverflow.com/q/52678215
tags question: http://stackoverflow.com/q/52701315
tags question: http://stackoverflow.com/q/52698468
tags question: http://stackoverflow.com/q/52696039
tags question: http://stackoverflow.com/q/52734659
tags question: http://stackoverflow.com/q/52670060
tags question: http://stackoverflow.com/q/52621257
tags question: http://stackoverflow.com/q/52634226
tags question: http://stackoverflow.com/q/52624870
tags question: http://stackoverflow.com/q/52732145
tags question: http://stackoverflow.com/q/52721616
tags question: http://stackoverflow.com/q/52624457
tags question: http://stackoverflow.com/q/52619166
tags question: http://stackoverflow.com/q/52684831
tags question: http://stackoverflow.com/q/52606828

http://stackoverflow.com/comment/92359469
comment on: http://stackoverflow.com/q/52716888
score: 0
type: Comment
type: QuestionComment
has text: Also, I think you want to use `for j in lst:` rather than `for j in range(len(lst)):` as at the moment, the values of lst aren't being accessed. You're iterating through from 0,1,2,... up to the length of the list.

http://stackoverflow.com/comment/92253314
has text: Please include the code you run to produce this error.
score: 0
comment on: http://stackoverflow.com/q/52661535
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92349634
type: Comment
score: 0
has text: Do you have the ability to define the default timeout in your wrapper? If so, you could call `connect(timeout=timeout or DEFAULT)`.
type: QuestionComment
comment on: http://stackoverflow.com/q/52711707

http://stackoverflow.com/comment/92286334
score: 0
type: QuestionComment
has text: @fred.schwartz, updated the answer, take a look
comment on: http://stackoverflow.com/q/52678422
type: Comment

http://stackoverflow.com/q/52703254
type: UnansweredQuestion
tagged with: python
tagged with: python-ldap
has title: How can I best install a Python package (python-ldap3 2.5.1) without easy_install (followup to an older thread)?
has comment: http://stackoverflow.com/comment/92340764
type: Question
has body: I am trying to figure how to install a Python package (ldap3) using a .egg file (fyi, the version of python-ldap3 we need does not have a .whl file) on a system that does not have easy_install available. I found from an earlier thread (How can I install a .egg Python package on Windows (attempt using easy_install not working)) that I might be able to: Untar the python-ldap3 tar.gz Change dir to the untarred dir run "python setup.py install" So I tried the above, and it does seem to deploy/install the python-ldap3, but the installation hangs because it looks like it is trying to download something: # python setup.py install running install running bdist_egg running egg_info writing requirements to ldap3.egg-info/requires.txt writing ldap3.egg-info/PKG-INFO writing top-level names to ldap3.egg-info/top_level.txt writing dependency_links to ldap3.egg-info/dependency_links.txt reading manifest file 'ldap3.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'ldap3.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running install_lib running build_py creating build creating build/lib creating build/lib/ldap3 copying ./ldap3/__init__.py -&gt; build/lib/ldap3 copying ./ldap3/version.py -&gt; build/lib/ldap3 creating build/lib/ldap3/abstract copying ./ldap3/abstract/cursor.py -&gt; build/lib/ldap3/abstract . . . Installed /usr/lib/python2.6/site-packages/ldap3-2.5.1-py2.6.egg Processing dependencies for ldap3==2.5.1 Searching for pyasn1&gt;=0.1.8 Reading https://pypi.python.org/simple/pyasn1/ The "python setup.py install" hangs at that last line above ("Reading...."), but if I kill the process then check the python-ldap3 version, it looks like it installed all right: # pip freeze | grep ldap3 ldap3==2.5.1 Also, FYI, our Python version is 2.6, and the pyasn1 is: #pip freeze | grep pyasn1 pyasn1==0.4.3 I am not that familiar with Python and Python packaging, so I was wondering: Is it all right to do the ldap3 2.5.1 in…
has comment: http://stackoverflow.com/comment/92406066
score: 0
has comment: http://stackoverflow.com/comment/92338924
has comment: http://stackoverflow.com/comment/92343721
linked to: http://stackoverflow.com/q/18558733
answer count: 0

http://stackoverflow.com/q/52693083
upvote count: 0
answer count: 1
has title: Kivy: Set image background and stretch through python
has answer: http://stackoverflow.com/a/52729115
tagged with: python
tagged with: kivy
favorite count: 0
accepted answer: http://stackoverflow.com/a/52729115
has body: I've searched everywhere on how to simply set the background of a Kivy app to an image, stretched to fit the screen, using python - only caveat is that I can't easily use a kv file to do so without reworking the majority of the app. Anything I've found pertaining to this just results in no change in background or countless errors. Is there any way to easily do this?
downvote count: 1
type: AnsweredQuestion
score: -1
type: Question

http://stackoverflow.com/comment/92293568
has text: fuglede, thank you for your help! i guess what i intended to say, but didn't was- i would like the results for north and south to be separate where we are able to find the largest drivers that explain the net movement for south and the largest drivers that explain the net movement for north
comment on: http://stackoverflow.com/a/52682719
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92361933
type: QuestionComment
comment on: http://stackoverflow.com/q/52699212
has text: @glenfant: But do I then not run into the same issue as with the cookies? I will have to make `client` available in several functions, so I somehow have to make it globally available (but it also has to be threadsafe). How I would I do this?
score: 0
type: Comment

http://stackoverflow.com/comment/92355375
score: 0
has text: Hmmm, thats weird, I get it on Python 3.7, Python 3.6, and Python 3.4 (Well python 3.4 is a RuntimeError). I am running macOS.
comment on: http://stackoverflow.com/q/52714532
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92348349
comment on: http://stackoverflow.com/q/52706853
has text: @kosist I would want to search for 'Rated: ' and append the results into a list. I would then have "ratings = ['Rating: K+', 'Rating: T']". I would then search for 'Words: ' and would then have "words = ['Words: 2,835', 'Words: 32']. etc, etc. I would append the results onto the appropriate list when applicable and append a blank space when no value is found, like how the second list doesn't have an update date. It would come out as "updates = ['Updated: 1/5/2004', ' ']", since there was no match for 'Updated: ' in the second list. That way there are just blank excel cells, no mismatched data.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92197263
type: QuestionComment
has text: @hpaulj I want to convert it to a Pandas dataframe
type: Comment
comment on: http://stackoverflow.com/q/52630865
score: 0

http://stackoverflow.com/q/52596040
has answer: http://stackoverflow.com/a/52596111
score: 0
answer count: 2
tagged with: string
has comment: http://stackoverflow.com/comment/92126769
type: UnansweredQuestion
tagged with: python
has body: I was wondering if there's a way in python that I can search for multiple strings in a stream at once without jamming them all into one line. Can I put them in some sort of list and substitute that for the long line of 'or's? if re.search("japan" or "japanese" or "nihon" or "nippon", str(comment.body).lower(), re.IGNORECASE): return True This is what I have right now, I just to make it look neater instead of searching for every variation of japan I can think of. Thanks for any help!
tagged with: bots
has answer: http://stackoverflow.com/a/52596141
type: Question
has title: Searching for multiple strings in a stream at once without doing "text1" or "text2" or "text3" or

http://stackoverflow.com/a/52627285
has comment: http://stackoverflow.com/comment/92188545
accepted answer of: http://stackoverflow.com/q/52626031
type: Answer
answers question: http://stackoverflow.com/q/52626031
score: 2
downvote count: 0
has body: That's the kind of problem the special method __new__ is supposed to solve. Unfortunately, NamedTuple prevents its overwriting inside its definition. But you can overwrite it outside the definition with a decorator: def set_default(attr, func): def set_new(typ): old = typ.__new__ sig = inspect.signature(old) def _new(cls, *args, **kwargs): bound = sig.bind_partial(cls, *args, **kwargs).arguments if not attr in bound: bound[attr] = func(*args, **kwargs) # print(bound) # uncomment for debug traces return old(**bound) typ.__new__ = _new return typ return set_new @set_default('id', lambda phrase, typ: f'{phrase}_{typ.name.lower()}') class WordItem(NamedTuple): phrase: str type: WORD_TYPE id: str = None You can then use WordItem: &gt;&gt;&gt; w = WordItem('a', WORD_TYPE.APPROVED) &gt;&gt;&gt; w WordItem(phrase='a', type=&lt;WORD_TYPE.APPROVED: 'approved'&gt;, id='a_approved') &gt;&gt;&gt; w2 = WordItem('b', WORD_TYPE.APPROVED, 'c') &gt;&gt;&gt; w2 WordItem(phrase='b', type=&lt;WORD_TYPE.APPROVED: 'approved'&gt;, id='c') But: NamedTuple prevents overwriting of __new__ for a reason this tries to implement a feature that is explicitely prohibited If you can, you should avoid this trick. It works fine in my 3.6 version, but it could break in a future version of NamedTuple, or be superseded by a native implementation...
upvote count: 2
has comment: http://stackoverflow.com/comment/92188386
type: AcceptedAnswer

http://stackoverflow.com/q/52715059
has answer: http://stackoverflow.com/a/52715111
tagged with: python
tagged with: cellular-automata
upvote count: 0
has body: I'm attempting to create a one-dimensional cellular automata. For a given rule (between 1 and 255), the number is converted into the corresponding 8-digit binary number and paired to all 8 possible combinations of 0's and 1's. The code seems to work fine outside of putting it in a function. However, when I run the second half, it gives me the AttributeError: 'list' object has no attribute 'shape'. I defined 'values' as a Numpy array and if I run the code without the stepping portion, it stays as an array. I am unsure what is going on. Any guidance would be appreciated! def cellular_step(value, rule=110): blist = np.unpackbits(np.uint8(rule)) truple = [(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)] lookup_dict = {} for indx,lmr in enumerate(truple): lookup_dict[lmr] = blist[indx] next_step = np.array([],dtype=np.int8) for i in range(value.shape[0]): indices = range(i-1,i+2) neighbourhood = value.take(indices,mode='wrap') b = tuple(neighbourhood) a = lookup_dict.get(b) next_step = np.append(next_step,a) return[next_step] value = np.zeros(5, dtype=np.int8) value[ len(value)//2 ] = 1 nsteps = 10 grid = np.ndarray( [nsteps,len(value)], dtype=np.int8) for n in range(nsteps): value = cellular_step(value,rule=30) grid[n,:] = value plt.imshow(grid)
type: UnansweredQuestion
has title: Numpy Array object converting to List object in function?
type: Question
has answer: http://stackoverflow.com/a/52715316
score: -1
answer count: 2
has comment: http://stackoverflow.com/comment/94899617
tagged with: arrays
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/52938715
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52735842
has body: The shell doesn't know about the Python variables, as it's a completely different system. So you can't use the shell's variable substitution mechanism ($date_ID). Instead, you'll have to pass them as a Python string: os.system("import_S1_TOPS_modified %s %s vv 1" % (date_ID, fullpath)) Note that this code has a serious problem: what if someone gives ; rm -rf /; as filename? the command will now look like: import_S1_TOPS_modified 20181021; rm -rf /; vv 1 Which will delete everything. This is why it is a better idea to use subprocess, which will not use the shell at all, and isn't vulnerable to this sort of problem: subprocess.call(['import_S1_TOPS_modified', date_ID, fullpath, 'vv', '1']) If you must use the shell, then use shlex.quote() and add shell=True: subprocess.call("import_S1_TOPS_modified %s %s vv 1" % ( shlex.quote(date_ID), shlex.quote(fullpath)), shell=True)
type: Answer
downvote count: 0

http://stackoverflow.com/comment/92379963
score: 1
has text: Since you are using line number information to print what you want, it makes sense to split along line breaks. I don't think it can get simpler than this. Any other method and you are working at character level.
comment on: http://stackoverflow.com/q/52727251
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92246020
comment on: http://stackoverflow.com/a/52657655
type: Comment
score: 1
type: AnswerComment
has text: Which makes it invalid no? You try and rename a file `/.txt` and itll tell you "A file name cannot contain any of the following characters:". I consider that to be invalid.

http://stackoverflow.com/a/52682338
has comment: http://stackoverflow.com/comment/92294609
has comment: http://stackoverflow.com/comment/92293968
has comment: http://stackoverflow.com/comment/92294695
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92294384
accepted answer of: http://stackoverflow.com/q/52682332
upvote count: 5
has comment: http://stackoverflow.com/comment/92294209
has body: Objects have types. Statements do not. pass is a statement, and does not have a type. (Also, None is not a type.)
type: Answer
answers question: http://stackoverflow.com/q/52682332
downvote count: 0
has comment: http://stackoverflow.com/comment/92294748
score: 5
has comment: http://stackoverflow.com/comment/92294664
has comment: http://stackoverflow.com/comment/92294349

http://stackoverflow.com/comment/92361625
has text: [Those are the options](https://i.sstatic.net/sCmYT.png) I see in inkscape. Which one of those are you refering to?
comment on: http://stackoverflow.com/q/52718028
score: 0
type: Comment
type: QuestionComment

dialog
tag name: dialog
tags question: http://stackoverflow.com/q/52703513
type: Tag
tags question: http://stackoverflow.com/q/52696176

http://stackoverflow.com/a/52608473
has comment: http://stackoverflow.com/comment/92157740
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/92157789
answers question: http://stackoverflow.com/q/52608218
has body: Do not use tbody tag in your XPath. Note that developer might skip this tag, so it will be added automatically by browser while page rendering. Simply try print(tree.xpath('/html/body/table//tr[2]//text()')) or print([i for i in tree.xpath('/html/body/table//tr[2]//text()') if i.strip()]) to avoid printing new line characters
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52608218
downvote count: 0

http://stackoverflow.com/a/52723228
has body: Here is an example implementation of a solution in GCP Dataflow that corresponds to the first suggestion in the accepted answer. You'll need to implement the json correction in function json_processor. You can run this code in a Datalab notebook. # Datalab might need an older version of pip # !pip install pip==9.0.3 import apache_beam as beam from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import StandardOptions project_id = 'my-project' bigquery_dataset_name = 'testdataset' # needs to exist table_name = 'testtable' bucket_name = 'my-bucket' json_file_gcs_path = 'gs://path/to/my/file.json' schema = "name:STRING,zipcode:STRING" def json_processor(row): import json d = json.loads(row) return {'name': d['name'], 'zipcode': d['zipcode']} options = beam.options.pipeline_options.PipelineOptions() google_cloud_options = options.view_as(GoogleCloudOptions) google_cloud_options.project = project_id google_cloud_options.job_name = "myjob" google_cloud_options.staging_location = 'gs://{}/binaries'.format(bucket_name) google_cloud_options.temp_location = 'gs://{}/temp'.format(bucket_name) options.view_as(StandardOptions).runner = 'DataflowRunner' google_cloud_options.region = "europe-west1" p = beam.Pipeline(options=options) (p | "read_from_gcs" &gt;&gt; beam.io.ReadFromText(json_file_gcs_path) | "json_processor" &gt;&gt; beam.Map(json_processor) | "write_to_bq" &gt;&gt; beam.io.Write(beam.io.gcp.bigquery.BigQuerySink(table=table_name, dataset=bigquery_dataset_name, project=project_id, schema=schema, create_disposition='CREATE_IF_NEEDED', write_disposition='WRITE_EMPTY')) ) p.run()
answers question: http://stackoverflow.com/q/52718752
downvote count: 0
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/92297262
type: Comment
has text: Hey pygo this is not the case.
type: AnswerComment
comment on: http://stackoverflow.com/a/52677839
score: 0

http://stackoverflow.com/a/52630563
answers question: http://stackoverflow.com/q/52630289
score: 1
upvote count: 1
has body: First, I think the indent is wrong but of course, it is not some big deals. And then you must know some fact that NaN at pandas/numpy is not some simple empty objects. If you using following code like bool(np.nan), it will output True which it exactly you used to remove empty atX=[(k,c) for k in dataframe.loc[:,c] if k]. If you do want to remove empty or determine nan, please use numpy.isnan or pd.isna. Or you just use pandas.dropna simply. The second question I think you might misunderstand the meaning of nonzero, after pd.isnull(NDF).any(1) you got a pure pd.Series which has not the index. So you just get some index constructed by nature number. More simply, you should use NDF.iloc[ans,:] because nonzero return the index of Series instead of index of dataframe.
accepted answer of: http://stackoverflow.com/q/52630289
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52716534
answers question: http://stackoverflow.com/q/52716336
downvote count: 0
has body: #to create a list with ids that are in A and found in B (unique) resultlist=list(set(A)&amp;set(B)) print(list(set(A)&amp;set(B))) #to create a list of ids that are in A and have no corresponding in B (unique) print(list(set(A)-set(B))) #the numbers in B, that don't have a corespondent in A print(list(set(B)-set(A)))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52716336
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/92157183
comment on: http://stackoverflow.com/q/52610380
score: 0
type: Comment
type: QuestionComment
has text: @KirollosMorkos my problem is not how to upload file but to do this in the same page without creating another html

http://stackoverflow.com/comment/92468193
has text: @akhilpathirippilly python doesn't have typed arguments, it is a dynamic language. There is no argument type. Now, Python 3.6+ introduced type-hinting. You can use `mypy` as a third-party static type-checker to enforce this before runtime, but Python itself doesn't enforce this, and if you want to, you have to check if the argument is a list yourself.
score: 0
comment on: http://stackoverflow.com/a/52747535
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52649850
favorite count: 0
has comment: http://stackoverflow.com/comment/96585908
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
has title: How to pass weights and mask to weighted_masked_objective in keras?
tagged with: loss-function
type: Question
has body: I am wondering how can I compute a pixel-wise weighted loss for image segmentation. For each image I have a ground-truth mask and a weighted mask to give more importance to certain pixels in an image. Note that, my weighted mask is unique for each image so I can not pass this mask in a user defined loss function as an input. I can see a function "weighted_masked_objective" in keras/engine/training_utils.py which can handle a mask but I din not find any way to pass weighted mask to that function. Is there any way to pass weighted mask to a loss function as part of standard input parameters e,g. y_true, y_pred?
downvote count: 0
score: 1
tagged with: keras
tagged with: python

http://stackoverflow.com/a/52665557
upvote count: 1
answers question: http://stackoverflow.com/q/52665492
downvote count: 0
score: 1
has body: A simple table merge will do: pd.merge(df_A, df_B, on='latitude', how='inner', suffixes=('_A', '_B'))
type: Answer

http://stackoverflow.com/comment/92199593
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52632884
has text: @Ben you can ask user for city_name and save it to `city_name` variable or you can display list of cities like 1) X 2) Y 3) Z .. and ask user to enter corresponding number. you just need to eventually replace `'dublin'` with the desired city_name `weather.lookup_by_location('dublin')`

http://stackoverflow.com/a/52668528
score: 0
has comment: http://stackoverflow.com/comment/92270537
type: Answer
has body: When I started using Pandas, I found building and chaining small blocks very useful and readable: E.g. #1. Select Category A or B: Pandas uses | for or and &amp; for and. categoryA = df['Category'] == 'A' categoryB = df['Category'] == 'B' catAorB = categoryA | categoryB df[catAorB] #2. All products where Sub_Category = ['B1'] and Color = ['Red', 'Black'] (a B1 that is either Red or Black). subCatB1 = df['Sub_Category'] == 'B1' colorRed = df['Color'] == 'Red' colorBlack = df['Color'] == 'BLACK' colRedorBlack = colorRed | colorBlack subCatB1andRB = subCatB1 &amp; colRedorBlack df[subCatB1andRB]
has comment: http://stackoverflow.com/comment/92270231
has comment: http://stackoverflow.com/comment/92268936
answers question: http://stackoverflow.com/q/52666914

http://stackoverflow.com/comment/92324429
comment on: http://stackoverflow.com/q/52698854
has text: Remove the `*.pyc` files.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/52602043
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52601848
type: Answer
downvote count: 0
has body: You can check for convergence by looking at the difference between the current value of z and its previous value. This difference is just the value you add at each iteration, that is, fz / dfz. I guess you need to stop looping when the difference is less than 0.25, then the code is as follows: def which_root_z4(z , n): # function which takes 2 arguments; z and n fz = z ** 4 - 1 # defining f(z) dfz = 4 * z ** 3 # defining the first derivative of f(z) while n &gt; 0: # this block will continue looping until n = 0 z = z - fz / dfz #T he Newton-Raphson formula if abs(fz / dfz)&lt;0.25: #This ends the loop when z's converged break return which_root_z4(z, n-1) # after each iteration, the function begins again with the new value of z and n-1 return z You can also print the value of fz/dfz to check if it's indeed reaching convergence
score: 1
accepted answer of: http://stackoverflow.com/q/52601848
upvote count: 1

http://stackoverflow.com/comment/92124287
has text: @Mike'Pomax'Kamermans Thanks for your comment. Basically, I am trying to streamline my workflow so that I can get selected text without using the clipboard. This isn't necessary, but it would save me some key strokes, so I just thought I would ask if anyone had any suggestions. You can see that reference link I left in my question for a similar question using Autohotkey. Anyway, I guess there is no easy way.
score: 0
comment on: http://stackoverflow.com/q/52593557
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92282636
has text: Added that, too.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52676639
type: AnswerComment

http://stackoverflow.com/q/52609585
favorite count: 0
tagged with: series
has answer: http://stackoverflow.com/a/52610163
has title: how to replace string at specific index in pandas dataframe
type: UnansweredQuestion
tagged with: datetime
tagged with: python
upvote count: 3
has body: I have following dataframe in pandas code bucket 0 08:30:00-9:00:00 1 10:00:00-11:00:00 2 12:00:00-13:00:00 I want to replace 7th character 0 with 1, my desired dataframe is code bucket 0 08:30:01-9:00:00 1 10:00:01-11:00:00 2 12:00:01-13:00:00 How to do it in pandas?
type: Question
score: 3
answer count: 2
has answer: http://stackoverflow.com/a/52609649
tagged with: pandas
downvote count: 0

http://stackoverflow.com/q/52740868
tagged with: hiveql
tagged with: python
score: 0
answer count: 1
tagged with: hive
tagged with: apache-spark-sql
tagged with: pyspark
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52744462
has title: Insert values to Hive table in Pyspark of Row type
has body: I'm new to working with Pyspark. I have a function which calculates the max of a query and inserts the max value which is of the type Row, along with two other values date and product name. def findCount(query, prod_date, prod_name): count = query.agg({"count": "max"}).collect()[0] (returns Row(max(count)=Decimal('1.0000000000'))) reopen = hc.sql('insert into details values(row_date, row_name, count)') print(=count) This is the code which calls the function: for row in aggs_list: prod_date= row.date prod_name = row.product_name query = prod_load.filter((col("date") == prod_date) &amp; (col("prod_name") == row_name)) findCount(query, prod_date, prod_name) This is something I've tried and is not working. Is there a more efficient way to do this?
type: Question

http://stackoverflow.com/q/52734619
has comment: http://stackoverflow.com/comment/96279479
has title: How to verify the integrity of a virtualenv
has comment: http://stackoverflow.com/comment/92400623
type: UnansweredQuestion
upvote count: 4
has comment: http://stackoverflow.com/comment/92396750
downvote count: 0
tagged with: virtualenv
favorite count: 0
has body: I am looking for a way to verify the integrity of a virtualenv at runtime. A bit more explicitly put; We are deploying a python project to a production server. Under the deploy a virtualenv is created and packages are installed using pip and setuptools (since our own package is not distributed). So far everything is in order. This is a medical grade application so at every run we need to verify that the virtualenv has not been altered. Checking versions against pip list (or pipfile.lock if we switch to pipenv) is not enough (as I understand things). We also need to verify that nothing has been altered within the virtualenv (e.g. changes in the code under virtualenv/lib/python/site-packages). Is there a pythonic way to do this?
type: Question
has answer: http://stackoverflow.com/a/52735936
has comment: http://stackoverflow.com/comment/92396802
tagged with: python
answer count: 1
score: 4

http://stackoverflow.com/q/52659643
downvote count: 1
tagged with: textselection
has comment: http://stackoverflow.com/comment/92253957
has comment: http://stackoverflow.com/comment/92258009
score: 3
has comment: http://stackoverflow.com/comment/92322462
has comment: http://stackoverflow.com/comment/92251290
type: Question
upvote count: 4
answer count: 1
has title: Select an element (text) using Python selenium
has comment: http://stackoverflow.com/comment/92327605
has body: In one of my internal web applications, we have to select text in a webpage and click on the selection. then a popup opens up with more options. This is a repetitive task for me and I want to automate it but selecting a web element as we do manually is not working fine for me. Since I cannot share the web app, I have taken a webpage accessible to all and tried to recreate the problem of selection. I am trying to simulate manual selection using mouse click at the top left of the element, then pressing Shift, then again click at end of the element. It's not working. What is wrong with the code? Expected selection is attached as a picture: Next is my code: import selenium import time from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys print("program has started") # Customary code starts myDriver=selenium.webdriver.Chrome("D:\\Software\\ChromeDriver\\chromedriver.exe") myDriver.set_page_load_timeout(60) myDriver.maximize_window() myDriver.implicitly_wait(30) # Customary code ends # opening website myDriver.get("https://en.wikipedia.org/wiki/Animal") time.sleep(4) actions = ActionChains(myDriver) element=myDriver.find_element_by_xpath("//*[@id='mw-content-text']/div/p[2]") actions.move_to_element(element) myDriver.switch_to_active_element() time.sleep(5) actions.move_by_offset(-(element.size["width"])/2, -(element.size["height"])/2) actions.click() ActionChains(myDriver).key_down(Keys.SHIFT) actions.move_by_offset((element.size["width"]),(element.size["height"])) actions.click() # actions.context_click() actions.perform() # print(element.size["width"]) # print(element.size["height"]) # print(element.location["x"]) # print(element.location["y"]) # print(element.location) print("end of action") print("Sucessfully came to the end") #myDriver.quit()
has comment: http://stackoverflow.com/comment/92256820
has comment: http://stackoverflow.com/comment/92323006
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/66687013
type: UnansweredQuestion
tagged with: selenium

tuples
tags question: http://stackoverflow.com/q/52704962
tags question: http://stackoverflow.com/q/52633763
tags question: http://stackoverflow.com/q/52595944
tags question: http://stackoverflow.com/q/52644521
tags question: http://stackoverflow.com/q/52735310
tags question: http://stackoverflow.com/q/52617096
tags question: http://stackoverflow.com/q/52742767
tags question: http://stackoverflow.com/q/52745773
tags question: http://stackoverflow.com/q/52613320
tags question: http://stackoverflow.com/q/52728944
tags question: http://stackoverflow.com/q/52729806
tags question: http://stackoverflow.com/q/52617670
tags question: http://stackoverflow.com/q/52710734
tags question: http://stackoverflow.com/q/52737189
tags question: http://stackoverflow.com/q/52699803
tags question: http://stackoverflow.com/q/52662191
tag name: tuples
tags question: http://stackoverflow.com/q/52715130
tags question: http://stackoverflow.com/q/52633279
tags question: http://stackoverflow.com/q/52635163
tags question: http://stackoverflow.com/q/52612883
tags question: http://stackoverflow.com/q/52593764
tags question: http://stackoverflow.com/q/52713859
tags question: http://stackoverflow.com/q/52675339
type: Tag
tags question: http://stackoverflow.com/q/52670591
tags question: http://stackoverflow.com/q/52690406

http://stackoverflow.com/q/52739605
has body: I have 3 pandas data frames, each containing 1 column. df1 = pd.DataFrame({'col1':[111, 222, 333, 444, 555]}) df2 = pd.DataFrame({'col2':[222, 333, 555]}) df3 = pd.DataFrame({'col3':[111, 222, 333, 666]}) I know how to concatenate them along columns: pd.concat([df1, df2, df3], axis=1) col1 col2 col3 111 222 111 222 333 222 333 555 333 444 NaN 666 555 NaN NaN What I want is that, the first row of all columns must be 111, if 111 is not available, it will be NaN, and this applies to the subsequent rows. I would like to sort numbers so that the final output is like this: col1 col2 col3 111 NaN 111 222 222 222 333 333 333 444 NaN NaN 555 555 NaN NaN NaN 666 Is this possible in pandas?
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52739678
has answer: http://stackoverflow.com/a/52739712
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/52739712
favorite count: 0
accepted answer: http://stackoverflow.com/a/52739678
upvote count: 1
type: AnsweredQuestion
score: 1
has title: Arrange row values across multiple columns in pandas

http://stackoverflow.com/comment/128271612
has text: No sir, my file name is `my.py`.
comment on: http://stackoverflow.com/a/52681202
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52714328
tagged with: bokeh
type: Question
has title: Show image of wordlcoud in bokeh
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/56768646
has body: Suppose I have a string for which I want to make a word cloud, like so: from wordcloud import WordCloud import matplotlib.pyplot as plt teststring = 'hi this is a test test test test test string for a word cloud' wordcloud = WordCloud(width=1000, height=1000, margin=0, background_color='white', collocations=False).generate(teststring) plt.imshow(wordcloud) Furthemore I have made a bokeh Tabs object with a few tabs from bokeh.plotting import figure, output_file, show from bokeh.models.widgets import Panel, Tabs output_file('stackoverflow.html') p1 = figure() p1.line(x=range(5), y=range(5)) tab1 = Panel(child=p1, title="Line plot") tabs = Tabs(tabs=[tab1]) show(tabs) How can I add the figure of the wordcloud to a tab2, to show in the panel? I've looked at many links (such as), but couldn't get it to work. The closes I found was here: How do I work with images in Bokeh (Python), but for this to work, it seems I have to save the wordcloud intermediately (in fact I have ~25 of them). Is that really necessary, or can I also immediately show the wordcloud in bokeh? Thanks in advance!
linked to: http://stackoverflow.com/q/34646270
tagged with: python
favorite count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/71953832

http://stackoverflow.com/comment/92233932
type: QuestionComment
comment on: http://stackoverflow.com/q/52651074
has text: Python is not drag and drop as far as I know...
score: 0
type: Comment

http://stackoverflow.com/comment/92410365
score: 0
comment on: http://stackoverflow.com/a/52742526
type: AnswerComment
has text: thanks so much for the quick response...I made that change but still only getting data for the Feminine Hygeine category and the Price data fields are all blank...any other ideas? I'm all ears!
type: Comment

http://stackoverflow.com/comment/92385162
comment on: http://stackoverflow.com/a/52727072
type: Comment
has text: Thanks! Using the for loop is actually fast (takes ~.05 seconds on 6 1D arrays of ~50k fields), and faster than doing the way I had originally posted (took about .8 seconds on the same dataset).
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92246863
type: QuestionComment
type: Comment
has text: I think your loop is totally fine. Of course, if you only need to affect the `user` and `name` then you can just index them directly, e.g. `d['user']['name'] = parse_value(d['user']['name'])`. But if you might need to replace any one of the dicts then you'll need a nested loop like you've got. Either way, your code is very very clear and any other methods would actually likely do the opposite. Syntactic sugar when doing nested lookups can actually be quite confusing.
comment on: http://stackoverflow.com/q/52658157
score: 0

http://stackoverflow.com/q/52687177
has title: Generate SQL in Python
has comment: http://stackoverflow.com/comment/92303122
upvote count: 4
has comment: http://stackoverflow.com/comment/92303880
has comment: http://stackoverflow.com/comment/92302728
has comment: http://stackoverflow.com/comment/92304096
favorite count: 0
has comment: http://stackoverflow.com/comment/92302675
tagged with: sql
has body: there is following DB table (example): +-----------+---------+------------+-------------------+-------------+---------+ | main_name | from | where | time | field | measure | +-----------+---------+------------+-------------------+-------------+---------+ | Students | table_s | source = 4 | current_date - 1 | students_id | count | | Students | table_s | type = 5 | current_date - 1 | students_id | count | | Students | table_s | age = 20 | current_date - 1 | students_id | count | | Teacher | table_t | source = 6 | current_date - 30 | b | sum | | Teacher | table_t | type = 6 | current_date - 30 | b | sum | | Teacher | table_t | age = 40 | current_date - 30 | b | sum | +-----------+---------+------------+-------------------+-------------+---------+ What i need to generate SQL queries from this table in Python SELECT COUNT(students_id) FROM table_s WHERE source = 4 AND type = 5 AND source = 20 AND date (date) = current_date - 1 My thoughts so far are: Transform table data to dict Generate SQL Queries using a Jinja Template I am a beginner in Python Thanks up front for the help :)
has comment: http://stackoverflow.com/comment/92302098
tagged with: python
has comment: http://stackoverflow.com/comment/92302700
answer count: 0
type: UnansweredQuestion
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/92301862
score: 2

http://stackoverflow.com/q/52740339
has answer: http://stackoverflow.com/a/52740828
has comment: http://stackoverflow.com/comment/92405330
has comment: http://stackoverflow.com/comment/92405560
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/92408487
tagged with: python
accepted answer: http://stackoverflow.com/a/52744924
has title: Numpy: vectorize matrix creation
type: AnsweredQuestion
has body: If I want to create a matrix, I simply call m = np.matrix([[x00, x01], [x10, x11]]) , where x00, x01, x10 and x11 are numbers. However, I would like to vectorize this process. For example, if the x's are one-dimensional arrays with length l, then I would like m to become an array of matrices, or a lx2x2-dimensional array. Unfortunately, zeros = np.zeros(10) ones = np.ones(10) m = np.matrix([[zeros, ones], [zeros, ones]]) raises an error ("matrix must be 2-dimensional") and m = np.array([[zeros, ones], [zeros, ones]]) gives an 2x2xl-dimensional array instead. In order to solve this, I could call np.moveaxis(m, 2, 0), but I am looking for a direct solution that doesn't need to change the order of axes of a (potentially huge) array. This also only sets the axis-order right if I'm passing one-dimensional arrays as values for my matrix, not if they're higher dimensional. Is there a general and efficient way of vectorizing the creation of matrices?
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/92405588
has answer: http://stackoverflow.com/a/52744924
score: 0
possible better answer: http://stackoverflow.com/a/52740828

http://stackoverflow.com/q/52620805
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/52621042
has body: I have this python list result =[('921', 36638, None, None, 'ron', '28-SEP', 'platform'), ('921', 36637, None, None, 'john', '28-SEP', 'platform')] The values in this list are dynamic. However the table header is always static. Table header: Issue Vers created_on Build Author Commit Source_Name I want to change this python output and make into a HTML table. This is my work so far z = import result s =open(z) table=['<htm> '] for line in s.splitlines(): if not line.strip(): continue table.append(r' {} {} '.format(*line.split('--- '))) table.append(' ') print ''.join(table) I am confused as to put the static header.Thanks
downvote count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52621042
has title: How to make python list to html table
type: Question
upvote count: 2
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52661334
tagged with: runtime-error
has comment: http://stackoverflow.com/comment/92253715
has answer: http://stackoverflow.com/a/52662230
has comment: http://stackoverflow.com/comment/92254037
favorite count: 0
has comment: http://stackoverflow.com/comment/92254605
upvote count: 2
has title: PyPDF2 'PageObject' is not defined
has comment: http://stackoverflow.com/comment/92252980
tagged with: python
has comment: http://stackoverflow.com/comment/92254193
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58724226
tagged with: pypdf
accepted answer: http://stackoverflow.com/a/52662230
has body: I've been using PyPDF2 (version 1.26.0) to create new PDFs with no problems so far: rotating, cropping pages and more. For some reason, the second line throws an error: from PyPDF2 import PdfFileWriter, PdfFileReader page = PageObject.createBlankPage(100, 100) Being the error the following: NameError: name 'PageObject' is not defined Why could this be happening?
possible better answer: http://stackoverflow.com/a/58724226
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/52671294
tagged with: pandas
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/52671341
has title: Compare dates in python pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52671341
type: Question
answer count: 1
has body: I have 2 panda datetime columns and I want to compare them as following: #check if the Date_Jan precedes Date_Feb df['find_preceding'] = df.apply(lambda x: x.Date_Jan &lt; x.Date_Feb, axis =1) # works # check if the Date_Jan follows Date_Feb df['find_following'] = df.apply(lambda x: x.Date_Jan &gt; x.Date_Feb, axis =1) # works # check if Date_Jan and Date_Feb are the same df['find_same'] = df.apply(lambda x: x.Date_Jan == x.Date_Feb, axis =1) # works # check if Date_Jan is NaT and Date_Feb is a date df['check_NaT_and_valid'] = df.apply(lambda x: x.Date_Jan == 'NaT' and x.Date_Feb != 'NaT', axis =1) # NOT working
score: 0

http://stackoverflow.com/q/52687372
has answer: http://stackoverflow.com/a/52688147
favorite count: 0
tagged with: beautifulsoup
has title: Beautifulsoup not returning complete HTML of the page
upvote count: 5
possible better answer: http://stackoverflow.com/a/66410661
tagged with: python
has body: I have been digging on the site for some time and im unable to find the solution to my issue. Im fairly new to web scraping and trying to simply extract some links from a web page using beautiful soup. url = "https://www.sofascore.com/pt/futebol/2018-09-18" page = urlopen(url).read() soup = BeautifulSoup(page, "lxml") print(soup) At the most basic level, all im trying to do is access a specific tag within the website. I can work out the rest for myself, but the part im struggling with is the fact that a tag that I am looking for is not in the output. For example: using the built in find() I can grab the following div class tag: class="l__grid js-page-layout" However what i'm actually looking for are the contents of a tag that is embedded at a lower level in the tree. js-event-list-tournament-events When I perform the same find operation on the lower-level tag, I get no results. Using Azure-based Jupyter Notebook, i have tried a number of the solutions to similar problems on stackoverflow and no luck. Thanks! Kenny
has comment: http://stackoverflow.com/comment/92303376
type: AnsweredQuestion
downvote count: 0
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/92303090
has answer: http://stackoverflow.com/a/66410661
accepted answer: http://stackoverflow.com/a/52688147
answer count: 2
score: 5

http://stackoverflow.com/comment/92382107
type: Comment
has text: can you say anything about the memory footprints (in MB/GB) of the individual objects and the OS/amount of memory you have available?
comment on: http://stackoverflow.com/q/52728432
score: 0
type: QuestionComment

http://stackoverflow.com/a/52678085
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52635363
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52635363
downvote count: 0
has body: As explained in the first answer by user2357112, this line tells Python 3 to print two characters indicated by their octal value (an octal byte indicates the unicode code point of the character): $ python3.6 -c 'print("\303\251")' Ã© The following line can be used for a behavior similar to Python 2: $ python3.6 -c 'print(b"\303\251".decode())' é
upvote count: 2

http://stackoverflow.com/a/55140535
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52691569
has body: I don't think keras officially supports a case of passing initializable iterators, as you noted, there is no place to provide the placeholders and values mappings. However a workaround is possible using keras callbacks: import tensorflow as tf import numpy as np import pandas as pd # Make sure only tensorflow.keras is imported, don't mix with keras from tensorflow.keras import layers import tensorflow.keras.backend as K # example data x_values = np.random.randn(200, 100).astype(np.float32) y_labels = np.random.randint(low=0, high=9, size=200) graph = tf.Graph() with graph.as_default(): # make datasets from placeholders as in https://www.tensorflow.org/guide/datasets#reading_input_data # X: features_placeholder = tf.placeholder(tf.float32, x_values.shape, name='features') dataset_x = tf.data.Dataset.from_tensor_slices({'x': features_placeholder}) # Y: labels_placeholder = tf.placeholder(tf.float32, [None], name='labels') dataset_y = tf.data.Dataset.from_tensor_slices({'y': labels_placeholder}) # compose datasets to make X-Y pairs for training dataset0 = tf.data.Dataset.zip((dataset_x, dataset_y)) dataset0 = dataset0.batch(16).repeat() # build model with keras inputs = tf.keras.Input(name='x', shape=(x_values.shape[1],)) mlp1 = layers.Dense(16, name='mlp-1', activation='relu') mlp1_out = mlp1(inputs) output = layers.Dense(1, name='y', activation='linear') output_out = output(mlp1_out) model = tf.keras.Model(inputs=inputs, outputs=output_out) # The compile step specifies the training configuration. model.compile(optimizer=tf.train.RMSPropOptimizer(0.001), loss='mse', metrics=['mse']) iterator = dataset0.make_initializable_iterator() feed_dict = { labels_placeholder: y_labels, features_placeholder: x_values } class InitIteratorCallback(tf.keras.callbacks.Callback): """ Ensures that placeholders in dataset are initialized before each epoch begins """ def on_epoch_begin(self, epoch, logs=None): sess = K.get_session() sess.run(iterator.initializer, feed_dict=feed_dict) mod…
score: 1
upvote count: 1

http://stackoverflow.com/a/52675028
type: Answer
downvote count: 0
score: 1
has body: You can apply a lambda to your vectors: df.apply(lambda x: len(x.dropna())) chaos 3 fury 4 shoe 2 dtype: int64 df.apply(lambda x: len(x.dropna())).max() 4
has comment: http://stackoverflow.com/comment/92280836
answers question: http://stackoverflow.com/q/52674987
upvote count: 1

http://stackoverflow.com/q/52627551
accepted answer: http://stackoverflow.com/a/52627729
tagged with: django
tagged with: python
tagged with: django-views
tagged with: django-forms
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52627729
has title: Django: using save(commit=false) when saving form extended from form.Forms
answer count: 1
has body: I have a many-to-many field and in order to save the retrieved data from the form, initially, I have to save an instance of that table, otherwise, I get an error like: "Order: None" needs to have a value for field "id" before this many-to-many relationship can be used. But the issue is when I have 2 save methods called, they also create 2 different logs(at the first save() it creates the instance and at the letter one it edits it) and this cause the chaos. Therefore, I want to be able to commit=False in the first one and finalize the save in the second save(). Commit is used for ModalForm, however, my form extends form.Forms. views.py if request.method == 'POST': form = OrderAddForm(request.POST) if form.is_valid(): order = Order() order.user = request.user order.save() order.ordered_materials.set(form.cleaned_data['ordered_materials']) order.location = form.cleaned_data['location'] order.note = form.cleaned_data['note'] form.save() else: form = OrderAddForm() forms.py class OrderAddForm(forms.Form): ordered_materials = forms.ModelMultipleChoiceField( queryset=Material.objects.all(), ) location = forms.CharField() note = forms.CharField() ordered_materials.widget.attrs.update({'id': 'materialsid', 'class': 'form-control', }) models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered_materials = models.ManyToManyField('Material') location = models.CharField(max_length=500) note = models.CharField(max_length=30, verbose_name="Note") STATUS = ( ('n', 'None'), ('a', 'Accepted'), ('r', 'Rejected'), ) status_name = models.CharField(max_length=1, choices=STATUS, default='n') def __str__(self): return str(self.id)
has comment: http://stackoverflow.com/comment/92188985

http://stackoverflow.com/q/52590597
accepted answer: http://stackoverflow.com/a/52599368
score: 0
tagged with: scons
tagged with: environment-variables
answer count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92120384
tagged with: import
has title: scons "Import of non-existent variable" env: how to fix?
type: Question
has body: I'm hoping that all SConscript could share the environment definition from SConstruct, like this: cat ./SConstruct import os,sys env = Environment(ENV = {'PATH' : os.environ['PATH']}) env.SConscript(dirs=['mydir']) Then under ./mydir cat ./SConscript Import('env') env = env.Clone() I try to run it: scons scons: Reading SConscript files ... scons: *** Import of non-existent variable ''env'' File "/home/john/mydir/SConscript", line 1, in &lt;module&gt; So why scons failed to "Import env", is my syntax wrong? Thanks.
has answer: http://stackoverflow.com/a/52599368

http://stackoverflow.com/comment/92419265
has text: thanks, works fine. How I reorder now, this is the result: ` [[9, 10, 11, 1, 2, 3, 4, 5, 6, 7, 8, 12], [Decimal('800.00'), Decimal('300.00'), Decimal('100.00'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00')]]`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52747230
type: Comment

http://stackoverflow.com/comment/92268565
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52669426
score: 1
has text: With code. Please show what you've tried and what went wrong.

http://stackoverflow.com/comment/92415787
has text: Do you want to extract string inside u'string'?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52745335
score: 0

http://stackoverflow.com/comment/92160107
type: QuestionComment
comment on: http://stackoverflow.com/q/52612012
score: 0
type: Comment
has text: I added the code that makes the thresholding to the image, the result of this code is the "Original Image" which I want to process to obtain the last one.

http://stackoverflow.com/q/52612524
answer count: 1
downvote count: 0
score: 1
has body: All, I am new to python and trying to categorize the data into bins. Assume, I have 2 columns Age and Purchase. Age is a continuous variable and Purchase is a binary variable (1-Yes, 0-No). I want to categorize age into bins and see the total no of purchases in each bin. I have written the following code but I sincerely believe there is much more effective method to do that. Please check the following and suggest new methods or enhancements. Code: bins = [15, 30, 40, 50, 60, np.inf] names = ['15-30', '30-40', '40-50', '50-60', '60+'] dataset['AgeRange'] = pd.cut(dataset['Age'], bins, labels=names) df = [ dataset[dataset.AgeRange == '15-30'].Purchased.sum(), dataset[dataset.AgeRange == '30-40'].Purchased.sum(), dataset[dataset.AgeRange == '40-50'].Purchased.sum(), dataset[dataset.AgeRange == '50-60'].Purchased.sum() ] Thanks!!!
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92159666
has title: Effective method to bin variables in Python
upvote count: 1
has comment: http://stackoverflow.com/comment/92180157
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52612616
type: Question
accepted answer: http://stackoverflow.com/a/52612616
tagged with: pandas

http://stackoverflow.com/comment/92259350
type: Comment
comment on: http://stackoverflow.com/q/52658270
score: 0
type: QuestionComment
has text: what version of oTree do you use? The code was apparently written in a pretty old version of oTree (since a new one uses `pages.py` not `views.py`). And if you use a new version with this code it can be due version incompatibility

http://stackoverflow.com/q/52743006
possible better answer: http://stackoverflow.com/a/52746259
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52746259
has comment: http://stackoverflow.com/comment/92411429
has comment: http://stackoverflow.com/comment/92412470
score: 6
has body: I need to find a random color, given a specific seed number - fast. given the same ID twice, should return the same color. I did this: def id_to_random_color(number): random_bytes = hashlib.sha1(bytes(number)).digest() return [int(random_bytes[-1]) / 255, int(random_bytes[-2]) / 255, int(random_bytes[-3]) / 255, 1.0] The problem is that calculating the sha1 of numbers many times is very slow in total. (I'm using this function about 100k times) Edit: The reason I use a hash function is that I want to have colors that are different for numbers that are close e.g id_to_random_color(7) should be very different from id_to_random_color(9)
type: Question
accepted answer: http://stackoverflow.com/a/52743488
has comment: http://stackoverflow.com/comment/92410830
tagged with: random
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92411675
has answer: http://stackoverflow.com/a/52743488
tagged with: hash
has title: Python - Get random color, given a seed number as fast as possible
has comment: http://stackoverflow.com/comment/92411461
has answer: http://stackoverflow.com/a/52744319
tagged with: python
upvote count: 6

http://stackoverflow.com/q/52594984
score: -1
possible better answer: http://stackoverflow.com/a/52595041
has answer: http://stackoverflow.com/a/52595055
tagged with: loops
type: Question
has body: I have a list with more listen inside. The list can contain unlimited lists. I would like to divide these lists in different lists. Here's an example: data = [[1538406000000, 6569.9680123, 6559.8, 6570, 6551.8, 301.21301548], [1538402400000, 6570, 6569.9, 6572.6, 6500, 1796.34637855], [1538398800000, 6604.7, 6570, 6612.4, 6561, 622.39871899], [1538395200000, 6594.9, 6604.8, 6613.5, 6570, 345.6560351], [1538391600000, 6579.69030138, 6593.9530902, 6603.1, 6555, 1243.109362], [1538388000000, 6617.5, 6579.7, 6622, 6578.6, 344.49315963], [1538384400000, 6628, 6617.5, 6630.2, 6617.4, 231.50416134], [1538380800000, 6602, 6628, 6629.5, 6596.5, 537.99703832], [1538377200000, 6630.4, 6603.9, 6632.12172725, 6600, 135.26208553], [1538373600000, 6627, 6631, 6639.8, 6600, 376.68741732]] var1 = [data[0][0], data[1][0], data[2][0], ....] var2 = [data[0][1], data[1][1], data[2][1], ....] How can I automate this? Many Thanks
favorite count: 0
has answer: http://stackoverflow.com/a/52595049
answer count: 7
tagged with: python
has answer: http://stackoverflow.com/a/52595146
has answer: http://stackoverflow.com/a/52595107
has answer: http://stackoverflow.com/a/52595245
downvote count: 2
has title: Split lists into lists in Python
has comment: http://stackoverflow.com/comment/92124752
upvote count: 1
has answer: http://stackoverflow.com/a/52595088
has answer: http://stackoverflow.com/a/52595041
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/52595049

http://stackoverflow.com/comment/92200279
has text: I haven't downvote but - you haven't asked a question. We don't know your setup. What are you hoping for us to suggest here?
comment on: http://stackoverflow.com/q/52633535
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52682614
has answer: http://stackoverflow.com/a/52682677
has title: define a function use other function names as parameter
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52682681
has body: I have a DataFrame looks like below: df = {'col_1': [1,2,3,4,5,6,7,8,9,10], 'col_2': [1,2,3,4,5,6,7,8,9,10], 'col_3':['A','A','A','A','A','B','B','B','B','B']} df = pd.DataFrame(df) while the real data I'm using has hundreds of columns, I want to manipulate these columns using different functions like min,max as well as self-defined function like: def dist(x): return max(x) - min(x) def HHI(x): ss = sum([s**2 for s in x]) return ss Instead of wirting many lines, I want to have a function like : def myfunc(cols,fun): return df.groupby('col_3')cols.transform(lambda x: fun) # which allow me to do something like: df'min_' + s for s in cols = myfunc(cols, min) df'max_' + s for s in cols = myfunc(cols, max) df'dist_' + s for s in cols = myfunc(cols, dist) Is this possible in Python(my guess is 'yes')? Then how if yes? EDIT ====== ABOUT NAME OF SELF-DEFINED FUNCTION ======= According to jpp's solution, what I've asked is possible, at least for bulit-in functions, more work need regard self-defined function. A workable solution, temp = df.copy() for func in ['HHI','DIST'] : print(func) tempfunc + s for s in cols = df.pipe(myfunc,cols,eval(func)) The key here is to use eval tunction to convert string expression as a function. However, there may be better way to do this, looking forward to see. EDIT ====== per jpp's comment about name of self-defined function ======= jpp's comment that feeds function name directly to myfun is valid based on my test, however, new column name based on func will be some thing like: &lt;function HHI at 0x00000194460019D8&gt;, which is not very readable, the modification is tempstr(func.__name__) + s for s in cols, hope this will help those who come to this problem later.
upvote count: 7
type: Question
accepted answer: http://stackoverflow.com/a/52682677
possible better answer: http://stackoverflow.com/a/52682681
tagged with: function
tagged with: dataframe
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
score: 7
favorite count: 0

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/52653184
tags question: http://stackoverflow.com/q/52639945
tags question: http://stackoverflow.com/q/52630920
tags question: http://stackoverflow.com/q/52610779

http://stackoverflow.com/comment/92413961
type: QuestionComment
type: Comment
score: 1
has text: I don't understand why you have two iterators over your range (a while and for). One of those is enough for what you want. Using both just makes everything convoluted. All you have to do is iterate through your range and test whether your current index is divisible by two with no remainder (making it even). You can also drop your last five lines for a simple join() statement, which will convert a list into a string with a given delimiter.
comment on: http://stackoverflow.com/q/52744638

http://stackoverflow.com/comment/92314473
type: QuestionComment
has text: Make functions which take some arguments and return some results. Then you can combine your functions, because you can take their return values. Here, `race` should return the number of seconds.
score: 0
comment on: http://stackoverflow.com/q/52693796
type: Comment

http://stackoverflow.com/comment/92372005
has text: Yeah Its only for filtering purpose
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52723003

http://stackoverflow.com/q/52638259
has comment: http://stackoverflow.com/comment/92209389
has answer: http://stackoverflow.com/a/52638312
type: Question
has title: Difficulty with for if statement
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92209365
has body: Write a function named "find_value" that takes a list of integers as a parameter and searches for the value 8. The function will return a boolean value representing true if 8 is in the list and false if it is not. def find_value(number): for i in number: if i in number is 8: return True else: return False function find_value incorrect on input [[11, 3, 11, 1, 8, 12]] returned: False expected: True
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52638313
tagged with: python

http://stackoverflow.com/q/52602917
has body: First of all, let me clarify and perhaps apologize, that I know the absolute bare minimum about programming, so although the answer to this is probably sort of scattered around the Internet (and believe me, I've searched), I do not understand it at all. I just need this for a project at school, and as a teenager, I do not have the funds to buy the services of a developer. Thus, I come here to ask you, so thank you so much, if anyone helps. In Python I need to: 1) Create an HTML form that uploads an XML file 2) Convert the XML file to JSON and save it ANY help/pointing to the right direction would be greatly appreciated, for currently I am lost. Thank you so much again.
has answer: http://stackoverflow.com/a/52602977
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: UnansweredQuestion
has title: Creating a Python XML to JSON converter?
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/92139982
answer count: 1
score: 0

http://stackoverflow.com/a/52650901
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92233668
has comment: http://stackoverflow.com/comment/92233713
upvote count: 2
has body: words = [raw_input("Enter a name: ")] takes the input and puts it in a list as a single element: ['aeroplane, fish']. In order to obtain ['aeroplane', 'fish'], you need to split the input with an appropriate delimiter: words = raw_input("Enter a name: ").split(', ') # or a little more robustly wrt white space: words = [w.strip() for w in raw_input("Enter a name: ").split(',')]
has comment: http://stackoverflow.com/comment/92233753
answers question: http://stackoverflow.com/q/52650783
has comment: http://stackoverflow.com/comment/92233609

http://stackoverflow.com/a/52709364
downvote count: 0
score: 1
has body: I don't know if this is exactly what you are looking for, but hopefully this gets you in the ballpark. I also know very little about python, so here is some R: library(tidyverse) library(ggridges) data = read_csv("https://www.dropbox.com/s/y78pynq9onyw9iu/Data.csv?dl=1") data2 = data %&gt;% mutate(breaks = cut(x, breaks = seq(-1,7,.5), labels = FALSE)) data2 %&gt;% ggplot(aes(x=x,y=breaks)) + geom_density_ridges() + facet_grid(~breaks, scales = "free") data2 %&gt;% ggplot(aes(x=x,y=y)) + geom_point() + geom_density() + facet_grid(~breaks, scales = "free") And please forgive the poorly formatted axis.
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52705037
accepted answer of: http://stackoverflow.com/q/52705037
type: Answer

http://stackoverflow.com/comment/92325483
type: QuestionComment
has text: `User.objects.annotate(last_order=Max('order__date_added')).values('order__user', 'last_order').order_by('order__user')` you need to add order by to group by user
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52699407

http://stackoverflow.com/q/52703465
accepted answer: http://stackoverflow.com/a/52710210
tagged with: python
possible better answer: http://stackoverflow.com/a/76724237
type: Question
type: AnsweredQuestion
tagged with: performance
has body: Currently I'm doing some experiments in python and have some jupyter notebooks for evaluation. I'm running each experiment multiple times and with different parameters so my folder structure looks something like this: root |-- .ipynb_checkpoints |-- idea 1 | |-- .ipynb_checkpoints | |-- run 1 | | |-- .ipynb_checkpoints | | |-- results &amp; evaluation | |-- run 2 | | |-- .ipynb_checkpoints | | ... | ... |-- idea 2 | |-- .ipynb_checkpoints | ... ... When i archive the experiments i want to get rid of the .ipynb_checkpoints folders as they are not necessary anymore in my opinion. For this i wrote a quick and dirty little script. import re from os import walk from shutil import rmtree r = re.compile('(^.*\.ipynb_checkpoints$)') dirs = [] for dirpath, _, _ in os.walk('.', topdown=True): if r.match(dirpath): dirs.append(dirpath) for d in dirs: shutil.rmtree(d) Basically, i create a regular expression matching the desired foldername, walk through all subfolders, store the path in dir and then loop a second time to delete all .ipynb_checkpoints folders. The script works fine. However, I'm not satisfied with the code, especially the two for-loops. Since I'm still learning how to programm, i ask myself now if there is a more pythonic way to do this. Any comment on how to make the code faster (although the script currently takes less than a second), pythonic or look cleaner is appreciated. Thanks for your help!
has answer: http://stackoverflow.com/a/76724237
score: 0
answer count: 2
has title: Remove multiple subdirectories with the same name in Python 3.X
tagged with: directory
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52710210

http://stackoverflow.com/comment/92377941
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52723281
has text: Nice. I was expecting some more of these utility functions for sets, lists, etc, on some unknown lib for me. I think I need to write some extra code, for other things that I also want. Thanks for your contribution. I will test and mark green after that.
type: AnswerComment

http://stackoverflow.com/q/52705904
has answer: http://stackoverflow.com/a/52705945
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: django-orm
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52705945
has title: Multiple annotations on related objects
upvote count: 1
type: Question
has body: I'm trying to calculate some related objects for user using Django ORM. As for example I have 3 models: User, A, B class A(models.Model): creator = models.ForeignKey( 'users.User', on_delete=models.CASCADE, related_name='A_set' ) class B(models.Model): creator = models.ForeignKey( 'users.User', on_delete=models.CASCADE, related_name='B_set' ) a_model = models.ForeignKey( 'a.A', on_delete=models.CASCADE, related_name='B_set' ) My query looks like: User.objects.annotate(a_count=Count('a_set')).annotate(b_count=Count('b_set')) When b_count always copying value a_count except when real number of b objects is 0. But when I'm splitting my query into two separate - it works good.

http://stackoverflow.com/q/52655415
upvote count: 1
answer count: 4
favorite count: 0
has title: Remove non digits and put it in a list
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92242202
tagged with: python
possible better answer: http://stackoverflow.com/a/52655478
has body: I want to remove the non digits in data and put it in a python list, but when I try to execute the loop it raises "IndexError: list assignment index out of range" why ? its iterating along the b variable that have the same length that the data has. data = ['1A', '1B', '2', '3A', '3B'] b=range(len(data)) pt=[] for x, i in zip((data), b): pt[i]=(''.join(c for c in x if c in digits))
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52655448
has answer: http://stackoverflow.com/a/52655542
type: Question
downvote count: 2
has comment: http://stackoverflow.com/comment/92242194
has answer: http://stackoverflow.com/a/52655448
score: -1
tagged with: string
has answer: http://stackoverflow.com/a/52655478
has answer: http://stackoverflow.com/a/52655495

http://stackoverflow.com/q/52671111
linked to: http://stackoverflow.com/q/147816
has comment: http://stackoverflow.com/comment/92272059
has body: My decorator is "closure-style"; it does some work before returning the decorated function. Borrowing from this famous question: Preserving signatures of decorated functions def args_as_ints(f): time.sleep(1) # hard at work def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) return g functools.wraps does not preserve the signature in Python 2. from functools import wraps def args_as_ints(f): time.sleep(1) # hard at work @wraps(f) def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z help(funny_function) shows Help on function funny_function in module __main__: funny_function(*args, **kwargs) Computes x*y + 2*z The decorator module doesn't seem to support this style of decorator. Also related: Preserve Signature in Decorator python 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/52673041
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92272315
tagged with: decorator
has comment: http://stackoverflow.com/comment/92272123
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92272309
has comment: http://stackoverflow.com/comment/92272055
linked to: http://stackoverflow.com/q/42359024
favorite count: 0
has answer: http://stackoverflow.com/a/52673041
possible better answer: http://stackoverflow.com/a/52671774
tagged with: python
has answer: http://stackoverflow.com/a/52671774
has comment: http://stackoverflow.com/comment/92272207
type: AnsweredQuestion
has title: Python decorator (closure version) that preserves signature
score: 3

lemmatization
type: Tag
tags question: http://stackoverflow.com/q/52625388
tag name: lemmatization

http://stackoverflow.com/comment/92132211
type: QuestionComment
comment on: http://stackoverflow.com/q/52598078
has text: @WillemVanOnsem I have some logic to deal if that. Just wanted the keep it clean here.
score: 0
type: Comment

http://stackoverflow.com/q/52728832
has title: How to zip a file to STDOUT with zipfile?
tagged with: python-zipfile
favorite count: 0
has comment: http://stackoverflow.com/comment/92407171
has comment: http://stackoverflow.com/comment/92384548
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92383269
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92382882
downvote count: 2
type: Question
has body: I have a program that creates a zip file containing a couple of files using zipfile. It takes an output filename as argument, but if no file or - is given, it should write to STDOUT. But if I pass sys.stdout as file parameter to ZipFile, it gives me the following error: File "/usr/lib/python2.7/zipfile.py", line 775, in __init__ self._start_disk = self.fp.tell() IOError: [Errno 29] Illegal seek Here's my code: import zipfile, sys def myopen(name, mode='r'): if name is not None: try: return open(name, mode) except EnvironmentError as e: print &gt;&gt; sys.stderr, '%s: %s' % (name, e.strerror) sys.exit(3) elif mode == 'r': return sys.stdin elif mode in 'aw': return sys.stdout else: return None outfile = None # build the files ... files = {'file1': 'Here is an example file.\n', 'file2': 'Some more ...'} with myopen(outfile, 'w') as f, zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED, True) as zf: for name, content in files.iteritems(): zf.writestr(name, content) How can I make this work?
tagged with: stdout
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/92280326
comment on: http://stackoverflow.com/q/52659814
score: 0
type: Comment
type: QuestionComment
has text: @Jeronimo alright i see what you mean! I didn't know that the information from that particular object could be passed like that. Thank you so much!

http://stackoverflow.com/comment/117351065
type: Comment
comment on: http://stackoverflow.com/a/52602365
type: AnswerComment
score: 0
has text: But how do I convert an image to blob format? Or do I have to convert it before uploading it to the database?

http://stackoverflow.com/a/52742887
has comment: http://stackoverflow.com/comment/92410680
accepted answer of: http://stackoverflow.com/q/52742803
answers question: http://stackoverflow.com/q/52742803
type: Answer
has comment: http://stackoverflow.com/comment/92410619
score: 0
has body: The first letter of your file is a d, because if file is a string, file[0] is the first character for seq_record in SeqIO.parse(file, 'fasta'): print (seq_record)
type: AcceptedAnswer

http://stackoverflow.com/q/52718054
linked to: http://stackoverflow.com/q/73588253
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/92365962
has answer: http://stackoverflow.com/a/66038567
score: 6
has body: I need to rename a column in a query, but I can't do it on column level, eg session.query(MyModel.col_name.label('new_name')) Is there any way to rename a column on the resulting query object? Eg, something like session.query(...).blah().blah().rename_column('old_name', 'new_name')
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/74480387
has title: sqlalchemy: rename a column on *query* level
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/92363232

http://stackoverflow.com/comment/92164282
has text: @LBaelish please add this to the question
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52614943

http://stackoverflow.com/comment/92229269
type: Comment
score: 1
type: AnswerComment
has text: useful I appreciate it, however the docs for `serving_input_fn` like much of the docs, leave a lot to be desired. What gets passed to to the function? what if it is a sequence example? why isn't there a default for it? From reading the those docs and what it is supposed to [return](https://www.tensorflow.org/api_docs/python/tf/estimator/export/ServingInputReceiver) I do not see what I am suppose to write in that function.
comment on: http://stackoverflow.com/a/52642619

http://stackoverflow.com/comment/92123966
has text: @SusmitAgrawal mm, I would prefer just directly unpacking. Your approach is more robust in the case that the input is _longer_ but still open to failing if the list is shorter.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52594503

http://stackoverflow.com/comment/120508700
score: 2
has text: Can you add some clarification as to why your answer is better and to help users understand what is different?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/68178635

http://stackoverflow.com/a/52726634
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/92414565
has comment: http://stackoverflow.com/comment/92379084
downvote count: 0
has comment: http://stackoverflow.com/comment/92381512
score: 6
has comment: http://stackoverflow.com/comment/92378973
accepted answer of: http://stackoverflow.com/q/52706139
has comment: http://stackoverflow.com/comment/92382346
answers question: http://stackoverflow.com/q/52706139
has body: Since you're new to coding, you should start writing the procedure you'd follow on paper, and then find out which tools you can use to automate this process. Important Read the full answer in order! Don't fall for the temptation of reading the code right away. The solutions I provide are hidden, but you can read them hovering your mouse over them or clicking on them (if you're using StackExchange mobile app, touch the "spoiler" link in each block). The algorithm What I'd do is: Assume I have bins with coins, each bin labeled with the coin denomination. The bins are sorted from the largest to the lowest denomination, and I always pick as much coins as I need from the highest denomination bin before moving to the next bin. Write in a piece of paper the value for which I need to calculate the number of coins of each denomination I need. Start with the first bin (the one holding the highest denomination). Pick as many coins I need from that bin, in such a way that I don't "overshoot" the amount written on the piece of paper (notice that this number can be zero). This can be done with an integer division; for example, if your value is 700 and the bin has denomination 200, you calculate the integer division 700 ÷ 200 = 3 (plus a remainder of 100) Calculate the total amount of the coins I've picked. Strike the value calculated in step 5 and write the remainder as a "new" value. Since you've already calculated the integer division in step 4, you can calculate the remainder. You can also consider that there's a "Modulo" operator in most programming languages that will give you the remainder of an integer division right away. Using the above example, 700 mod 200 = 100, which reads "700 modulo 200 is 100", or "The remainder of the integer division 700 ÷ 200 is 100". Move on to the next bin of coins. Repeat from step 4 until I use all the bins or the value is zero. Example Suppose I start with a value of 292 and I have bins with the following denominations (already sorted from …
type: AcceptedAnswer

http://stackoverflow.com/q/52598877
has comment: http://stackoverflow.com/comment/92132573
tagged with: django
type: Question
has body: I am running django application serving with nginx and gunicorn in supervisor,I am getting gunicorn timeout errors in gunicorn error logs but don't know what causing the errors. 2018-10-01 20:20:19 [20529] [CRITICAL] WORKER TIMEOUT (pid:20646) 2018-10-01 20:20:19 [23948] [INFO] Booting worker with pid: 23948 Is there a way we can configure gunicorn to write logs entry before the gunicorn process is timeout and killed ?
has comment: http://stackoverflow.com/comment/92133217
score: 0
has answer: http://stackoverflow.com/a/53090185
answer count: 1
tagged with: gunicorn
type: UnansweredQuestion
has title: Gunicorn is timeout and no logs in error files
tagged with: python

http://stackoverflow.com/q/52600836
has body: I use video2record to deal with some short video, I want to turn them into tfrecord then I can input them into tensorflow. Then I use videorecord on github: https://github.com/ferreirafabio/video2tfrecord But when I run it, the error said numpy wrong here are my code(python): from video2tfrecord import convert_videos_to_tfrecord convert_videos_to_tfrecord(source_path="video", destination_path="video", n_videos_in_record= 1 , n_frames_per_video = 5 , file_suffix="*.mp4") here are the error: AssertionError Traceback (most recent call last) in () 1 from video2tfrecord import convert_videos_to_tfrecord 2 ----> 3 convert_videos_to_tfrecord(source_path="video", destination_path="video", n_videos_in_record= 1 , n_frames_per_video = 5 , file_suffix="*.mp4") /usr/local/lib/python3.6/dist-packages/video2tfrecord/video2tfrecord.py in convert_videos_to_tfrecord(source_path, destination_path, n_videos_in_record, n_frames_per_video, file_suffix, dense_optical_flow, width, height, color_depth, video_filenames) 174 total_batch_number = int(math.ceil(len(filenames) / n_videos_in_record)) 175 print('Batch ' + str(i + 1) + '/' + str(total_batch_number) + " completed") --> 176 assert data.size != 0, 'something went wrong during video to numpy conversion' 177 save_numpy_to_tfrecords(data, destination_path, 'batch_', 178 n_videos_in_record, i + 1, total_batch_number, AssertionError: something went wrong during video to numpy conversion
score: 0
tagged with: tensorflow
tagged with: numpy
has comment: http://stackoverflow.com/comment/92137935
answer count: 0
tagged with: tfrecord
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92136744
tagged with: python
has title: something went wrong during video to numpy conversion
type: Question

http://stackoverflow.com/comment/92155138
type: QuestionComment
has text: I see... can't you set a max_len for that particular input? if you know that the max_len is 100 (for example), then you can set a placeholder that long, and for any shorter input you just need to fill in NaN until max_len is reached.
comment on: http://stackoverflow.com/q/52605876
score: 0
type: Comment

http://stackoverflow.com/a/52662386
has comment: http://stackoverflow.com/comment/92255743
type: Answer
score: 3
downvote count: 0
has body: You can do this by sort_values, groupby and cumcount df['date_rank'] = df.sort_values(['id', 'date'], ascending=[True, False]).groupby(['id']).cumcount() + 1 demo In [1]: df = pd.DataFrame({ ...: 'id':[1, 1, 2, 3, 3, 4, 5, 6,6,6,7,7], ...: 'value':[.01, .4, .2, .3, .11, .21, .4, .01, 3, .5, .8, .9], ...: 'date':['10/01/2017 15:45:00','05/01/2017 15:56:00', ...: '11/01/2017 15:22:00','06/01/2017 11:02:00','05/01/2017 09:37:00', ...: '05/01/2017 09:55:00','05/01/2017 10:08:00','03/02/2017 08:55:00', ...: '03/02/2017 09:15:00','03/02/2017 09:31:00','09/01/2017 15:42:00', ...: '19/01/2017 16:34:00']}) ...: In [2]: df['date_rank'] = df.sort_values(['id', 'date'], ascending=[True, False]).groupby(['id']).cumcount() + 1 ...: In [3]: df Out[3]: id value date date_rank 0 1 0.01 10/01/2017 15:45:00 1 1 1 0.40 05/01/2017 15:56:00 2 2 2 0.20 11/01/2017 15:22:00 1 3 3 0.30 06/01/2017 11:02:00 1 4 3 0.11 05/01/2017 09:37:00 2 5 4 0.21 05/01/2017 09:55:00 1 6 5 0.40 05/01/2017 10:08:00 1 7 6 0.01 03/02/2017 08:55:00 3 8 6 3.00 03/02/2017 09:15:00 2 9 6 0.50 03/02/2017 09:31:00 1 10 7 0.80 09/01/2017 15:42:00 2 11 7 0.90 19/01/2017 16:34:00 1 Edit you can do this by rank method df.groupby(['id'])['date'].rank(ascending=False, method='dense').astype(int) demo In [1]: df['rank'] = df.groupby(['id'])['date'].rank(ascending=False, method='dense').astype(int) In [2]: df Out[2]: id value date rank 0 1 0.01 2017-10-01 15:45:00 1 1 1 0.40 2017-10-01 15:45:00 1 2 1 0.50 2017-05-01 15:56:00 2 3 2 0.70 2017-11-01 15:22:00 1 4 2 0.77 2017-11-01 15:22:00 1 5 3 0.10 2017-06-01 11:02:00 1 6 3 0.20 2017-05-01 09:37:00 2 7 3 0.30 2017-05-01 09:37:00 2 8 4 0.11 2017-05-01 09:55:00 1 9 4 0.21 2017-05-01 09:55:00 1 10 5 0.40 2017-05-01 10:08:00 2 11 5 0.01 2017-05-01 10:09:00 1 12 6 3.00 2017-03-02 08:55:00 3 13 6 0.50 2017-03-02 09:15:00 2 14 6 0.80 2017-03-02 09:31:00 1 15 7 0.90 2017-09-01 15:42:00 1 16 7 0.10 2017-01-19 16:34:00 2
answers question: http://stackoverflow.com/q/52661772
has comment: http://stackoverflow.com/comment/92257059
upvote count: 3
has comment: http://stackoverflow.com/comment/92255826
has comment: http://stackoverflow.com/comment/92257428
has comment: http://stackoverflow.com/comment/92254992

http://stackoverflow.com/q/52624858
type: AnsweredQuestion
has body: I want to download data from python application/command (for eg: youtube-dl or any other library that download from 3rd party url) directly to google cloud storage(Bucket). I have used gsutil stream command to stream data directly from process to gcs, but it saves only console output to bucket Also i don't want to mount storage because i want to share that storage with distributed system Is there any way in which i can download it without downloading on file system first and then copying it to google cloud storage ? Thanks,
has answer: http://stackoverflow.com/a/52635338
type: Question
has title: Download data directly to google cloud storage
score: 4
tagged with: google-cloud-storage
upvote count: 4
answer count: 2
tagged with: google-cloud-platform
accepted answer: http://stackoverflow.com/a/52635338
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92183129
tagged with: bucket
possible better answer: http://stackoverflow.com/a/52653348
tagged with: python
has answer: http://stackoverflow.com/a/52653348
has comment: http://stackoverflow.com/comment/92209307

http://stackoverflow.com/comment/92404501
has text: Maybe you can use, stop_words= 'english' a built-in stop word list for English is used, or you may find a stop words list elsewhere and input it in, or you can generate a stop words list by yourself. In this way, you need to count the word frequency, then pick out the most frequent ones.
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/52713458

http://stackoverflow.com/comment/92378479
type: QuestionComment
comment on: http://stackoverflow.com/q/52725852
has text: Where is the Python code running, inside the same VPC as the RDS instance? Or from outside the VPC? If outside, is the "Publicly Accessible" flag enabled on the RDS instance?
score: 0
type: Comment

http://stackoverflow.com/comment/92165687
type: Comment
has text: your columns don't have names at this point so you could just name them...
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52615560

http://stackoverflow.com/comment/92160062
has text: @martineau if we need to maintain a sum less than 20 when a new int is added, isn't it essential that we calculate the sum with newly added random number to ensure that it remains under 20 before adding it and if the sum exceeeds 20 we must select a different random number? I would think that the sum of l + the potential new variable we are going to add is a critical measure
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52612498

http://stackoverflow.com/a/52687344
answers question: http://stackoverflow.com/q/52687300
downvote count: 0
has comment: http://stackoverflow.com/comment/92301938
has comment: http://stackoverflow.com/comment/92302021
has comment: http://stackoverflow.com/comment/92302033
has body: To do it without any packages to install (long one-liner :-) ): import itertools,statistics a = dict(zip(sorted(set([i['index'] for i in lod])),[statistics.mean(int(item['value']) for item in group) for key, group in itertools.groupby(lod, key=lambda x: x['index'])])) Now: print(a) Returns: {1: 2.5, 2: 4} If python 2: import itertools a = dict(zip(sorted(set([i['index'] for i in lod]),key=[i['index'] for i in lod].index),[sum(int(item['value']) for item in group)/len(int(item['value']) for item in group) for key, group in itertools.groupby(lod, key=lambda x: x['index'])])) Explanation: get the ordered list of unique elements using set use itertools.groupby for grouping then iterate by key a group, the get average using statistics or sum and len the above two notes are all in a zip(dict(zip(...))) Or to make the code little cleaner: Python 3: import itertools,statistics unique_elements=sorted(set([i['index'] for i in lod])) groups=statistics.mean(int(item['value']) for item in group) for key, group in itertools.groupby(lod, key=lambda x: x['index'])] a = dict(zip(unique_elements,groups)) Python 2: import itertools unique=sorted(set([i['index'] for i in lod]) groups=[sum(int(item['value']) for item in group)/len(int(item['value']) for item in group) for key, group in itertools.groupby(lod, key=lambda x: x['index'])] a = dict(unique,groups))
has comment: http://stackoverflow.com/comment/92302103
has comment: http://stackoverflow.com/comment/92301930
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/92206441
comment on: http://stackoverflow.com/a/52636660
score: 0
type: AnswerComment
type: Comment
has text: Thanks that seems to do the trick. Is it possible to convert them back?

http://stackoverflow.com/q/52589025
tagged with: sftp
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52589270
linked to: http://stackoverflow.com/q/50118919
tagged with: python
accepted answer: http://stackoverflow.com/a/52589270
has comment: http://stackoverflow.com/comment/92113237
type: AnsweredQuestion
score: 1
tagged with: pysftp
upvote count: 1
type: Question
has title: Move files from local to remote server using sftp in python
has body: I want to copy all files from a local directory to a remote directory. I used the pysftp library for that. My code below is not showing any errors, but my local files are also not being transferred to my remote server. My code: import pysftp remotepath = '/home/a7user/sftp/sftp/CentralData/' localpath = 'E:\\backup\\' cnopts = pysftp.CnOpts() cnopts.hostkeys = None with pysftp.Connection(host='xx.xxx.xx.xx',username='user',password='5fTPt00',cnopts=cnopts) as sftp: sftp.put_d(localpath,remotepath) print('Upload finished') What am I doing incorrectly?
linked to: http://stackoverflow.com/q/29128205
has comment: http://stackoverflow.com/comment/92113212

http://stackoverflow.com/q/52655738
type: Question
has comment: http://stackoverflow.com/comment/92246256
answer count: 2
upvote count: 1
has title: Python "zfill()" equivalent in OCaml
downvote count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/92244560
tagged with: ocaml
has body: I'm a beginner and I have to learn Ocaml for scientific programming. I just have one question: Is there an equivalent of Python's .zfill() method in Ocaml to make leading zeros appear in a string?
score: 0
has answer: http://stackoverflow.com/a/52656714
tagged with: leading-zero
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52656820

http://stackoverflow.com/q/52715595
has comment: http://stackoverflow.com/comment/105406313
upvote count: 1
favorite count: 0
tagged with: shared-data
has title: Share images and data between two python processes running simultaneously with multiprocessing
tagged with: python
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: multiprocessing
type: Question
has body: I'm currently working on a python project. It's about image detection. I have to processes, which are running simultaneously with multiprocessing. The first function communicates with the frame grabber and is doing some image processing. The second function communicates with a neural net, which does the actual image-detection. The second function needs the image grabbed in the first function for the detection. The second function should then provide the results, which are used by the first function to draw rectangles on the video stream (where the detected objects are). The code looks something like this: import multiprocessing import cv2 import json def fun1(): while True: # Shows video-stream, does image editing, grabs frames # and stores them in an external folder # Accesses the result for drawing rectangles from the # .json file def fun2(): while True: # Uses frames from the external folder # does image-detection, saves result to .json file if __name__ == "__main__": s = Process(target=fun1) r = Process(target=fun2) s.start() r.start() s.join() r.join() As you can see, both processes are running in an infinite while loop. As for now, I save the images created in fun1 in a folder, where fun2 can access them. The results from the neural net from fun2 are saved in a .json file, where fun1 can access them. Both, the result and the image, change every iteration. I was wondering, if there is a way to send the current image directly to fun2 and to send the result from fun2 to fun1 without using an extern .json file. Is there a way to communicate directly? I hope that I could explain my problem understandably. Thanks for helping me out!
score: 1
tagged with: ubuntu-16.04

http://stackoverflow.com/comment/92442330
type: AnswerComment
type: Comment
has text: I tried to implement the inverse function: server sends file to client, but using this method i get a Memory Error Exception at line `buffer = self.sock.recv(expected_size - len(packet))`. I tried to print the file size on the server, and it is 276 bytes. I printed the expected_size on the client,and I have a weird value (5216694956355249004) What's the problem?
comment on: http://stackoverflow.com/a/52724841
score: 0

http://stackoverflow.com/a/52743223
score: 0
answers question: http://stackoverflow.com/q/52743188
type: Answer
has comment: http://stackoverflow.com/comment/92440390
has body: Have you tried: return jsonify({result: True})

http://stackoverflow.com/comment/92232928
type: AnswerComment
comment on: http://stackoverflow.com/a/52645942
score: 0
type: Comment
has text: Thank you! I've come up with a solution a bit similar but more complicated... This is perfect !

http://stackoverflow.com/comment/100388516
has text: @Sade were you able to resolve the issue. I am also facing similar issue and looking for a solution
score: 0
comment on: http://stackoverflow.com/a/52635160
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/92392306
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52733660
has text: Why not set the key column as index and simply transpose the df?
score: 0

http://stackoverflow.com/a/52668683
has body: Just use random.sample which is the built-in way of generating non-repeating random elements from a population: from random import sample for i in range(1, 3): for j in sample(list(range(1, 11)), 7): print(i, ',', j) # 7 random non-repeating `j` from [1, 2, ..., 10] For sampling 14 random elements from the entire pool of possible pairs, you can combine it with itertools.product: from itertools import product sample_pairs = sample(list(product(range(1, 3), range(1, 11))), 14) #[(2, 10), # (1, 1), # (2, 7), # (2, 9), # (1, 10), # (2, 5), # (1, 2), # (1, 9), # (2, 4), # (2, 3), # (2, 2), # (1, 8), # (2, 8), # (1, 6)]
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52668547
type: Answer

http://stackoverflow.com/comment/92337281
type: QuestionComment
score: 1
has text: When there are no brackets after the decimal, do you want a match or not?
comment on: http://stackoverflow.com/q/52705416
type: Comment

http://stackoverflow.com/a/52726133
has comment: http://stackoverflow.com/comment/92777738
type: Answer
has comment: http://stackoverflow.com/comment/92776923
has body: Firstly, regarding the issue with reading the data, I would suggest using dcmread in Python, as that gave me the same exact data as dicomread in MATLAB. Secondly, in MATLAB when im2uint8 converts int16 values it will scale them assuming minimum and maximum values for the data equal to -32768 and 32767, respectively (i.e. the minimum and maximum values representable by an int16). For bytescale to behave equivalently, I believe you need to set the cmin and cmax arguments accordingly (since they will otherwise default to data.min() and data.max(), respectively). This should replicate the results of im2uint8 in Python: Z_axis = bytescale(img.astype(float), cmin=-32768, cmax=32767) Note: conversion of the data to float first is necessary to account for an apparent bug in bytescale that doesn't handle the integer arithmetic properly (found courtesy of Cris Luengo).
has comment: http://stackoverflow.com/comment/92395803
has comment: http://stackoverflow.com/comment/92776996
score: 4
has comment: http://stackoverflow.com/comment/92776775
accepted answer of: http://stackoverflow.com/q/52725553
has comment: http://stackoverflow.com/comment/92776883
upvote count: 4
answers question: http://stackoverflow.com/q/52725553
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52711720
has body: Try something like this: ([ ](?![^(]*\))) (Try it here: https://regex101.com/r/UNgliZ/2) Explained: Capture all of: [ ] - Match a single space character. The character class is unnecessary, but makes the space explicit since it's at the beginning of the pattern and might look unintentional. (?![^(]*\)) Negative lookahead; Asserts that the space ([ ]) is not followed by: [^(]* Matches any number of characters that aren't ( \) Matches a single )
type: Answer
has comment: http://stackoverflow.com/comment/92371652
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52711543
answers question: http://stackoverflow.com/q/52711543
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/52742055
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52741970
type: Answer
has body: This is happening because message.guild is None. guild is None because private messages, direct messages between two users, do not go through a guild. If your bot sends or receives any private messages, those messages will have None as their message.guild attributes.
score: 1

http://stackoverflow.com/q/52725743
has comment: http://stackoverflow.com/comment/92376830
has body: I have a simple for loop which loops through the contents of an int list and multiplies every non zero int. I store this value in the variable mult. However, mult is not changing. What's wrong? def answer(l): mult = 0 for i in l: if i != 0: if mult == 0: mult *= i return mult print (answer([3,4,5]))
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52725774
has answer: http://stackoverflow.com/a/52725895
has comment: http://stackoverflow.com/comment/92376744
has answer: http://stackoverflow.com/a/52725998
has comment: http://stackoverflow.com/comment/92376738
has answer: http://stackoverflow.com/a/52725827
has title: Python variable not changing
type: Question
has answer: http://stackoverflow.com/a/52725929
tagged with: python
has answer: http://stackoverflow.com/a/52725882
has comment: http://stackoverflow.com/comment/92377041
answer count: 6
score: 0

http://stackoverflow.com/q/52729179
tagged with: pandas
has answer: http://stackoverflow.com/a/52729284
tagged with: python
has answer: http://stackoverflow.com/a/52729219
linked to: http://stackoverflow.com/q/37011734
has body: Input df: title desc movie A It is a awesome movie with action movie B Slow but intense movie. I want to filter rows which contains the following keywords: keys = ["awesome", "action"] Output DF: title desc movie A It is a awesome movie with action Code: index_list = [] for index,rows in df.iterrows(): if any(x in rows["desc"].split(" ") for x in keys) == True: index_list.append(index) df = df.loc[index_list] Approach: In each row, I am checking if any of the keywords are present after splitting the rows This approach works fine, but I am interested to know if there is any one liner in pandas to achieve the same. Example: df.loc[df['column_name'].isin(some_values)]
type: UnansweredQuestion
type: Question
answer count: 2
duplicate of: http://stackoverflow.com/q/37011734
has comment: http://stackoverflow.com/comment/92383521
score: 0
has title: filter rows on column values with string methods

http://stackoverflow.com/q/52744220
has comment: http://stackoverflow.com/comment/92492796
answer count: 1
has comment: http://stackoverflow.com/comment/92413147
has comment: http://stackoverflow.com/comment/92413402
favorite count: 0
has comment: http://stackoverflow.com/comment/92460579
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: Context I would like to subclass a class from a library (xarray) which has a huge API, and I can't modify the class upstream. This superclass (xarray.Dataset) is a general data storage class, which I want subclass to make it more specific to my use case by adding new attributes and methods, while retaining most of the API. I also want to be able to further subclass my new class in case another user wants even more specific functionality. I've tried various approaches (which I am happy to describe in detail), but I'm not sure whether my newest idea (decorating all inherited methods) is possible/a terrible one. Problem The reason I can't simply subclass like this: class MyDataset(xarray.Dataset): def __init__(data, new_input) super.__init__(self, data) self.new_attribute = new_input def new_method(self) return self.new_attribute Is because lots of the inherited xarray.Dataset methods return new instances of xarray.Dataset objects, which means I will lose my new attributes when performing common operations on my data structure using those methods. i.e. ds = MyDataset(data, new_input) # take the mean of my data over time, a common operation which uses an inherited method result_ds = ds.mean(dim=time) # Now I will have lost my extra data print(result_ds.new_attribute) # will return either AttributeError or None depending on the implementation of the method My proposed solution I know that I want all the methods that would normally return an instance of xarray.Dataset to instead return an instance of MyDataset, and that to get MyDataset from xarray.Dataset I just need to tack on the new_attribute data. (which is stored privately in the instance of MyDataset whose method was called.) Can I therefore write something in the __init__ of MyDataset which decorates all methods which were inherited from super(), using a decorator which checks if the return value of the method is an instance of xarray.Dataset, and if so converts it to an instance of MyDataset using my extra data? …
tagged with: python
score: 2
tagged with: oop
has comment: http://stackoverflow.com/comment/92413013
type: Question
has comment: http://stackoverflow.com/comment/92413370
downvote count: 0
has comment: http://stackoverflow.com/comment/92413227
tagged with: decorator
has answer: http://stackoverflow.com/a/52744909
tagged with: python-xarray
has title: Decorating all inherited methods
has comment: http://stackoverflow.com/comment/92413456

http://stackoverflow.com/a/62221781
has body: I found a solution, but it is definitely not beautiful. I found that pytesseract was crap at capturing digits that have few number. I took inspiration from a CNN which uses "Zero padding" when doing image recognition. Now be aware, the only thing i took inspiration from, is the actual name of it, not the method (which is far more complex than anything this post will come close to). I found an image which contained a 0, and create a "zero padding image" with three zeros (arbitrarily chosen number and amount of numbers). Anyway, i found that pytesseract was able to scan the image of the digits perfectly! 15/15 cases, rather than 3/15 cases. Remember to divide the OCR scanned digit by 1000 (if you use three 0's). I used the horizontal image stacking technique shown in this post: Image stacking post import numpy as np from PIL import Image def concat_images(imga, imgb): """ type(imga): string of filename type(imgb): string of filename type(new_img): PIL.Image.Image """ imga = np.asarray(Image.open(imga).convert('LA') ) imgb = np.asarray(Image.open(imgb).convert('LA') ) ha,wa = imga.shape[:2] hb,wb = imgb.shape[:2] max_height = np.max([ha, hb]) total_width = wa+wb new_img = np.zeros(shape=(max_height, total_width, 2) , dtype = 'uint8') new_img[:ha,:wa]=imga new_img[:hb,wa:wa+wb]=imgb new_img = Image.fromarray(new_img) return new_img
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52731296

http://stackoverflow.com/comment/127998501
comment on: http://stackoverflow.com/a/52679572
type: Comment
has text: Several of the changes here are unnecessary. `print()` allows you to concatenate values with commas just fine, though you can't do that in the arguments to `input()`.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52607063
has answer: http://stackoverflow.com/a/63206628
tagged with: warnings
has title: Tensorflow warning: The graph couldn't be sorted in topological order?
answer count: 2
tagged with: deep-learning
linked to: http://stackoverflow.com/q/50622525
downvote count: 0
tagged with: neural-network
favorite count: 0
has answer: http://stackoverflow.com/a/52607304
tagged with: python
upvote count: 16
type: AnsweredQuestion
has body: When I run tensorflow training (with custom defined graph, closed source), it outputs the warning: 2018-10-03 14:29:24.352895: E tensorflow/core/grappler/optimizers/dependency_optimizer.cc:666] Iteration = 0, topological sort failed with message: The graph couldn't be sorted in topological order. What does it mean? What could likely cause this problem and how to avoid it? Update: For the record, in my case, tensorflow still works correctly despite this warning. So I think it just means there are more loops in the computation graph than what tensorflow expects, not necessarily infinite loop. I fixed this by avoid using manual loop in code, but instead using tensor manipulation (stack, concat, slice, reshape...)
accepted answer: http://stackoverflow.com/a/52607304
score: 16
tagged with: tensorflow
type: Question
possible better answer: http://stackoverflow.com/a/63206628

http://stackoverflow.com/comment/92269367
has text: Please print a few lines of your `.csv` file. Is this .csv file, generated by download link in tensorboard GUI?
comment on: http://stackoverflow.com/q/52653656
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52666048
has comment: http://stackoverflow.com/comment/92261868
has title: DidThe existing group or dataset be cleaned when opening and writing h5 file using h5py？
score: 0
answer count: 1
tagged with: h5py
type: UnansweredQuestion
tagged with: python
has body: Some data need to be written to HDF5 file in different steps, and the sample code is posted below. The problem I meet is the existing h5 group and dataset were cleaned when a new step, including opening and writing, runs again. import h5py import numpy as np a=r"F:\HY1A1B\cd.h5" #first open and write b=h5py.File(a, 'w') zeroPixelCounts = np.zeros((5,10)) QC_Attribute = b.create_group("QC Attributes") QC_Attribute.create_dataset("Zero Pixel Counts",(5,10),data=zeroPixelCounts) b.close() #second open and write b=h5py.File(a, 'w') QC_Attributex = b.create_group("QC Attributes xxxx") QC_Attributex.create_dataset("Zero Pixel Counts",(5,10),data=zeroPixelCounts) b.close() #problem：the existing data in first open and write processing were cleaned
has answer: http://stackoverflow.com/a/52666292
type: Question

http://stackoverflow.com/comment/135549992
type: AnswerComment
has text: I think it does not answer the question
score: 0
type: Comment
comment on: http://stackoverflow.com/a/63869249

http://stackoverflow.com/a/63475655
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52725278
downvote count: 0
has body: Python is alerting you that you threw an exception while another one was in the process of being handled. The warning is there to alert you in case this was unexpected so that you know about the original exception. Consider a case like the following: class Resource: def close(self): if cannot_close: raise Error("Cannot close") def write_data(self, data): ... some_function(): try: res = Resource() res.write_data("some data") except Error as e: res.close() Let's say that write_data raises an exception, but then the close does so also, unexpectedly. When that happens, it's nice to know about both exceptions. In most cases, you want to know about the original exception raised by write_data but knowing about the one from close helps you know that something strange happened with close. But for your case, you are simply restating the original error in a new way. Doing so lets you provide more context, for example: with open(json_file) as j: try: json_config = json.load(j) except ValueError as e: raise Exception('Invalid json from file {}: {}'.format(json_file, e)) This would provide you with the path of the file that failed to be parsed as JSON, which is helpful context information that won't be in the original exception message. So to tell Python that you are essentially re-raising the original exception, but with more context, you add from e. with open(json_file) as j: try: json_config = json.load(j) except ValueError as e: raise Exception('Invalid json from file {}: {}'.format(json_file, e)) from e This is equivalent to "exception chaining" in Java where you supply the original exception to the constructor of the new exception.

http://stackoverflow.com/a/52703974
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52703921
upvote count: 2
downvote count: 0
has body: to make your code work, change dep_delay = all_data.groupby(["Month"].DepDelay.count().max()) to dep_delay = all_data.groupby(["Month"]).DepDelay.count().max() To find your solution: idx = all_data['DepDelay'].idxmax() all_data.loc[[idx], ['Month', 'DepDelay']] Output Month DepDelay 8 2 15.0

http://stackoverflow.com/a/52669331
type: Answer
has body: You need to compare the entered student ID with the ones in the file line-by-line. import csv filePath = "data.csv" student_num=input("Enter student ID:") if (student_num == ""): print("Empty input. Please enter again.") found = False with open(filePath) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if (row['student_id'] == student_num): average = int((row['CSIT110'])+int(row['CSIT121'])+int(row['CSIT135'])+int(row['CSIT142']))/4 print("=================") print("Student's details") print("=================") print("Student ID | First Name | Last Name") print("{0:&lt;10} |{1:&gt;11} | {2:&lt;10}".format(row['student_id'],row['first_name'],row['last_name'])) print("===============================================") print("CSIT110 | CSIT121 | CSIT135 | CSIT142 | Average") print("{0:^8}|{1:^9}|{2:^9}|{3:^9}|".format(row['CSIT110'],row['CSIT121'],row['CSIT135'],row['CSIT142'])) found = True break if not found: print("No student record found.")
has comment: http://stackoverflow.com/comment/92324335
accepted answer of: http://stackoverflow.com/q/52669094
answers question: http://stackoverflow.com/q/52669094
has comment: http://stackoverflow.com/comment/92269572
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/92274787
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52671981
has text: @chepner I think it is. Where else is the base case?

http://stackoverflow.com/comment/92118298
has text: @peak, acceptable output is updated on the top of the question already.
comment on: http://stackoverflow.com/q/52588722
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52600173
answer count: 0
has body: Here is a sample code of what I want to do: class myfiles: def __init__: self.input_file = "" self.output_file = "" class process_files: def __init__(self, list_of_myfiles): self.myfiles_list = list_of_myfiles self.my_new_files = [] def intial_work(self): list_of_objects = [] for f in self.myfiles_list: new_files = myfiles() new_files.input_file = f list_of_objects.append(new_files) self.my_new_files = list_of_objects def update_files(self): # this will update the instance output_file for f in self.my_new_files: # do some work on input file and write it to ouput new_files process_files.work_function(f) # this will not update the instance output_file n_cores = psutil.cpu_count() p = multiprocessing.Pool(n_cores) p.map(process_files.work_function, self.my_new_files) @staticmethod def work_function(new_file): # do some work on input file and update output new_file.output_file = "something new" I have two classes the first is myfiles which I will use it as list of objects. second is process_files which will process objects from the previous class. list_of_files = ["a", "b", "c"] myprocess = process_files(list_of_files) myprocess.intial_work() myprocess.update_files() In method update_files() if I used for loop to update the instance myfiles.output_file will have a value, but if I used Pool.map myfiles.output_file will always be empty string why? If Pool will not work. Is there another way to run them in parallel? (multithreading or multi processing)
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92134956
tagged with: class
has comment: http://stackoverflow.com/comment/92135059
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92136208
tagged with: python
has title: Updating class variable from another class using Pool

http://stackoverflow.com/comment/92193069
score: 0
type: AnswerComment
has text: @NathanExplosion In that case the flow goes like this. You have a slice operation that gives you a scalar, so you start the gradient computation with the scalar 1 as `dc[0,0]/dc[0,0]`. Then you compute `dc[0,0]/dc`, which is a matrix shaped like `c` with the gradient of `c[0,0]` wrt each element - so it is a matrix, `grad_c`, with all 0 except a 1 in the first value of the first row. Then you can get `dc[0,0]/da`, which is `(dc[0,0]/dc)*(dc/da)`. We saw it ended up being `grad_c * b.T`, so you get a matrix the size of `a` where the first row is the first column of `b` and all other rows are 0.
comment on: http://stackoverflow.com/a/52626700
type: Comment

http://stackoverflow.com/q/52675015
type: Question
has title: Why does my UDP pinger client only timeout?
has body: I've made a UDP Pinger server side, however this UDP Pinger client only sends request time outs. I'm trying to make a pinger that sends 10 pings to the server. import time from socket import * serverName = '' serverPort = 12000 ClientSocket = socket(AF_INET, SOCK_DGRAM) ClientSocket.settimeout(1) ping = 1 message = 'ping' counter = 10 i = 0 remain = counter - i while counter &lt; i : i = i + 1 addr = ("", 120000) start = time.time() ClientSocket.sendto(message, (serverName, serverPort)) while ping &lt; 11: try: message, server = ClientSocket.recvfrom(1024) end = time.time() elapsed = end - start print (message + " " + str(ping) + " " + str(elapsed)) except timeout: print ('REQUEST TIMED OUT') ping = ping + 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/92279780
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/52721988
accepted answer of: http://stackoverflow.com/q/52721690
type: Answer
has comment: http://stackoverflow.com/comment/92369298
has body: Jpp already added the solution, but just to add a slightly more readable formatted string - see this awesome website. import calendar def last_thurs_date(date): year, month = date.year, date.month cal = calendar.monthcalendar(year, month) # the last (4th week -&gt; row) thursday (4th day -&gt; column) of the calendar # except when 0, then take the 3rd week (February exception) last_thurs_date = cal[4][4] if cal[4][4] &gt; 0 else cal[3][4] return f'{year}-{month:02d}-{last_thurs_date}' Also added a bit of logic - e.g. you got 2019-02-0 as February doesn't have 4 full weeks.
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52721690
has comment: http://stackoverflow.com/comment/92369361
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92495352
type: AnswerComment
comment on: http://stackoverflow.com/a/52741412
type: Comment
has text: Yes I solved the problem now thanks, I'll explain tomorrow what I did.
score: 0

http://stackoverflow.com/q/52669737
upvote count: 3
has comment: http://stackoverflow.com/comment/92284693
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92271283
tagged with: postgresql
tagged with: odoo-10
tagged with: sql
has answer: http://stackoverflow.com/a/52670099
has title: Use values in different rows of a column as values in different columns but only one row
has answer: http://stackoverflow.com/a/52669808
favorite count: 0
has body: Is possible to group rows and use one value of each row for different custom columns? Original table: ID Tax Amount -------------------------- 1 21% 33,40 1 10% 15,30 1 4% 1,32 2 21% 12,43 2 10% 4,20 Desired table: ID Tax 21% Tax 10% Tax 4% -------------------------------------- 1 33,40 15,30 1,32 2 12,43 4,20 0,00 How would you do that? Thanks in advance.
possible better answer: http://stackoverflow.com/a/52669808
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52670099

vapoursynth
tags question: http://stackoverflow.com/q/52742553
type: Tag
tag name: vapoursynth

http://stackoverflow.com/comment/92216788
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52642247
type: Comment
has text: Oh My God !! blhsing you so excellent !! Thank you My Dear Friend

http://stackoverflow.com/comment/92468429
type: Comment
comment on: http://stackoverflow.com/a/52728691
has text: Yeah. But that would mean that I would need to declare a potentially infinite amount of variables that I could assign the values to. Or am I misunderstanding you? 'Cause at the end of the program the user will press a button and all the information is distributed to different places, like word documents and mail software and others. Whereafter the program terminates.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52705933
tagged with: vectorization
has comment: http://stackoverflow.com/comment/92340745
type: AnsweredQuestion
has body: The following code models a system that can sample 3 different states at any time, and the constant transition probability between those states is given by the matrix prob_nor. Threrefore, each point in trace depends on the previous state. n_states, n_frames = 3, 1000 state_val = np.linspace(0, 1, n_states) prob = np.random.randint(1, 10, size=(n_states,)*2) prob[np.diag_indices(n_states)] += 50 prob_nor = prob/prob.sum(1)[:,None] # transition probability matrix, # row sum normalized to 1.0 state_idx = range(n_states) # states is a list of integers 0, 1, 2... current_state = np.random.choice(state_idx) trace = [] sigma = 0.1 for _ in range(n_frames): trace.append(np.random.normal(loc=state_val[current_state], scale=sigma)) current_state = np.random.choice(state_idx, p=prob_nor[current_state, :]) The loop in the above code makes it run pretty slow, specially when I have to model millions of data points. Is there any way to vectorize/accelerate it?
has comment: http://stackoverflow.com/comment/92341343
has comment: http://stackoverflow.com/comment/92339634
type: Question
tagged with: numpy
score: 5
has comment: http://stackoverflow.com/comment/92341015
upvote count: 5
has title: Vectorize numpy code with operation depending on previous value
linked to: http://stackoverflow.com/q/50789448
has comment: http://stackoverflow.com/comment/92339513
has comment: http://stackoverflow.com/comment/92341417
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52706091
possible better answer: http://stackoverflow.com/a/52707048
favorite count: 0
has answer: http://stackoverflow.com/a/52707048
accepted answer: http://stackoverflow.com/a/52706091
tagged with: python

http://stackoverflow.com/q/52709057
score: 0
has title: Managing thread execution in Python
has answer: http://stackoverflow.com/a/52709107
answer count: 1
type: UnansweredQuestion
tagged with: python-multithreading
tagged with: python
has body: I am currently using worker threads in Python to get tasks from a Queue and execute them, as follows: from queue import Queue from threading import Thread def run_job(item) #runs an independent job... pass def workingThread(): while True: item = q.get() run_job(item) q.task_done() q = Queue() num_worker_threads = 2 for i in range(num_worker_threads): t = Thread(target=workingThread) t.daemon = True t.start() for item in listOfJobs: q.put(item) q.join() This is functional, but there is an issue: some of the jobs to be executed under the run_job function are very memory-demanding and can only be run individually. Given that I could identify these during runtime, how could I manage to put the parallel worker threads to halt their execution until said job is taken care of? Edit: It has been flagged as a possible duplicate of Python - Thread that I can pause and resume, and I have referred to this question before asking, and it surely is a reference that has to be cited. However, I don't think it adresses this situation specifically, as it does not consider the jobs being inside a Queue, nor how to specifically point to the other objects that have to be halted.
tagged with: multithreading
type: Question
linked to: http://stackoverflow.com/q/33640283
has comment: http://stackoverflow.com/comment/92344383

http://stackoverflow.com/q/52656330
has answer: http://stackoverflow.com/a/53369907
upvote count: 6
has body: Let say I have a pandas DataFrame called "missing_data" , one of the columns is called "normalized-losses". When I wrote missing_data["normalized-losses"]. And then press tab I expected to see a lot of methods for pandas Series, HOWEVER, this is what I saw missing_data["normalized-losses"].ipynb_checkpoints/ What is this, and how could I change it to auto-completion?
favorite count: 0
tagged with: jupyter-notebook
accepted answer: http://stackoverflow.com/a/53369907
has title: In jupyter notebook, pressing tab print "ipynb_checkpoints/" instead of auto-completion
score: 6
tagged with: python
type: AnsweredQuestion
tagged with: ipython
type: Question
downvote count: 0
tagged with: series
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/92367452
score: 0
has text: In case I use `fillna`, the `LabelBinarizer` will create one more column for the `nan`, instead of create a zero-vector.
comment on: http://stackoverflow.com/q/52720733
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92306486
type: QuestionComment
score: 0
has text: this is the regex function how can i edit it to get only gmail accounts ? regex = re.compile(("([a-z0-9!#$%&*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`" "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|" "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))
type: Comment
comment on: http://stackoverflow.com/q/52689716

http://stackoverflow.com/a/52693010
type: AcceptedAnswer
type: Answer
has body: Since this is a homework problem, I don't want to give the code. But I will say, you should consider putting all of your code in the while loop and change its terminating condition to 5. (ie, quit when "choice==5") Then you can handle the logic of selections and invalid selections within the loop, say in a series of if-else.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52692931
accepted answer of: http://stackoverflow.com/q/52692931
upvote count: 1

http://stackoverflow.com/comment/92234824
has text: Actually no, you are unpacking tuple `args` to function call, sorry. But it feels a little strange
comment on: http://stackoverflow.com/q/52651506
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52639831
answers question: http://stackoverflow.com/q/52639457
downvote count: 0
type: AcceptedAnswer
score: 6
type: Answer
upvote count: 6
has body: Use SerializerMethodField() in your serializer class GetLanguageSerializer(serializers.ModelSerializer): technology = serializers.StringRelatedField(many=True) frameworks = serializers.StringRelatedField(many=True) total_technology = serializers.SerializerMethodField(read_only=True) toatl_frameworks = serializers.SerializerMethodField(read_only=True) def get_toatl_frameworks(self, language): return language.frameworks.count() def get_total_technology(self, language): return language.technology.count() # change 'technology' with corresponding "related_name" value class Meta: model = Language fields = (other_fileds, 'total_technology', 'toatl_frameworks') depth = 1
accepted answer of: http://stackoverflow.com/q/52639457

http://stackoverflow.com/comment/92247286
type: AnswerComment
has text: Replace that line with `output = img_filename.split('.')[0].split('_')` and do a `print output` right after to see what you are getting from that command.
comment on: http://stackoverflow.com/a/52658312
type: Comment
score: 0

http://stackoverflow.com/comment/92326051
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52699803
has text: So you replace the second part of the tuple with `y_new`? What happens with the "old" second item?
score: 0

http://stackoverflow.com/comment/92337623
type: Comment
type: QuestionComment
has text: The question marked as duplicate appears not to reference namespaces. How can I make that more clear in my question?
comment on: http://stackoverflow.com/q/52705108
score: 0

http://stackoverflow.com/comment/92203828
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52635228
has text: Oh, my God, I'm so sorry. I have not seen it. Thank you @BryanOakley

http://stackoverflow.com/q/52616773
tagged with: python
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92167894
has title: Pyspark: rdd in json object
tagged with: pyspark
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92167967
has body: This is homework assignment hw2-files-10mb.txt is json data rdd = sc.textFile('./hw2-files-10mb.txt') rdd = rdd.map(json.loads) Output of rdd.take(1): [{'created_at': 'Tue Feb 23 17:42:31 +0000 2016', 'user': {'id': 470520068, 'id_str': '470520068', 'name': 'Marni Halasa', 'screen_name': 'MarniHalasa1', 'location': 'NYC', ....] Question: 1) How to select 'id_str' in 'user' in rdd way? I tried the method to map the rdd to the func which return field_list = ['user.id_str'] but it is not working. field_list = ['user.id_str', 'text'] def f(x): d = {} for k in x: if k in field_list: d[k] = x[k] return d rdd1 = rdd.map(f) Output: [{'text': "I'm voting 4 #BernieSanders bc he doesn't ride a CAPITALIST PIG adorned w/ #GoldmanSachs $. SYSTEM RIGGED CLASS WAR"}] 2) How to remove the tweet where 'created_at' field is not exist? My codes below is not working. It returns error when i use rdd.count() rdd = rdd.filter(lambda row: row['created_at'] is not None) My expected output: 1) Remove all the broken tweets ('created_at' field is empty) 2) a pair RDD of (user_id, text), where user_id is the 'id_str' data field of the user dictionary. Thanks.
has answer: http://stackoverflow.com/a/52640558
favorite count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/92385745
score: 0
type: QuestionComment
type: Comment
has text: I don't have an answer for you right off hand, but try out `dateutil.parser` like so: `from dateutil.parser import parse; _date = parse('Sat, 26 Nov 2016 15:17:00 +0000')`
comment on: http://stackoverflow.com/q/52730311

http://stackoverflow.com/q/52625233
favorite count: 0
tagged with: iteration
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52625382
has body: Using Python3, I need to iterate over the list of elements sequentially starting from an arbitrary i (i &lt;= 6), complete the full iteration cycle, repeat it starting with i += 1 and so on. This cycle should not end. In content, this is the getting of the names of the days of the week, starting with the current one. For example, if today is Wednesday, as a result of iterations I have to get a list [Wednesday, Thursday, Friday, Saturday, Sunday, Monday, Tuesday]. It seems to be quite simple, but I am at a dead end. I will be grateful for the hint or help.
tagged with: python
has answer: http://stackoverflow.com/a/52625580
has title: Iteration over list with shifting starting point
answer count: 4
type: AnsweredQuestion
tagged with: list
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/52625382
score: -2
has answer: http://stackoverflow.com/a/52625534
has answer: http://stackoverflow.com/a/52625670
possible better answer: http://stackoverflow.com/a/52625534
upvote count: 0

floating-point
tags question: http://stackoverflow.com/q/52736698
tags question: http://stackoverflow.com/q/52686490
type: Tag
tags question: http://stackoverflow.com/q/52612150
tags question: http://stackoverflow.com/q/52600983
tags question: http://stackoverflow.com/q/52611557
tags question: http://stackoverflow.com/q/52649052
tags question: http://stackoverflow.com/q/52684644
tag name: floating-point

http://stackoverflow.com/q/52742118
has answer: http://stackoverflow.com/a/52742344
has title: Get previous business day in a DataFrame
score: 13
tagged with: calendar
has body: I have a DataFrame with two columns, a date and a category. I want to create a new date column according to the rule: if category is B then the value should the business day closest to the date (only from the past or the day itself), else it's the value of the date column itself. I define business day as any day which isn't on a weekend, nor present in the list holidays defined in the minimal example below. Please consider the following DataFrame df: import datetime as dt import pandas as pd from IPython.display import display holidays = [dt.datetime(2018, 10, 11)] df = pd.DataFrame({"day": ["2018-10-10", "2018-10-11", "2018-10-12", "2018-10-13", "2018-10-14", "2018-10-15" ], "category":["A", "B", "C", "B", "C", "A"] } ) df["day"] = pd.to_datetime(df.day, format="%Y-%m-%d") display(df) day category 0 2018-10-10 A 1 2018-10-11 B 2 2018-10-12 C 3 2018-10-13 B 4 2018-10-14 C 5 2018-10-15 A How do I get a third column whose values are the ones listed below? 2018-10-10 2018-10-10 2018-10-12 2018-10-12 2018-10-14 2018-10-15 I have a created a function that finds the last business day when working with lists, if that's any help. # creates a list whose elements are all days in the years 2017, 2018 and 2019 days = [dt.datetime(2017, 1 , 1) + dt.timedelta(k) for k in range(365*3)] def lastt_bus_day(date): return max( [d for d in days if d.weekday() not in [5, 6] and d not in holidays and d &lt;= date ] ) for d in df.day: print(last_bus_day(d)) #prints 2018-10-10 00:00:00 2018-10-10 00:00:00 2018-10-12 00:00:00 2018-10-12 00:00:00 2018-10-12 00:00:00 2018-10-15 00:00:00
type: Question
has answer: http://stackoverflow.com/a/52743136
has answer: http://stackoverflow.com/a/52742715
has answer: http://stackoverflow.com/a/52742505
accepted answer: http://stackoverflow.com/a/52743136
tagged with: pandas
has answer: http://stackoverflow.com/a/52742568
downvote count: 0
favorite count: 0
tagged with: python-3.x
answer count: 5
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/92410899
possible better answer: http://stackoverflow.com/a/52742344
upvote count: 13
type: AnsweredQuestion

http://stackoverflow.com/comment/92230985
type: Comment
has text: Well at the moment it will error because `fruit` isn't defined. Is there more to this code?
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52649558

http://stackoverflow.com/a/52693754
answers question: http://stackoverflow.com/q/52693715
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The easiest way is to catch the error and then set the value to None in an except block. try: rating = int(request.POST['rating']) except ValueError: rating = None article = Article( name = request.POST['name'], rating = rating, ) article.save()
accepted answer of: http://stackoverflow.com/q/52693715
score: 1
upvote count: 1

http://stackoverflow.com/q/52600897
has title: python average array when value are over a threshold (average if)
accepted answer: http://stackoverflow.com/a/52600917
tagged with: numpy
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/92136150
answer count: 2
tagged with: mean
tagged with: arrays
has body: I have a 1D array and I want to get the average for all value which are more than a certain threshold. In excel the equivalent would be = AVERAGEIF(range,"&gt;6") In python, I came up with this lines which works fine, but i was wondering if there is a nicer way to write it a = np.array([5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 1.0, 2.0, 3.0, 4.0]) indice = 6 b = sum(i for i in a if i &gt; indice)/sum(a &gt; indice) print b &gt;&gt;&gt; 8.0 If there any smarter way to do this, or using some numpy function? Thanks
downvote count: 0
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52600917
upvote count: 2
possible better answer: http://stackoverflow.com/a/52601044
type: Question
has answer: http://stackoverflow.com/a/52601044

data-visualization
tags question: http://stackoverflow.com/q/52727937
tags question: http://stackoverflow.com/q/52730204
tags question: http://stackoverflow.com/q/52705037
tag name: data-visualization
tags question: http://stackoverflow.com/q/52638897
type: Tag

http://stackoverflow.com/a/52637619
has comment: http://stackoverflow.com/comment/92246168
score: 2
answers question: http://stackoverflow.com/q/52637307
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92238190
has comment: http://stackoverflow.com/comment/92210339
upvote count: 2
has comment: http://stackoverflow.com/comment/92234908
has comment: http://stackoverflow.com/comment/92234185
has body: The order on the axis is determined entirely by the order of factors in the plot range: If you want the factors to appear on the axis in a different order, you must simply sort this list to whatever order you want, and re-assign to the range: p.x_range.factors = sorted_factors For your case, here is one way to do it (I'm not a Pandas expert, there are probably much better ways): desc = group.describe() low_cities = desc.Murder['mean']['low'].index low_sorted = [('low', city) for city in sorted(low_cities, key=lambda x: desc.Murder['mean'][('low',)][x])] high_cities = desc.Murder['mean']['high'].index high_sorted = [('high', city) for city in sorted(high_cities, key=lambda x: desc.Murder['mean'][('high',)][x])]
has comment: http://stackoverflow.com/comment/92210376
type: Answer
accepted answer of: http://stackoverflow.com/q/52637307

http://stackoverflow.com/comment/92344592
score: 0
has text: Post some code attempt and we'll guide you to the right way.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52709166

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/52610368
tags question: http://stackoverflow.com/q/52634441
tags question: http://stackoverflow.com/q/52648045

http://stackoverflow.com/comment/92176561
has text: Answer my self : `df[column_order ]`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52621123
type: QuestionComment

http://stackoverflow.com/q/52700904
score: 1
tagged with: evaluation
has comment: http://stackoverflow.com/comment/92328371
type: Question
has body: Is it safe to rely on condition evaluation order in if statements? The above question asks exactly what I would like to know but is the same true of Pandas &amp; and | operator when performing conditional selection. Thankyou. Edit: So this behaviour does not occur with pandas but is there any way one can achieve it?
has comment: http://stackoverflow.com/comment/92328428
has comment: http://stackoverflow.com/comment/92328527
linked to: http://stackoverflow.com/q/752373
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92328204
duplicate of: http://stackoverflow.com/q/22646463
has title: Pandas order of operation in & and | conditionals in short circuit evaluation
tagged with: pandas
has comment: http://stackoverflow.com/comment/92328332
tagged with: python
has comment: http://stackoverflow.com/comment/92328404
answer count: 0
type: UnansweredQuestion
tagged with: subset
linked to: http://stackoverflow.com/q/22646463
tagged with: conditional-statements
downvote count: 0

http://stackoverflow.com/q/52740254
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/92405101
tagged with: dataframe
type: Question
upvote count: 0
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/52740381
favorite count: 0
has title: Split dataset in train and set validation. Why this error?
has body: I have to split my dataset into train and set validation (70 and 30%) I used this code: def get_train_test(df, y_col, x_cols, ratio): """ This method transforms a dataframe into a train and test set, for this you need to specify: 1. the ratio train : test (usually 0.7) 2. the column with the Y_values """ mask = np.random.rand(len(df)) &amp;lt; ratio df_train = df[mask] df_test = df[~mask] Y_train = df_train[y_col].values Y_test = df_test[y_col].values X_train = df_train[x_cols].values X_test = df_test[x_cols].values return df_train, df_test, X_train, Y_train, X_test, Y_test y_col_glass = 'Type' x_cols_glass = list(df_glass.columns.values) x_cols_glass.remove(y_col_glass) train_test_ratio = 0.7 df_train, df_test, X_train, Y_train, X_test, Y_test = get_train_test(df_glass, y_col_glass, x_cols_glass, train_test_ratio) but I have error on y_col_glass and ratio. Please help! This is the error File "/Users/blabla/.py", line 120, in &lt;module&gt; x_cols_glass.remove(y_col_glass) line 1576, in __nonzero__ .format(self.__class__.__name__)) ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
tagged with: pandas
answer count: 1
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/92405032
has comment: http://stackoverflow.com/comment/92405026

http://stackoverflow.com/q/52630730
has comment: http://stackoverflow.com/comment/92199910
has body: The scenario is: I have 2 tables: today_version (storing everyday latest info) and history_version (whenever before a record in today_version is changed, the old record will first be inserted into history_version for backup, and get changed in today_version). They are created by: CREATE TABLE IF NOT EXISTS today_version ( region TEXT, instance TEXT, version TEXT, last_update_time TEXT, PRIMARY KEY (region, version) ) CREATE TABLE IF NOT EXISTS history_version ( region TEXT, instance TEXT, version TEXT, last_update_time TEXT ) For everyday, there are 2 possible changes in today_version: insert a new record (PRIMARY KEY not found), or, update the version &amp; last_update_time (PRIMARY KEY exists). So my python/pandas code here becomes: df = pd.read_csv("data.csv") query = '''insert or replace into today_version (region, instance, version, last_update_time) values (?,?,?,?,?)''' conn.executemany(query, df.to_records(index=False)) This part is valid and I have checked in terminal by: $ sqlite3 $ &gt; select * from today_version; ...... (record) Then, I would like to use TRIGGER to achieve the part: (whenever a record in today_version is changed, it will be inserted into history_version for backup). However, from CREATE TRIGGER, only "insert", "delete", "update" is supported for trigger, where "replace" is actually first delete this row then insert a new one. May I ask that how can I achieve this requirement? Currently I am trying out the following but didn't work (gives out empty table): CREATE TRIGGER add_history BEFORE DELETE ON today_version WHEN new.version != old.version BEGIN INSERT INTO history_version (market, instance, version, last_update_time) VALUES (old.market, old.instance, old.version, old.last_update_time); END;
score: 0
tagged with: pandas
tagged with: sql
tagged with: sqlite
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92207682
answer count: 0
has title: python sqlite3 trigger before "REPLACE"
type: Question

http://stackoverflow.com/q/52677230
has comment: http://stackoverflow.com/comment/92283729
type: Question
has comment: http://stackoverflow.com/comment/92283435
has comment: http://stackoverflow.com/comment/92284057
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92283568
has comment: http://stackoverflow.com/comment/92283492
has comment: http://stackoverflow.com/comment/92283782
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92290539
has comment: http://stackoverflow.com/comment/92283724
accepted answer: http://stackoverflow.com/a/52677501
tagged with: python
type: AnsweredQuestion
has title: Should I use a singleton for my console game?
has body: I'm writing my first time in python - a console game. I reached the point where I have to make the decision wheter I should use singletons or not. The situation: I have classes like (for example) Character. If you begin a new game, character creation starts (name your character, ...) After creating a character, I create an object from Character class character = Character(name, foo, bar) The problem: When I need the character obj in other functions / classes later (for example to save it to a json file), I have to get access to the initially created object. I will never need multiple player objects Now I'm wondering if i should use singleton(s) or if i should always pass my object to places where I need it. Another option would be to store variables in a module and import the module if i need to get data. So what do you think?
has answer: http://stackoverflow.com/a/52677501

http://stackoverflow.com/a/52629508
upvote count: 1
downvote count: 1
score: 0
has body: There are lots of things need to optimize in your code. Please have a look at this sample: def myfunction(must_print): if must_print: print("Done") else: print("Change value") if __name__ == "__main__": myfunction(True)
answers question: http://stackoverflow.com/q/52629441
type: Answer
has comment: http://stackoverflow.com/comment/92192661

http://stackoverflow.com/comment/92383670
comment on: http://stackoverflow.com/q/52729207
score: 0
type: Comment
type: QuestionComment
has text: yes python script is running apschedular

http://stackoverflow.com/a/52606299
has comment: http://stackoverflow.com/comment/92146605
has comment: http://stackoverflow.com/comment/92146696
has body: sorted(zip(Sorted_Array,Input), key=lambda pair: pair[0]) sort the result based on the key, the first member of the pair, from which you extracted the second member &gt;&gt;&gt;&gt; Output = [x for x in sorted(zip(Sorted_Array,Input), key=lambda pair: pair[0])] &gt;&gt;&gt;&gt; print(Output) [('1M', '7Y'), ('3M', '1Y'), ('Historic Rate', '6M'), ('Overnight', '2Y')] &gt;&gt;&gt;&gt; Output = [x for _, x in sorted(zip(Sorted_Array,Input), key=lambda pair: pair[0])] &gt;&gt;&gt;&gt; print(Output) ['7Y', '1Y', '6M', '2Y'] you need to change the key to pair[1] &gt;&gt;&gt;&gt; Output = [x for _, x in sorted(zip(Sorted_Array,Input), key=lambda pair: pair[1])] &gt;&gt;&gt;&gt; print(Output) ['1Y', '2Y', '6M', '7Y']
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52606057

http://stackoverflow.com/q/52677330
tagged with: python
has comment: http://stackoverflow.com/comment/92283687
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/92284018
type: Question
tagged with: multiprocessing
has title: Multiprocessing.dummy.Pool has only one worker running
has comment: http://stackoverflow.com/comment/92299864
tagged with: pool
has comment: http://stackoverflow.com/comment/92283685
linked to: http://stackoverflow.com/q/26432411
has comment: http://stackoverflow.com/comment/92283783
type: UnansweredQuestion
has body: I have created a class in which I store several large dictionaries and a method that takes as input a file and process it using the informations contained in the dictionaries. Now, the total amount of files that I have to process is around 18000 so I opted to use a multiprocessing.dummy.Pool in this way: with dummy.Pool(processes=50) as pool: failed = [x for x in pool.imap(export.get_uniref_uniprotkb_from_panproteome, species, chunksize=300)] What I noticed in htop is that the main process spawns correctly 50 threads but only one is in running state even I change the chunksize.

http://stackoverflow.com/comment/92196937
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52631700
has text: I know its wrong logic but I am new to python so trying to learn by experimenting.
score: 0

http://stackoverflow.com/a/53704003
downvote count: 0
type: Answer
upvote count: 16
score: 16
has body: Django 2.1.* requires MySQL 5.6 or higher. It broke the compatibility by mapping DateTimeField to datetime(6). You can patch Django MySQL data type mapper. Put this to the top of your settings.py from django.db.backends.mysql.base import DatabaseWrapper DatabaseWrapper.data_types['DateTimeField'] = 'datetime' # fix for MySQL 5.5
answers question: http://stackoverflow.com/q/52730817

http://stackoverflow.com/comment/92205548
type: QuestionComment
type: Comment
has text: @BryanOakley I do have three frames one as a root, the characterFrame = Character Window, planetFrame = Planet Window. I have the scroll implemented but not as a frame and the Menu bar wouldn't be a frame either.
comment on: http://stackoverflow.com/q/52634921
score: 0

http://stackoverflow.com/q/52622716
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92179095
has comment: http://stackoverflow.com/comment/92181674
tagged with: python
has body: I am trying to create a bot for auto trade binary for IQO. I wanted to have a human like feeling. Hence, I decided to use Selenium with Chrome Browser. I was not getting a start, hence tried the following script but found errors: #!/usr/bin/python # -*- coding: utf8 -*- __author__ = 'Testing' from win32gui import FindWindow, FindWindowEx, SendMessage from win32con import EM_GETLINE import random from struct import pack from time import localtime, strftime, sleep 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 NoSuchElementException, ElementNotVisibleException from optparse import OptionParser #Config URL = 'https://iqoption.com/en' TITLE_ENG = 'Alert' WINDOW_ID = '#32770' TIMEOUT = 10 BUY_TEXT = 'Buy' SELL_TEXT = 'Sell' TURBO = 'Турбо опцион' BIN = 'Бинарный опцион' TEST_MESSAGES = ['Buy', 'Sell'] MODES = ['test', 'real', 'demo'] #Locators LOGIN_BUTTON = '//button[@ng-click="login()"]' EMAIL = '//input[@name="email"]' PASSWORD = '//input[@name="password"]' SUBMIT = '//button[@type="submit"]' BUY_UP_BUTTON = '//button[contains(@ng-click,"call")]' BUY_DOWN_BUTTON = '//button[contains(@ng-click,"put")]' BUY_UP_CONFIRM_BUTTON = '//button[contains(@ng-show, "call")][text()="Купить"]' BUY_DOWN_CONFIRM_BUTTON = '//button[contains(@ng-show, "put")][text()="Купить"]' CONTINUE_DEMO_BUTTON = """//button[contains(@ng-click, "opt.game.newRate()")] [text()="Продолжить демо-торги"]""" CONTINUE_REAL_BUTTON = """//button[contains(@ng-click, "opt.game.newRate()")] [text()="Новый опцион"]""" BALANCE = '//a[contains(@value,"user.profile.balance")]' CLOSE_BUTTON = '//button[@ng-click="close()"][text()="Закрыть"]' NAV_BAR = 'bs-example-navbar-collapse-1' TURBO_BUTTON = '//a[@href="/ru/options/turbo"]' BIN_BUTTON = '//a[@href="/ru/options/binary"]' LANG_CNTRL = '//ul[@ng-controller="ChangeLangCtrl"]' DROP…
has comment: http://stackoverflow.com/comment/92181461
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/92181312
tagged with: selenium
has title: software with selenium giving assert python3
type: Question
has comment: http://stackoverflow.com/comment/92179451
has comment: http://stackoverflow.com/comment/92181497
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/92179309
favorite count: 0

http://stackoverflow.com/a/52700673
score: 0
type: Answer
has body: demo:db&lt;>fiddle Since I am not really into SQLAlchemy I can show you the pure Postgres way: SELECT datetime::date, category, COUNT(*) FROM simple_table GROUP BY datetime::date, category There is no problem to do it with weeks using EXTRACT (https://www.postgresql.org/docs/current/static/functions-datetime.html) WITH weeks AS ( SELECT EXTRACT(week from datetime) as week, category FROM simple_table ) SELECT week, category, COUNT(*) FROM weeks GROUP BY week, category
answers question: http://stackoverflow.com/q/52699990

http://stackoverflow.com/a/52642647
has body: You can see that the first element of your empty list is shared across all the values in your dictionary: &gt;&gt;&gt; id(empty[0]) == id(status['a'][0]) == id(status['b'][0]) == id(status['c'][0]) True They each share the same memory location. The same is also true for the second item in the empty list, id(empty[1]) == id(status['a'][1]) == ... The reason for this is your assignment of your empty list to each value. You can either perform a deep copy this empty, nested list, or else use a list comprehension to generate new ones for each key in your dictionary. This list comprehension for the empty list creation is itself done within a dictionary comprehension to generate your status variable for all the required keys. empty_rows = 2 empty_cols = 2 keys = ['a', 'b', 'c'] status = {k: [[False] * empty_cols for _ in range(empty_rows)] for k in keys} # Example usage: status['a'][0][0] = True &gt;&gt;&gt; status {'a': [[True, False], [False, False]], 'b': [[False, False], [False, False]], 'c': [[False, False], [False, False]]} Now you can change any element without it affecting the others.
type: Answer
answers question: http://stackoverflow.com/q/52642538
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/92221629
downvote count: 0

http://stackoverflow.com/comment/92398262
type: Comment
score: 1
has text: you need to call `.get()` instead of `.filter()` on Queryset on `a.page_set`
type: QuestionComment
comment on: http://stackoverflow.com/q/52736737

http://stackoverflow.com/comment/92288739
type: AnswerComment
score: 0
type: Comment
has text: Actually, I was looking for an algorithm. Shouldn't use any internal/external libraries.
comment on: http://stackoverflow.com/a/52680086

http://stackoverflow.com/q/52636783
upvote count: 5
score: 4
has answer: http://stackoverflow.com/a/54671399
has comment: http://stackoverflow.com/comment/92207387
has title: figsize does not work for matplotlib 3d plot
answer count: 3
has body: I plotted 2 figures, here is the screenshot figsize the one (2D) on top is rendered as expected. the one (3D) on bottom is not, the figure is so small! setting the value of figsize does not work. figsize=(3,3) and figsize=(13,13) give the same result! %matplotlib inline rendered same way. I tried different browsers, clear the cache, dose not work either. I guess some rcParams control this, because this is reproducible only on my mac, but I don't have a clue to find it! any clue will be appreciated. whole coding: %pylab inline from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(3,3)) ax = fig.gca(projection='3d') ax.scatter(0.5, 0.5, 0.5, marker = '^')
has answer: http://stackoverflow.com/a/52768025
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92207708
tagged with: python
has comment: http://stackoverflow.com/comment/92206945
has comment: http://stackoverflow.com/comment/92207183
tagged with: matplotlib
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/54498537
has comment: http://stackoverflow.com/comment/92207331

http://stackoverflow.com/a/52613266
type: Answer
answers question: http://stackoverflow.com/q/52612982
score: 2
accepted answer of: http://stackoverflow.com/q/52612982
upvote count: 2
has body: Concatenate and use sorted queue1 = ["a","d","x"] queue2 = ["b","c","y","z"] queue3 = sorted(queue1 + queue2) ['a', 'b', 'c', 'd', 'x', 'y', 'z']
has comment: http://stackoverflow.com/comment/92161046
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92415005
has text: `1000.0 // 100`
score: 5
comment on: http://stackoverflow.com/q/52745166
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92334409
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/52663756
has text: Have you enabled gremlin-python on the server by running `./bin/gremlin-server.sh -i org.apache.tinkerpop gremlin-python x.x.x`, see the section "Connecting with Python" from this [blog post](https://medium.com/@BGuigal/janusgraph-python-9e8d6988c36c)

http://stackoverflow.com/comment/92284619
type: Comment
comment on: http://stackoverflow.com/a/52677133
has text: Perhaps bitstring is not installed. Use pip to install, thereafter it should work just fine.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52686748
type: AnsweredQuestion
downvote count: 0
type: Question
has body: Comparing today date with date in dataframe Sample Data id date 1 1/2/2018 2 1/5/2019 3 5/3/2018 4 23/11/2018 Desired output id date 2 1/5/2019 4 23/11/2018 My current code dfdateList = pd.DataFrame() dfDate= self.df"id", "date" today = datetime.datetime.now() today = today.strftime("%d/%m/%Y").lstrip("0").replace(" 0", "") expList = [] for dates in dfDate["date"]: if dates &lt;= today: expList.append(dates) dfdateList = pd.DataFrame(expList) Currently my code is printing every single line despite the conditions, can anyone guide me? thanks
score: 1
tagged with: dataframe
tagged with: python-2.7
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has title: Comparing today date with date in dataframe
has answer: http://stackoverflow.com/a/52687024
accepted answer: http://stackoverflow.com/a/52687024
tagged with: datetime
tagged with: python

http://stackoverflow.com/a/52590846
answers question: http://stackoverflow.com/q/52590564
has comment: http://stackoverflow.com/comment/92125595
score: 0
has comment: http://stackoverflow.com/comment/92125260
type: Answer
has comment: http://stackoverflow.com/comment/92125282
has comment: http://stackoverflow.com/comment/92125853
has body: If you are only interested in the words of the string to process, we can perform a match linear in the number of characters of the dictionary, with: filter(None, map(LANGUAGE_TO_ISO.get, book_title.split())) This will contain a list of ISO codes for matched words (so we do not match 'en' in the word 'men'). For example: &gt;&gt;&gt; book_title = "The Dark Tower - eng" &gt;&gt;&gt; list(filter(None, map(LANGUAGE_TO_ISO.get, book_title.split()))) ['en'] We can - if we want to - make it even more or less case sensitive (for some special cases, for example characters without a lowercase variant, this will not work) with: filter(None, map(LANGUAGE_TO_ISO.get, book_title.lower().split())) (given the keys in the dictionary are all lowercase). If you however want to be able to parse substrings (like 'en' in 'men'), then you may want to look for a parser (a parser works linear in the input as well, and acts like an annotated finite state machine). Python splits words according to spaces, but dots, etc. will not separate the words. You can however split those with for example a regex, like: import re splt = re.compile('\W+') filter(None, map(LANGUAGE_TO_ISO.get, splt.split(book_title))) Or based on your edit: Either a dot, comma, hyphen, space, ... You can list the characters between square brackets: import re splt = re.compile('[\s.,-]+') filter(None, map(LANGUAGE_TO_ISO.get, splt.split(book_title)))
has comment: http://stackoverflow.com/comment/92125688

http://stackoverflow.com/comment/92193320
type: AnswerComment
comment on: http://stackoverflow.com/a/52612152
score: 0
type: Comment
has text: This is what I am plotting

http://stackoverflow.com/a/52644058
has body: You can try numpy.genfromtxt, like: import numpy as np data = np.genfromtxt("C:/Marine/lookup/distinct_lookup_scales.csv", delimiter = ",", skip_header = 1) minzooms = data[:,0] maxzooms = data[:,1]
type: Answer
answers question: http://stackoverflow.com/q/52643870
score: 0
has comment: http://stackoverflow.com/comment/92222115

http://stackoverflow.com/q/52653043
has title: Pandas Series.map equivalent in NumPy
has body: I have a dictionary of lookup of values dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 3} The result I want from numpy is what pandas.Series.map() returns after passing in the dictionary. Eg series.map(dictionary, na_action='ignore') NOTE: This series.map() function is extremely fast which makes me believe there must be an equivalent in the numpy API rather than me implementing some solution involving numpy.where() and for looping through the dictionary keys.
tagged with: numpy
score: 5
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52653438
tagged with: python
accepted answer: http://stackoverflow.com/a/52653438
has comment: http://stackoverflow.com/comment/92238817
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35215161
linked to: http://stackoverflow.com/q/16992713
type: Question
upvote count: 5

http://stackoverflow.com/q/52647684
has comment: http://stackoverflow.com/comment/92227700
upvote count: 0
has body: I have some images for which I also have their mask (green in the picture). I am producing a bounding box (dot line in the picture) around the object, and take only this part of the image. Now I would like to replace the gray part with pixel that extend the car color in the most natural way. For example, taking the same color as the closest car pixel. At the end I would like to have an image with all the car details but without any shape anymore. I tried to simple inverse the mask, so that the mask represent the gray pixel around the car, and then use the 'inpaint' function from opencv to paint this new mask with adequate color: result = cv2.inpaint(car_image,new_mask,50,cv2.INPAINT_NS) Its not working well as we clearly still see the borders all around the car. Any hints would be greatly appreciated. I am working on python and it would need to be quite efficient as I have a huge number of images.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92228914
has answer: http://stackoverflow.com/a/52724436
tagged with: mask
score: -1
tagged with: image-processing
accepted answer: http://stackoverflow.com/a/52724436
has comment: http://stackoverflow.com/comment/92228608
has comment: http://stackoverflow.com/comment/92227486
type: Question
has title: keeping all details of object removing the shape in the smoothest and most efficient way
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92228827
tagged with: python

http://stackoverflow.com/a/52745223
has body: Cheapest way is AWS Lambda, but you'll have to get rid of the bash script and modify your Python script some. Easiest way is EC2, because it's just a Linux server that you can login to and install whatever you want and setup your script on a cron job just like your local Linux server.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52745181
upvote count: 2
score: 2

http://stackoverflow.com/a/52630624
downvote count: 0
has body: You can rename columns, pd.melt and then sort_values: df.columns = [i if not i.startswith('Week') else int(i[-1]) for i in df] res = pd.melt(df, id_vars='Shop', var_name='Week', value_name='Hour')\ .sort_values('Shop').reset_index(drop=True) print(res) Shop Week Hour 0 1 1 15 1 1 2 5 2 2 1 25 3 2 2 44 ... 16 9 2 81 17 9 1 76 18 10 1 62 19 10 2 46
accepted answer of: http://stackoverflow.com/q/52630427
answers question: http://stackoverflow.com/q/52630427
upvote count: 2
has comment: http://stackoverflow.com/comment/92194853
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/a/52602325
accepted answer of: http://stackoverflow.com/q/52601707
has comment: http://stackoverflow.com/comment/92161814
has comment: http://stackoverflow.com/comment/92161714
has comment: http://stackoverflow.com/comment/92161910
has comment: http://stackoverflow.com/comment/92139059
has comment: http://stackoverflow.com/comment/92160966
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92152324
has body: You can use pandas string methods to extract the last two numbers df1['PARID'].str.extract('.*(\d{2})', expand = False) You get 0 31 1 31 2 13 3 13 4 31
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/92152253
has comment: http://stackoverflow.com/comment/92161805
answers question: http://stackoverflow.com/q/52601707
has comment: http://stackoverflow.com/comment/92160942
score: 3

http://stackoverflow.com/comment/92286446
has text: Nice of people to downvote without reasoning... but it would help to know some more information. How are you saving the variables to a file (as in what format)? The `sorted` function can be used to order a list in Python, this may be of use
type: Comment
comment on: http://stackoverflow.com/q/52678722
type: QuestionComment
score: 0

http://stackoverflow.com/q/52650442
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92232878
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92234731
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/92232872
has comment: http://stackoverflow.com/comment/92232828
has body: Is there a variable type that is a list but also a single value unless index is specified? var = [1, 2, 3] print var print var[1] Output 1 2 The purpose is for my automation script. I have a method that is used in two ways: toggle.find(get_cell("Sounds")) click(get_cell("Sounds")) In the first case, toggle will use the list of values get_cell returns to retry look up In the second case, click just wants to use the first value in the list
has comment: http://stackoverflow.com/comment/92232908
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/92233132
type: Question
has answer: http://stackoverflow.com/a/52651853
has comment: http://stackoverflow.com/comment/92232923
has title: Use first item unless specified
score: -1
has answer: http://stackoverflow.com/a/52650758
has comment: http://stackoverflow.com/comment/92232846
has answer: http://stackoverflow.com/a/52650866
answer count: 3
has comment: http://stackoverflow.com/comment/92232830
has comment: http://stackoverflow.com/comment/92232835
favorite count: 0

http://stackoverflow.com/a/52612028
score: 0
has body: You can use df['base'].apply(lambda x: x.pop(1)). Note that pop acts in place, so you don't need to assign the result to base (in fact, if you do so, you'll get the removed element instead of the remaining list). However, as @jpp says, you should consider using some other data structure, such as a dataframe with multi-index or a three-dimensional numpy array. And considering your edit, it's probably easier to convert the data to a dataframe with multiple columns, and then delete the extra column, rather than trying to manipulate a column of lists and then turn it into your final dataframe. It may seem simpler to have "only one column", but you're just putting the extra complexity into a separate layer, rather than getting rid of it. Pandas was built around two-dimensional data being represented as columns and rows, not a single column of lists, so you're going out of your way to not use the tools that pandas was built to provide. Presumably, you had something like this: data=[['a','b','c'], ['c','d','e'], ['a','b','h']] And you did something like this: df = pd.DataFrame({'base':data}) You should instead do df = pd.DataFrame(data) df = df[[0,2]]
answers question: http://stackoverflow.com/q/52611213
type: Answer

http://stackoverflow.com/comment/92298416
comment on: http://stackoverflow.com/q/52635688
score: 0
has text: https://stackoverflow.com/questions/41059144/running-chromedriver-with-python-selenium-on-heroku
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52614996
type: AcceptedAnswer
downvote count: 0
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/52598366
accepted answer of: http://stackoverflow.com/q/52598366
score: 9
has body: For string I have three values- passed, failed and null. How do I replace those nulls with 0? fillna(0) works only with integers First, import when and lit from pyspark.sql.functions import when, lit Assuming your DataFrame has these columns # Reconstructing my DataFrame based on your assumptions # cols are Columns in the DataFrame cols = ['name', 'age', 'col_with_string'] # Similarly the values vals = [ ('James', 18, 'passed'), ('Smith', 15, 'passed'), ('Albie', 32, 'failed'), ('Stacy', 33, None), ('Morgan', 11, None), ('Dwight', 12, None), ('Steve', 16, 'passed'), ('Shroud', 22, 'passed'), ('Faze', 11,'failed'), ('Simple', 13, None) ] # This will create a DataFrame using 'cols' and 'vals' # spark is an object of SparkSession df = spark.createDataFrame(vals, cols) # We have the following DataFrame df.show() +------+---+---------------+ | name|age|col_with_string| +------+---+---------------+ | James| 18| passed| | Smith| 15| passed| | Albie| 32| failed| | Stacy| 33| null| |Morgan| 11| null| |Dwight| 12| null| | Steve| 16| passed| |Shroud| 22| passed| | Faze| 11| failed| |Simple| 13| null| +------+---+---------------+ You can use: withColumn() - To specify the column you want use. isNull() - A filter that evaluates to true iff the attribute evaluates to null lit() - creates a column for literals when(), otherwise() - is used to check the condition with respect to the column I can replace the values having null with 0 df = df.withColumn('col_with_string', when(df.col_with_string.isNull(), lit('0')).otherwise(df.col_with_string)) # We have replaced nulls with a '0' df.show() +------+---+---------------+ | name|age|col_with_string| +------+---+---------------+ | James| 18| passed| | Smith| 15| passed| | Albie| 32| failed| | Stacy| 33| 0| |Morgan| 11| 0| |Dwight| 12| 0| | Steve| 16| passed| |Shroud| 22| passed| | Faze| 11| failed| |Simple| 13| 0| +------+---+---------------+ Part 1 of your question: Yes/No boolean values - you mentioned that, there are 100 columns of Bo…

http://stackoverflow.com/comment/92501446
score: 0
type: Comment
type: QuestionComment
has text: thank u soo much for your time and code I will try and tell u my results..
comment on: http://stackoverflow.com/q/52670151

http://stackoverflow.com/comment/92175150
comment on: http://stackoverflow.com/q/52605238
has text: Possible duplicate of [How to use AWS KMS in AWS lambda](https://stackoverflow.com/questions/32620182/how-to-use-aws-kms-in-aws-lambda)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52649815
has answer: http://stackoverflow.com/a/63606502
downvote count: 0
accepted answer: http://stackoverflow.com/a/63598255
favorite count: 0
has answer: http://stackoverflow.com/a/63578860
answer count: 5
has body: I know how to calculate the Euclidean distance between points in an array using scipy.spatial.distance.cdist Similar to answers to this question: Calculate Distances Between One Point in Matrix From All Other Points However, I would like to make the calculation assuming cyclic boundary conditions, e.g. so that point [0,0] is distance 1 from point [0,n-1] in this case, not a distance of n-1. (I will then make a mask for all points within a threshold distance of my target cells, but that is not central to the question). The only way I can think of is to repeat the calculation 9 times, with the domain indices having n added/subtracted in the x, y and then x&y directions, and then stacking the results and finding the minimum across the 9 slices. To illustrate the need for 9 repetitions, I put together a simple schematic with just 1 J-point, marked with a circle, and which shows an example where the cell marked by the triangle in this case has its nearest neighbour in the domain reflected to the top-left. this is the code I developed for this using cdist: import numpy as np from scipy import spatial n=5 # size of 2D box (n X n points) np.random.seed(1) # to make reproducible a=np.random.uniform(size=(n,n)) i=np.argwhere(a>-1) # all points, for each loc we want distance to nearest J j=np.argwhere(a>0.85) # set of J locations to find distance to. # this will be used in the KDtree soln global maxdist maxdist=2.0 def dist_v1(i,j): dist=[] # 3x3 search required for periodic boundaries. for xoff in [-n,0,n]: for yoff in [-n,0,n]: jo=j.copy() jo[:,0]-=xoff jo[:,1]-=yoff dist.append(np.amin(spatial.distance.cdist(i,jo,metric='euclidean'),1)) dist=np.amin(np.stack(dist),0).reshape([n,n]) return(dist) This works, and produces e.g. : print(dist_v1(i,j)) [[1.41421356 1. 1.41421356 1.41421356 1. ] [2.23606798 2. 1.41421356 1. 1.41421356] [2. 2. 1. 0. 1. ] [1.41421356 1. 1.41421356 1. 1. ] [1. 0. 1. 1. 0. ]] The zeros obviously mark the J points, and the distances are correct (this ED…
has comment: http://stackoverflow.com/comment/112443719
tagged with: python
type: AnsweredQuestion
tagged with: scipy
has title: Fastest code to calculate distance between points in 2D numpy array with cyclic (periodic) boundary conditions
has answer: http://stackoverflow.com/a/63598255
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/46700326
score: 5
tagged with: performance
upvote count: 5
has answer: http://stackoverflow.com/a/63576721
has answer: http://stackoverflow.com/a/52673578
tagged with: distance
possible better answer: http://stackoverflow.com/a/63606502
has comment: http://stackoverflow.com/comment/92234971

http://stackoverflow.com/comment/92124456
type: Comment
type: QuestionComment
has text: Sounds fair. I found i have also installed python 3.7 in my pc
comment on: http://stackoverflow.com/q/52594688
score: 0

http://stackoverflow.com/q/52674271
has answer: http://stackoverflow.com/a/52682975
has answer: http://stackoverflow.com/a/52674332
tagged with: python
has body: I am using Python 3.4.2 on Windows 10 and am just getting into opening and read/writing to files from the Python shell I did this test and got the following error message in spite of the fact that I had created the file beforehand (but not from the shell as that would not work either). Can someone tell me what I haven't taken into consideration here because all my searches tell me this should work. &gt;&gt;&gt; import os &gt;&gt;&gt; helloFile = open('C:\\Users\\jennifer\\Hello.txt') Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; helloFile = open('C:\\Users\\jennifer\\Hello.txt') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\jennifer\\Hello.txt' I did as John Gordon suggested and removed .txt from the pathname and it still didn't work. Here is the directory and path for the file: C:\Users\jennifer\Desktop\Hello Finally, it has opened and will be very aware of the need to call the complete path in the future! Thank you
type: UnansweredQuestion
has title: Opening file in Python 3.4.2 shell
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92278409
has comment: http://stackoverflow.com/comment/92293526
has comment: http://stackoverflow.com/comment/92278192

http://stackoverflow.com/q/52714362
has comment: http://stackoverflow.com/comment/92370246
has comment: http://stackoverflow.com/comment/92354818
has comment: http://stackoverflow.com/comment/92362767
has comment: http://stackoverflow.com/comment/92354545
has comment: http://stackoverflow.com/comment/92360139
linked to: http://stackoverflow.com/q/448271
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92360486
type: UnansweredQuestion
tagged with: python
has title: ImportError: Cannot import name httputil
has comment: http://stackoverflow.com/comment/92464873
has answer: http://stackoverflow.com/a/52717772
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92354487
type: Question
has comment: http://stackoverflow.com/comment/92362101
has comment: http://stackoverflow.com/comment/92360451
has comment: http://stackoverflow.com/comment/92363125
has body: I hava two different files: data_source and util. I import util at data_source like this: from util import HttpUtil But there is some error when I run from util import HttpUtil ImportError: cannot import name HttpUtil How can I solve this? This is the directory structure of the module: enter image description here In util class HttpUtil(object): @staticmethod def request(host, port, method): In data_source import json import urllib import time from util import HttpUtil

http://stackoverflow.com/a/52712599
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: You can install the keyboard package and use the keyboard.on_press method to listen to events of keyboard presses: import keyboard import time import sys def on_press(event): global pos move = event.name if move == "w": pos[0] = (pos[0] + 1) print(pos) elif move == "d": pos[1] = (pos[1] + 1) print(pos) elif move == "x": sys.exit() pos = [0,0] keyboard.on_press(on_press, suppress=True) while True: time.sleep(1)
answers question: http://stackoverflow.com/q/52712142

http://stackoverflow.com/comment/92375306
type: Comment
comment on: http://stackoverflow.com/q/52724255
has text: @JohnGordon Ok: '2.7.12 (default, Dec 4 2017, 14:50:18) \n[GCC 5.4.0 20160609]'. Also my Django debug page says "Python Version: 2.7.12". Thank you
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92325234
score: 0
type: AnswerComment
type: Comment
has text: @TejasJoshi Please note that don't ask for answer modification that is not told in the question.
comment on: http://stackoverflow.com/a/52662618

http://stackoverflow.com/a/52643228
upvote count: 3
has body: The function need to be instance level then only self will contain a record reference. In your example, the function is @api.model type it needs to be in @api.multi hen you will get record in self. In case of @api.model self is representing model. If you are using is JS code in form view widget then you already have current record just try this.field_manager.datarecord and you will get current record.
type: Answer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/52609576

http://stackoverflow.com/comment/92212108
comment on: http://stackoverflow.com/a/52619416
score: 0
has text: @pygo how do I do that?
type: AnswerComment
type: Comment

http://stackoverflow.com/a/68151266
has body: Once you added the imformation of end effector, you can cotr it by using setmotorcontrol or array with inverse kinematiccalculation
answers question: http://stackoverflow.com/q/52717941
upvote count: 1
score: 0
downvote count: 1
type: Answer

http://stackoverflow.com/q/52642508
favorite count: 0
accepted answer: http://stackoverflow.com/a/52642648
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has body: I've been trying to teach myself a little bit about coding and thought a cool project would be to make a DND 5E Character Generator in Python 3.5 for personal use. I've built a simple one so far that'll give you a Class, Gender, Race, and Background. But I really want to flesh it out a ton more over time. Eventually I'd like to have it do everything involved in character creation and type it into a PDF character sheet. But I'm not nearly that far yet. I've managed to hack together something resembling real code that works thus far, now I want to add in Stat Rolling and that's where I need help 'cause I'm flying by the seat of my pants and don't really know what I'm doing. So the way I like to roll stats for characters is to roll 4d6 and drop the lowest die, then add the three remaining numbers together to get a stat number. Then I do that 7 times and drop the lowest number to have a total of 6 stat numbers available to assign to the different stats. I'm not sure how to drop the lowest number and add the remainders together, also not 100% sure how to handle assigning the stats. For now I'm thinking they should probably be assigned automatically at first and then later on I could code in the option to change stuff at the end after presenting the user with a "finished" character. Likewise if I make an automatic version first I could go back later and add the option to do an automatic or guided character creation, and make a guided version that prompts the user to choose each setting as they go along. Anyways, for now I just really need help with how to add the stats up and assign them correctly so any advice you'd have to offer would be greatly appreciated! Here's my code so far: import random gender='female' race='dragonborn' klass='barbarian' background='acolyte' genders = [ 'Female', 'God Damned', 'Male' ] races = [ 'Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 'Half-Orc', 'Halfling', 'Human', 'Tiefling' ] klasses = [ 'Barbarian', 'Bard', 'Cleric', 'Druid', 'Fi…
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/78928671
type: Question
possible better answer: http://stackoverflow.com/a/78928671
score: -1
has answer: http://stackoverflow.com/a/52642648
answer count: 2
has title: Rolling Stats for a DND Character in Python

http://stackoverflow.com/q/52683831
has body: I followed instructions in simmilar thread like: How do you index on a jinja template? but my html template is not working and whole django project is not responding due to this. Error that I'm getting: Error during template rendering. Could not parse the remainder: '[loop.index0]' from 'songs_titles[loop.index0]' My code looks like this: {% if converted_files_urls %} Titles: {{ songs_titles }} {% for n in converted_files_urls %} Download: {{ songs_titles[loop.index0] }} {% endfor %} {% endif %} and the {{ songs_titles }} renders as list, so at least till here it works ok. What am I doing wrong?
tagged with: templates
favorite count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/92295719
upvote count: 1
tagged with: python
tagged with: jinja2
linked to: http://stackoverflow.com/q/20233721
has answer: http://stackoverflow.com/a/52685830
score: 1
type: Question
answer count: 2
has title: Could not parse the remainder: '{{ list[loop.index0] }}'
downvote count: 0
has answer: http://stackoverflow.com/a/52687538
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/92279629
type: QuestionComment
has text: What kind of text is it? More details are always useful.
comment on: http://stackoverflow.com/q/52671775
score: 0
type: Comment

http://stackoverflow.com/comment/92200782
has text: `[tuple(i for i in item if i not in B) for item in A]` ?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52633763

http://stackoverflow.com/comment/92402739
comment on: http://stackoverflow.com/a/52738491
type: AnswerComment
has text: @TM90 So, I considered using a `side_effect` to split on `\n` and return an iterable, but at that point you're basically testing that `__iter__` on `open`'s return value works properly. I think that's a thing you can take for granted and not worry about testing. You want to mock the file for the way you're using it, not completely test `builtins.open`.
score: 0
type: Comment

http://stackoverflow.com/a/52691397
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52691128
type: Answer
upvote count: 1
has body: Here's one way to do it using groupby and pivot: df = df.groupby(['ID', pd.Grouper(key = 'Timestamp', freq = 'W')] ['ID'].count().\ to_frame().rename(columns = {'ID' : 'counts'}).reset_index() Then pivot: df.pivot(index = 'ID', columns = 'Timestamp', values = 'counts') This would ofcourse, return column names as the first day if the respective week; you can change these by replacing df.columns with a list of your desired column names. EDIT: If you already have a column of weeks, you can just use pd.pivot_table without doing a groupby.

c++11
tags question: http://stackoverflow.com/q/52700096
type: Tag
tag name: c++11

http://stackoverflow.com/comment/124843905
type: Comment
comment on: http://stackoverflow.com/a/52593889
score: 2
type: AnswerComment
has text: @soumeng78 If you haven't noticed yet (and can take advantage), Python 3.9 makes `dict` generic, so `dict[ErrorClass, float]` would now work. `Dict` is now deprecated (though I have no idea if there is a timeline for actually removing it).

apache
tag name: apache
tags question: http://stackoverflow.com/q/52693651
tags question: http://stackoverflow.com/q/52669162
tags question: http://stackoverflow.com/q/52675660
tags question: http://stackoverflow.com/q/52638199
tags question: http://stackoverflow.com/q/52668420
type: Tag
tags question: http://stackoverflow.com/q/52592496

http://stackoverflow.com/comment/92308665
type: QuestionComment
comment on: http://stackoverflow.com/q/52617364
score: 0
has text: Like I said it's been a long time, but as I recall the issue is due to the Python interpreter using one version of the C runtime and the extension using another (and the two don't mix). Apparently there are/were some `#pragma` directives in the Python interpreter's source code that control which C runtime dll it uses at runtime. It's possible, of course, that things have changed...but if what you're doing seems to work, why are you even asking this question? I think the solution is to build your own debugging version of the Python interpreter (which requires obtaining all of its source code).
type: Comment

http://stackoverflow.com/comment/92410766
type: Comment
type: QuestionComment
has text: Where did you place your synonyms file?
score: 0
comment on: http://stackoverflow.com/q/52742943

http://stackoverflow.com/a/52595015
score: 1
has body: The many-to-many relationship goes both ways, so you don't need to base everything around authors. class BooksListView(ListView): context_object_name = 'booklist' model = Book template_name = 'Books/books_list.html' And the template: {% for books in booklist %} &lt;li class="list-group-item list-group-item-light"&gt; &lt;h5&gt;{{ book.title }}&lt;/h5&gt; &lt;p&gt; {% for author in book.author_set.all %} {{ author.first_name }} {{ author.last_name }}{% if not forloop.last %}, {% endif %} {% endfor %} &lt;/p&gt; &lt;/li&gt; {% endfor %} Notes: By default, the related_name is {{ModelName}}_set (author_set in this case). If you want something more natural you can set related_name='authors'. There will be a query made to the databse for every book in the list and this can be quite slow with a lot of data, so take a look at prefetch_related().
accepted answer of: http://stackoverflow.com/q/52593967
answers question: http://stackoverflow.com/q/52593967
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/a/52671602
score: 1
accepted answer of: http://stackoverflow.com/q/52671406
answers question: http://stackoverflow.com/q/52671406
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You can do this with a while loop taking player input: #Main import random computer_rps = ['ROCK','PAPER','SCISSORS','SPOCK','LIZARD'] valid_input = False # Make sure to enter at least once while valid_input is False: player_rps = input('Rock, Paper, Scissors, Lizard, or Spock:\t').upper() if player_rps in computer_rps: valid_input = True game_rps = random.choice(computer_rps) #Player if player_rps == 'ROCK': print('Player picked Rock') elif player_rps == 'PAPER': print('Player picked Paper') elif player_rps == 'SCISSORS': print('Player picked Scissors') elif player_rps == 'SPOCK': print('Player picked Spock') elif player_rps == 'LIZARD': print('Player picked Lizard') #Computer if game_rps == 'ROCK': print('Computer picked Rock') elif game_rps == 'PAPER': print('Computer picked Paper') elif game_rps == 'SCISSORS': print('Computer picked Scissors') elif game_rps == 'SPOCK': print('Computer picked Spock') elif game_rps == 'LIZARD': print('Computer picked Lizard') #Output for rock if player_rps == "ROCK" and game_rps == "SCISSORS": print("Rock crushes scissors, the Player wins!") if player_rps == "SCISSORS" and game_rps == "ROCK": print("Rock crushes scissors, the Computer wins!") if player_rps == "ROCK" and game_rps == "PAPER": print("Paper covers rock, the Computer wins!") if player_rps == "PAPER" and game_rps == "ROCK": print("Paper covers rock, the Player wins!") if player_rps == "ROCK" and game_rps == "SPOCK": print("Spock vaporizes rock, the Computer wins!") if player_rps == "SPOCK" and game_rps == "ROCK": print("Spock vaporizes rock, the Player wins!") if player_rps == "ROCK" and game_rps == "LIZARD": print("Rock crushes lizard, the Player wins!") if player_rps == "LIZARD" and game_rps == "ROCK": print("Rock crushes lizard, the Computer wins!") #Output for paper if player_rps == "PAPER" and game_rps == "LIZARD": print("Lizard eats paper, the Computer wins!") if player_rps == "LIZARD" and game_rps == "PAPER": print("Lizard eats paper, the Player wins!") if player…
downvote count: 0

http://stackoverflow.com/a/52598800
answers question: http://stackoverflow.com/q/52596862
has body: Your code needs to return an HttpResponse instance for the case when a request is POST but the form is not valid. Looking at your code, try to move the last lines back one indentation level; that way everything that isn't a POST with a valid form will fall into that last return statement. def reply_post(request, pk): post = ... if request.method == "POST": form = ReplyPostForm(request.POST) if form.is_valid(): ... return redirect("post", post.id) else: form = ReplyPostForm() args = { 'form': form, 'post': post, } return render(request, 'home/replypost.html', args)
accepted answer of: http://stackoverflow.com/q/52596862
type: AcceptedAnswer
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/92174528
has text: Is calling `ps aux | grep a.py | grep -v grep | awk '{print $2}' | xargs kill -9` okay, or do you want to avoid depending on `os.system` or something similar?
comment on: http://stackoverflow.com/q/52620256
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92291051
comment on: http://stackoverflow.com/a/52680763
has text: @user3768971 on it now
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92188122
has text: Ok, thank you. But could you explain how to install python2? I've tried $ sudo apt-get install --reinstall python2 Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package python2 How can I reinstall python2 package? Sorry I'm a newbie at python.. @Florian Weimer
comment on: http://stackoverflow.com/a/52626003
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92389290
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52731094
has text: The `*` operator is unpacking the items from the output of the generator expression so that the items can be passed as individual arguments to the `print` function. You can see https://www.python.org/dev/peps/pep-0448/ for details.

http://stackoverflow.com/comment/92676660
score: 0
comment on: http://stackoverflow.com/a/52864930
type: Comment
type: AnswerComment
has text: Thanks, I just tried running the process on `python 2.7` with `sagemaker==1.11.3` and got the same `NoCredentialsError: Unable to locate credentials` error

http://stackoverflow.com/comment/92346199
type: QuestionComment
has text: Strange. I tried your first example and although my Python code completed without errors it did not create the .bak file. The exact same `BACKUP DATABASE` statement created the .bak file when executed from both SSMS and sqlcmd. Did you verify that the .bak file is created (or appended to) after executing your first example?
comment on: http://stackoverflow.com/q/52686705
score: 0
type: Comment

http://stackoverflow.com/q/52592298
has comment: http://stackoverflow.com/comment/92119583
has answer: http://stackoverflow.com/a/52592842
has comment: http://stackoverflow.com/comment/92120768
has title: send a file from a server to another server use rest framework
has comment: http://stackoverflow.com/comment/92119306
downvote count: 0
answer count: 1
tagged with: django-rest-framework
favorite count: 0
accepted answer: http://stackoverflow.com/a/52592842
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92119911
has body: I have a server that generates a file, I want to send that file to another server, when the file is ready. so the server that receives file should always listen and I have used Django rest framework, does anybody have a link to help me?
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/92119700
has comment: http://stackoverflow.com/comment/92119421
type: Question
has comment: http://stackoverflow.com/comment/92119687
has comment: http://stackoverflow.com/comment/92119540

http://stackoverflow.com/comment/92229059
comment on: http://stackoverflow.com/q/52636191
score: 0
type: Comment
type: QuestionComment
has text: Good point from both of you. @Daniel thanks for pointing out the inefficiency - removing those inner loops got me about a 60x speedup which is more than parallelization can do anyways. @user2357112 do you know of a way to make it thread-safe with numba? I tried `numba.config.THREADING_LAYER = 'threadsafe'`, but that didn't help.

http://stackoverflow.com/comment/92390153
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52732077
has text: You're welcome @user2357112. This was a real lifesaver though. Tested it. works like a charm !!
type: AnswerComment

http://stackoverflow.com/q/52714138
has body: I am reading gmail messages (using the code from accepted answer) (retcode, messages) = conn.search(None, '(UNSEEN)') if retcode == 'OK': for num in messages[0].split(' '): # messages[0] is b'6' in my case. It's throwing, "TypeError: a bytes-like object is required, not 'str'". But I can see clearly its a byte object b'6' Tried same on python shell as well and getting same error there as well. Not sure whats wrong here. &gt;&gt;&gt; b'6'.split(' ') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: a bytes-like object is required, not 'str'
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/52714177
linked to: http://stackoverflow.com/q/13210737
score: 0
answer count: 1
type: UnansweredQuestion
has title: Gmail messages, unable to split message Ids
tagged with: python
tagged with: gmail-imap

http://stackoverflow.com/a/52745571
type: Answer
has body: I find the solution and I want to share with you the answer. In the API documentation Test Client says: When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back. We should put the assert after with statement not in, for this work, so the code should be: def test_dashboard(client): with client.session_transaction(subdomain='blue') as session: session['expires'] = time.time() + 10000 response = client.get('/dashboard', subdomain='blue') assert response.status_code == 200 This simple indent solves my problem.
upvote count: 12
score: 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52709008
answers question: http://stackoverflow.com/q/52709008

http://stackoverflow.com/q/52591265
upvote count: 2
type: UnansweredQuestion
has title: plotting a pdf together with a histogram using plotnine in python
tagged with: python
score: 2
type: Question
has body: I have the following data: import pandas as pd from plotnine import * gd_sp_tmp = pd.DataFrame({ 'variable': {0: 'var1', 1: 'var1', 2: 'var1', 3: 'var1', 4: 'var1', 5: 'var1', 6: 'var1', 7: 'var1', 8: 'var1', 9: 'var1', 10: 'var1', 11: 'var1', 12: 'var1', 13: 'var1', 14: 'var1', 15: 'var1', 16: 'var1', 17: 'var1', 18: 'var1', 19: 'var1', 20: 'var1', 21: 'var1', 22: 'var1', 23: 'var1', 24: 'var1', 25: 'var1', 26: 'var1', 27: 'var1', 28: 'var1', 29: 'var1', 30: 'var1', 31: 'var1', 32: 'var1', 33: 'var1', 34: 'var1', 35: 'var1', 36: 'var1', 37: 'var1', 38: 'var1', 39: 'var1', 40: 'var1', 41: 'var1', 42: 'var1', 43: 'var1', 44: 'var1', 45: 'var1', 46: 'var1', 47: 'var1', 48: 'var1', 49: 'var1', 50: 'var2', 51: 'var2', 52: 'var2', 53: 'var2', 54: 'var2', 55: 'var2', 56: 'var2', 57: 'var2', 58: 'var2', 59: 'var2', 60: 'var2', 61: 'var2', 62: 'var2', 63: 'var2', 64: 'var2', 65: 'var2', 66: 'var2', 67: 'var2', 68: 'var2', 69: 'var2', 70: 'var2', 71: 'var2', 72: 'var2', 73: 'var2', 74: 'var2', 75: 'var2', 76: 'var2', 77: 'var2', 78: 'var2', 79: 'var2', 80: 'var2', 81: 'var2', 82: 'var2', 83: 'var2', 84: 'var2', 85: 'var2', 86: 'var2', 87: 'var2', 88: 'var2', 89: 'var2', 90: 'var2', 91: 'var2', 92: 'var2', 93: 'var2', 94: 'var2', 95: 'var2', 96: 'var2', 97: 'var2', 98: 'var2', 99: 'var2'}, 'value': {0: 0.6058597809345508, 1: 0.5793863580299581, 2: 0.8464980992038321, 3: 0.24855227431181698, 4: 1.8852877490212698, 5: 0.4234171954404873, 6: 0.3435477323074209, 7: 3.358464370031963, 8: 0.5253401196517882, 9: 2.358632857360592, 10: 0.15960003602748035, 11: 0.2882705893127418, 12: 1.0995070639266127, 13: 0.3492611123700738, 14: 0.656410247866536, 15: 1.7926397942332677, 16: 0.2809984468410994, 17: 2.146319743864339, 18: 1.6912849075574694, 19: 1.233812138850312, 20: 0.21044290817060624, 21: 0.7130666643073327, 22: 0.521102906290718, 23: 0.8191663841868542, 24: 0.20231016020355008, 25: 1.542239677553837, 26: 0.07752167395995535, 27: 0.07661799644296931, 28: 0.13728522388491152, 29:…
has answer: http://stackoverflow.com/a/52612152
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: plotnine
tagged with: python-3.x

http://stackoverflow.com/comment/92340143
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52706667
has text: You could return [`NotImplemented`](https://docs.python.org/3/library/constants.html#NotImplemented) instead, or raise a [`NotImplementedError`](https://docs.python.org/3/library/exceptions.html#NotImplementedError). The docs for `NotImplementedError` also mention setting the method to `None` if that class will never support that method.

http://stackoverflow.com/q/52715621
has comment: http://stackoverflow.com/comment/92364281
tagged with: python
has answer: http://stackoverflow.com/a/52724042
tagged with: linear-regression
tagged with: machine-learning
downvote count: 1
type: Question
has title: How can I plot best fit line in multiple Linear Regression if I have two independent variables and one dependent variable
score: -1
has body: This code is for 1-Dimentional. What I have to edit in this code for multiple Dimentional? y_pred= regressor.predict(X_test) Plotting the Training set result: plt.scatter(X_train, y_train, color='red') plt.plot(X_train, regressor.predict(X_train) , color= 'blue') plt.title('Salary vs Experience (training set) ') plt.xlabel('year of experiance') plt.ylabel('salary') plt.show() Plotting the test set result: plt.scatter(X_test, y_test, color='red') plt.plot(X_train, regressor.predict(X_train), color= 'blue') plt.title('Salary vs Experience (training set) ') plt.xlabel('year of experiance') plt.ylabel('salary') plt.show()
tagged with: numpy
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92357049
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/64221852
type: Answer
answers question: http://stackoverflow.com/q/52647466
has body: I spent around 1 day and test 4 solutions for Linux/raspberry startup run script issues. Then here is the solution (I choose crontab) open crontab (use linux@crontab -e -&gt; not use sudo crontab -e ... thats could be error in future some access for script etc.) pi@ crontab -e Then choose nano and edit like this... It is tricky, ı found after test may be more than 10x times: @reboot cd /home/pi/beetool &amp;&amp; /usr/bin/python3 run.py &amp; My code is waiting for me under /home/pi/beetool. If you don't change the directory that occurs error. And my code uses infinite loop so I have to finish with &quot;&amp;&quot; as you see above. So I hope that helps someone, too ...
score: 0

http://stackoverflow.com/q/52703902
has title: using df.apply to call function associate with different colum
has body: Given a pd.DataFrame like: to_remove pred_0 .... pred_10 0 ['apple'] ['apple','abc'] .... ['apple','orange'] 1 ['cd','sister'] ['uncle','cd'] .... ['apple'] On each row, I want to remove the element in pred_0...pred_10 if this element show up in to_remove in the same row. In this example, the answer should be: to_remove pred_0 .... pred_10 0 ['apple'] ['abc'].... ['orange'] # remove 'apple' this row 1 ['cd','sister'] ['uncle']....['apple'] # remove 'cd' and 'sister' this row I am wondering how to associate the code to do so. To generate the example df: from collections import OrderedDict D=pd.DataFrame(OrderedDict({'to_remove':[['apple'],['cd','sister']],'pred_0':[['apple','abc'],['uncle','cd']],'pred_1':[['apple','orange'],['apple']]}))
has comment: http://stackoverflow.com/comment/92334922
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/52704282
type: AnsweredQuestion
tagged with: list
tagged with: dataframe
has comment: http://stackoverflow.com/comment/92335143
type: Question
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/52704282
possible better answer: http://stackoverflow.com/a/52704393
tagged with: pandas
has answer: http://stackoverflow.com/a/52704393
tagged with: python
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52611748
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52611833
has body: I am trying to extract all the tags that appear after an tag until it comes across a then it repeats again. Example html code: Need to grab this Need to grab this Need to grab this Need to grab this Problem is the with "Need to grab this" vary so sometimes there could be one, three or even like 8. How do I create a loop and grab them all until that next tag again? I am using BeautifulSoup at the moment. Here is my current python code: headernum = 0 i = 0 x = soup.find_all("h1") for i in range(len(x)): header = soup.find_all('h1')[headernum] name = header.find_all_next('p')[1] print(name.text) workplace = name.find_all_next('i')[0] print(workplace.text) abstract = workplace.find_all_next('p')[1].get_text() print(abstract) i += 1 headernum += 1
tagged with: http://stackoverflow.com/tag/html
has title: Extract all tags until appears? BeautifulSoup and Python
tagged with: python
possible better answer: http://stackoverflow.com/a/52611856
has answer: http://stackoverflow.com/a/52611856
type: AnsweredQuestion
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/52611833
type: Question
answer count: 2

http://stackoverflow.com/q/52713780
favorite count: 0
possible better answer: http://stackoverflow.com/a/52713854
has answer: http://stackoverflow.com/a/52716927
has answer: http://stackoverflow.com/a/52713854
has answer: http://stackoverflow.com/a/52713806
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has title: How can i split those lists in on list using for loops in single line?
tagged with: loops
accepted answer: http://stackoverflow.com/a/52713806
type: Question
tagged with: for-loop
has body: I want to make list flatten([[list1], [list2], [list3] ....]) from pandas Can someone tell me how to make 'for loop' in single line? Thanks (Is there any other way to solve this?) words = [] for sent in train['tokenize']: words += sent The result i want is [[list1], [list2], [list3]] >> [list1, list2, list3]
downvote count: 0
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/92269009
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52669521
score: 0
has text: I think your 'read_csv' command is missing some options. As is, the index and columns each have 1 level.

http://stackoverflow.com/q/52740724
tagged with: numpy
has answer: http://stackoverflow.com/a/52741104
has comment: http://stackoverflow.com/comment/92406132
tagged with: function
tagged with: arrays
downvote count: 0
has body: Let's say I have a list of three functions: f_list = [f1,f2,f3] and an array of values, where each function should be evaluated values = numpy.array([1,2,3]) such that I get f1(1), f2(2) and f3(3). One way to do that is of course looping over the functions: for i in range(3): print(f_list[i](values[i]) Is there a more efficient way to do that? Something similar to numpy array operations, where I can pass all values at once to get an array of function evaluations? As far as I know I cannot store functions in a numpy array, can I? In my case I have a very large 2D-list of scipy interpolation (interp1d) functions (or call objects), which takes a long time to evaluate when looping over both axes.
has comment: http://stackoverflow.com/comment/92406040
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/92407758
score: 3
has comment: http://stackoverflow.com/comment/92418789
tagged with: python
has comment: http://stackoverflow.com/comment/92407488
has answer: http://stackoverflow.com/a/52741278
upvote count: 3
answer count: 2
has title: How to efficiently evaluate a whole Python list of functions element-wise?
has comment: http://stackoverflow.com/comment/92406157
has comment: http://stackoverflow.com/comment/92406310
tagged with: performance
type: UnansweredQuestion

http://stackoverflow.com/comment/139109787
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52636680
has text: Please note that recent Shapely versions (>=2.00) won't allow you to iterate over multipolygons You must iterate over its .geoms property.
score: 0

http://stackoverflow.com/comment/92145697
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52605666
has text: Done, thanks for your patience :)

vectorization
tags question: http://stackoverflow.com/q/52704777
tags question: http://stackoverflow.com/q/52705933
tags question: http://stackoverflow.com/q/52722315
tag name: vectorization
type: Tag

http://stackoverflow.com/a/52705085
answers question: http://stackoverflow.com/q/52704808
has body: Your original code would kind-of work if you called it via appender(*frames()), but you would still get an error because assignment_frame should be main_frame. However, there is even a simpler approach. Just pass a collection of dataframes and use a list comprehension with your condition to filter them. Note that YOU DO NOT WANT TO BUILD DATAFRAMES BY APPENDING! This is called quadratic copy, because each time you call append a copy of the original dataframe is returned plus the newly appended dataframe. This will get very slow. See timings below. def appender(dataframes): return pd.concat([df for df in dataframes if not df.empty]) # Optional: .reset_index() &gt;&gt;&gt; appender(frames()) 0 0 not 1 empty 0 not 1 empty Timings (concat vs append) df = pd.DataFrame(np.random.randn(10, 10)) %timeit df2 = pd.concat([df] * 1000) # 10 loops, best of 3: 54.7 ms per loop %%timeit df3 = pd.DataFrame() for _ in range(1000): df3 = df3.append(df) # 1 loop, best of 3: 1.28 s per loop &gt;&gt;&gt; df3.equals(df2) True
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52704808

http://stackoverflow.com/comment/92392492
has text: `set()` creates a set and throws it away. You need to assign it to a variable to use it. You may also return the set itself from `unique()`. No need to convert to list as you can enumerate and lookup elements in a set too.
type: QuestionComment
comment on: http://stackoverflow.com/q/52733653
type: Comment
score: 0

http://stackoverflow.com/q/52603048
accepted answer: http://stackoverflow.com/a/52603081
has comment: http://stackoverflow.com/comment/92140332
possible better answer: http://stackoverflow.com/a/52603082
has comment: http://stackoverflow.com/comment/92140219
answer count: 2
has title: How do I check the users input in Python3?
favorite count: 0
has body: So my code says this: a = input("Choose a letter") if a == "A" or "B" or "D": cr = "false" elif a == "C": cr = "true" if cr == "false": print("Sorry you did not asnwer correctly") import sys sys.exit() elif cr == "true": print("Well done!") But for some reason, whatever I put, it says it is wrong. Any help? I am new to python and have come from Lua.
linked to: http://stackoverflow.com/q/15851146
duplicate of: http://stackoverflow.com/q/20002503
has answer: http://stackoverflow.com/a/52603082
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92140327
has answer: http://stackoverflow.com/a/52603081

http://stackoverflow.com/a/52708634
has body: After going through tf documentation for some time, I came up with the following solution c1_pix, _, _ = tf.split(tf.equal(op_img,[[[255,255,255]]]), 3, axis=-1) c2_pix = tf.logical_not(c1_pix) new_op_img = tf.concat([c1_pix, c2_pix], -1) This worked for me.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52705471
accepted answer of: http://stackoverflow.com/q/52705471

http://stackoverflow.com/comment/92406986
comment on: http://stackoverflow.com/q/52740989
has text: Perhaps you thought up to now `int` would be there to get a number from a string? But it's there to get an _integer_ number from a string. Try inputting e.g. `3.14` or sth like that in your code - it will throw an error, as this is not castable to `int`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52636092
has answer: http://stackoverflow.com/a/52636479
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/52636226
accepted answer: http://stackoverflow.com/a/52636250
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92205603
tagged with: dataframe
type: Question
score: 2
has title: Find a value of a dictionary in dataframe column and modify it
downvote count: 0
has body: I dealing with DataFrames and Dictionaries now, and i have a problem, I have a Dictionary "Fruits" {BN:'Banana', LM:'Lemon', AP:'Apple' ..... etc} And a DataFrame- "Stock": Fruit Price 0 Sweet Mango 1 1 Green Apple 2 2 Few blue Banana 0 3 Black Banana 5 I wand to do the next thing: replace all the values from Stock['Fruit'] with the Fruits.values() this way: if the value from Fruits appears in the Stock['Fruit'] row it will be replaced this way: Few blue Banana ---> Banana Black Banana ---> Banana now the DataFrame Stock will look this way: Fruit Price 0 Sweet Mango 1 1 Green Apple 2 2 Banana 0 3 Banana 5 I found different codes to replace or to check if values from the Dicitionary appears in the DataFrame Stock['Fruit'] = Stock.Fruit.map(Fruits) if (Fruits.values() in Stock['Fruit'] for item in Stock) any('Mango' in Stock['Fruit'] for index,item in Stock.iterrows()) But i cant find any thing to update the rows of the DataFrame
tagged with: any
favorite count: 0
linked to: http://stackoverflow.com/q/2912231
answer count: 3
has answer: http://stackoverflow.com/a/52636250
tagged with: pandas
has comment: http://stackoverflow.com/comment/92205614
has comment: http://stackoverflow.com/comment/92205640
has answer: http://stackoverflow.com/a/52636226
upvote count: 2
has comment: http://stackoverflow.com/comment/92205623

http://stackoverflow.com/comment/92285273
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52677912
has text: Here 12 means that divide the region between two major ticks into 12 regions so you have basically 11 minor ticks

http://stackoverflow.com/comment/92326608
has text: Do I have to use .values()? I still need a queryset instance
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52699407

http://stackoverflow.com/comment/124171371
type: Comment
has text: @HunterKohler huh. So they [are](https://docs.python.org/3/library/functions.html#delattr). I see. Thanks for clarifying. I should have read through the PEP 585 before commenting.
comment on: http://stackoverflow.com/a/68908479
type: AnswerComment
score: 0

http://stackoverflow.com/a/52712798
has comment: http://stackoverflow.com/comment/92351866
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92351817
has body: #!/usr/bin/python3 for filename in os.listdir('/path/to/json_files'): if filename.endswith('.json'): with open(filename, encoding='utf-8') as f: data = f.read() print(json.dumps(data, indent=4)) Notice the encoding used with open(). This SHOULD import the files and display them as necessary. I think.
type: Answer
answers question: http://stackoverflow.com/q/52712674
score: 0

http://stackoverflow.com/q/52619030
favorite count: 0
has body: Could you explain how to assign certain scores from a list to values in multiple lists and get the total score for each value? score = [1,2,3,4,5] assigne a score based on the position in the list l_1 = [a,b,c,d,e] assign a=1, b=2, c=3, d=4, e=5 l_2 = [c,a,d,e,b] assign c=1, a=2, d=3, e=4, b=5 I am trying to get the result like {'e':9, 'b': 7, 'd':7, 'c': 4, 'a': 3} Thank you!
possible better answer: http://stackoverflow.com/a/52619282
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/52619142
has answer: http://stackoverflow.com/a/52622064
has answer: http://stackoverflow.com/a/52622866
type: AnsweredQuestion
tagged with: list
has title: How to assign certain scores from a list to values in multiple lists and get the sum for each value in python?
has comment: http://stackoverflow.com/comment/92173900
tagged with: cumulative-sum
downvote count: 1
type: Question
score: 3
answer count: 6
has answer: http://stackoverflow.com/a/52619424
upvote count: 4
has answer: http://stackoverflow.com/a/52619142
has answer: http://stackoverflow.com/a/52619282
has answer: http://stackoverflow.com/a/52619323

http://stackoverflow.com/comment/92404953
comment on: http://stackoverflow.com/q/52738492
score: 0
has text: set(), bith with a for-loop and a if sentence, .append/.update
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52706958
answer count: 3
tagged with: nested
tagged with: python
possible better answer: http://stackoverflow.com/a/52707298
has comment: http://stackoverflow.com/comment/92340430
has answer: http://stackoverflow.com/a/52707298
has comment: http://stackoverflow.com/comment/92340532
score: 0
accepted answer: http://stackoverflow.com/a/52707757
has title: Organize/Formatting the python code to one line
has comment: http://stackoverflow.com/comment/92340475
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/92340306
has answer: http://stackoverflow.com/a/52707495
type: Question
tagged with: for-loop
has body: Is there any way to rewrite the below python code in one line for i in range(len(main_list)): if main_list[i] != []: for j in range(len(main_list[i])): main_list[i][j][6]=main_list[i][j][6].strftime('%Y-%m-%d') something like below, [main_list[i][j][6]=main_list[i][j][6].strftime('%Y-%m-%d') for i in range(len(main_list)) if main_list[i] != [] for j in range(len(main_list[i]))] I got SyntaxError for this. Actually, i'm trying to storing all the values fetched from table into one list. Since the table contains date method/datatype, my requirement needs to convert it to string as i faced with malformed string error. So my approach is to convert that element of list from datetime.date() to str. And i got it working. Just wanted it to work with one line
has answer: http://stackoverflow.com/a/52707757

http://stackoverflow.com/comment/92143221
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52603672
has text: Ok, i'm checking.
score: 0

http://stackoverflow.com/q/52602484
possible better answer: http://stackoverflow.com/a/52617179
tagged with: jupyter-irkernel
has comment: http://stackoverflow.com/comment/92139099
has answer: http://stackoverflow.com/a/72776396
has comment: http://stackoverflow.com/comment/92139196
score: 14
has answer: http://stackoverflow.com/a/60906195
tagged with: jupyter
answer count: 4
tagged with: jupyter-notebook
favorite count: 0
linked to: http://stackoverflow.com/q/52551878
tagged with: pycharm
tagged with: python
has title: How to solve the ModuleNotFoundError: No module named 'prompt_toolkit.formatted_text' in Jupyter Notebook inside the Pycharm IDE?
has body: I am using Pycharm 2018.2 version in ubuntu 18.04 and I am trying to use the JupyterNoteBook inside the pycharm it's been loading and creating a new notebook. But the cell in the Jupyter always shows busy and it throws some error like ModuleNotFoundError: No module named 'prompt_toolkit.formatted_text'. Eventhough, I restarted the kernel again and again it throws the same error. Even I uninstalled and after the re-installation it throws the same error. Error it throws Can aynone please help me to resolve this error? Thanks in advance !
type: AnsweredQuestion
upvote count: 14
accepted answer: http://stackoverflow.com/a/60906195
has comment: http://stackoverflow.com/comment/92168299
has comment: http://stackoverflow.com/comment/92139886
has answer: http://stackoverflow.com/a/52617179
type: Question
has answer: http://stackoverflow.com/a/68955954
downvote count: 0

http://stackoverflow.com/comment/92199611
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52595273
has text: @api55 I am using .8 for threshold. Don't you think that's pretty high? I am really confused right now. :/
score: 0

http://stackoverflow.com/comment/92297455
type: QuestionComment
has text: Yes, each site is compared in itself.
score: 0
comment on: http://stackoverflow.com/q/52681048
type: Comment

http://stackoverflow.com/comment/92148701
score: 1
comment on: http://stackoverflow.com/a/52607078
type: AnswerComment
type: Comment
has text: @dbachhav , this doesn't really answers the question. If you want to ask OP for some more details - leave a comment under the question

http://stackoverflow.com/comment/92372291
comment on: http://stackoverflow.com/q/52723449
has text: I'm sorry but I don't understand what you me to by "prevent to do the same" in the reverse direction? Do you mean you want to exclude the example where `list_02 = [3, 2, 1, 0]`?
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/52731884
accepted answer: http://stackoverflow.com/a/52732077
has body: So I am trying to write a C function that accepts a numpy array object, extracts the data, does some manipulations and returns another c array as a numpy array object. Everything works seamlessly and I use python wrappers which help easy manipulation on the python side. However, I am facing a memory leak. I have an output pointer of doubles that I malloc-ed and which I wrap into a Python array object just before returning it to the calling python function, PyObject *arr; int nd = 2; npy_intp dims[] = {5, 10}; double *data = some_function_that_returns_a_double_star(x, y, z); arr = PyArray_SimpleNewFromData(nd, dims, NPY_DOUBLE, (void *)data); return arr; However, this creates a memory leak, because data is never freed and I did some googling to find that this is a problem in such applications and solution is non-trivial. The most helpful resource that I found on this is given here. I could not implement the destructor that this page talks about from the given example. Can someone help me with this? More concretely I am looking for something like, PyObject *arr; int nd = 2; npy_intp dims[] = {5, 10}; double *data = some_function_that_returns_a_double_star(x, y, z); arr = PyArray_SimpleNewFromData(nd, dims, NPY_DOUBLE, (void *)data); some_destructor_that_plug_memLeak_due_to_data_star(args); return arr; Numpy Array C APIs Numpy C APIs
type: Question
tagged with: numpy
tagged with: http://stackoverflow.com/tag/c
upvote count: 4
possible better answer: http://stackoverflow.com/a/58001107
answer count: 2
has answer: http://stackoverflow.com/a/58001107
downvote count: 0
has answer: http://stackoverflow.com/a/52732077
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 4
has title: PyArray_SimpleNewFromData

http://stackoverflow.com/comment/92347336
comment on: http://stackoverflow.com/a/52710369
score: 0
type: AnswerComment
has text: I get the following: TypeError Traceback (most recent call last) <ipython-input-52-c392c9462213> in <module> 1 for col in df.columns: ----> 2 if (df[col] != 'col').any(): 3 df[col]=df[col].replace('student','') /anaconda3/envs/Python/lib/python3.7/site-packages/pandas/core/ops.py in wrapper(self, other, axis) 1281 1282 with np.errstate(all='ignore'): -> 1283 res = na_op(values, other) 1284 if is_scalar(res): 1285 raise TypeError('Could not compare {typ} ty...
type: Comment

http://stackoverflow.com/comment/92377408
has text: There are no columns in python in any strict sense. Presumably you have a dataframe. Use `pandas.to_datetime()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52726072

http://stackoverflow.com/comment/92341874
type: Comment
has text: I fully understood everything you said but the part about the return of a code outside the 200-299 range. I mean, I'm not a programmer and This may be a very stupid question but how can I write the code to return the values you are saying? Should I just write: "return 300" Because the downside of the raise ValueError code is that is shown in the Stackdriver error report page on google app engine and i just want to avoid that
type: AnswerComment
comment on: http://stackoverflow.com/a/52702863
score: 0

seaborn
tags question: http://stackoverflow.com/q/52705037
tags question: http://stackoverflow.com/q/52708019
tag name: seaborn
tags question: http://stackoverflow.com/q/52646026
tags question: http://stackoverflow.com/q/52594235
tags question: http://stackoverflow.com/q/52670304
tags question: http://stackoverflow.com/q/52629796
tags question: http://stackoverflow.com/q/52590247
tags question: http://stackoverflow.com/q/52687936
tags question: http://stackoverflow.com/q/52720616
tags question: http://stackoverflow.com/q/52614194
tags question: http://stackoverflow.com/q/52659771
tags question: http://stackoverflow.com/q/52592844
tags question: http://stackoverflow.com/q/52650994
tags question: http://stackoverflow.com/q/52652264
tags question: http://stackoverflow.com/q/52736103
tags question: http://stackoverflow.com/q/52626103
tags question: http://stackoverflow.com/q/52626698
tags question: http://stackoverflow.com/q/52729459
type: Tag

http://stackoverflow.com/q/52685198
tagged with: google-oauth
type: Question
upvote count: 2
tagged with: google-api-client
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52694338
tagged with: python
has title: Authorizing service account with oauth2 using python for Google Play Developer API
score: 2
downvote count: 0
has body: I am trying to authorize a service account using oauth2 through the google-client-api python library. I am ultimately wanting to verify in-app purchases. This is my code: SCOPES = ['https://www.googleapis.com/auth/androidpublisher'] SERVICE_ACCOUNT_FILE = 'google.api.json' credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) http = credentials.authorize(httplib2.Http()) service = build( serviceName='androidpublisher', version='v2', credentials=credentials ) req = service.purchases().products().get( packageName=package, productId=product, token=token ) response = req.execute() I get this message back: ...returned "The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console." My project ID is absolutely linked; my service account is absolutely connected in the Google Play Console as a user with the correct permissions for this project. When I log the above code, I am getting the project ID that is linked. The token (not access token, but in-app purchase token) is from a test purchase of my personal Google account (just recently Google finally opened up developer's accounts for test purchases!). And the sku for my test purchase is the actual sku that I am going to sell to the app users. I am at a loss. There is so much conflicting information on how to do what I am trying to achieve. For shame, Google! For Shame! The docs are lacking, to say the least. (I mean they have good information, it is just scattered all over the place). I would love any advice on this. I am at a loss and can't get past the above error message. EDIT: My code was correct above; see my answer for the real cause.
tagged with: google-play-developer-api
favorite count: 0

http://stackoverflow.com/comment/92271447
type: Comment
has text: Got it. If i have more columns in the file but i don't need them do i still need to define them in col.names? or only until the first 4 columns that i really care for?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52670732

http://stackoverflow.com/q/52649992
answer count: 2
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/52650316
tagged with: python
has comment: http://stackoverflow.com/comment/92233751
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: selenium
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/52651131
type: Question
has title: Selenium: How to parse through a code after using selenium to click a dropdown
has body: I'm trying to webscrape trough this webpage https://www.sigmaaldrich.com/. Up to now I have achieved for the code to use the requests method to use the search bar. After that, I want to look for the different prices of the compounds. The html code that includes the prices is not visible until the Price dropdown has been clicked. I have achieved that by using selenium to click all the dropdowns with the desired class. But after that, I do not know how to get the html code of the webpage that is generated after clicking the dropdowns and where the price is placed. Here's my code so far: import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep #get the desired search terms by imput name=input("Reagent: ") CAS=input("CAS: ") #search using the name of the compound data_name= {'term':name, 'interface':'Product%20Name', 'N':'0+', 'mode':'mode%20matchpartialmax', 'lang':'es','region':'ES', 'focus':'product', 'N':'0%20220003048%20219853286%20219853112'} #search using the CAS of the compound data_CAS={'term':CAS, 'interface':'CAS%20No.', 'N':'0','mode':'partialmax', 'lang':'es', 'region':'ES', 'focus':'product'} #get the link of the name search r=requests.post("https://www.sigmaaldrich.com/catalog/search/", params=data_name.items()) #get the link of the CAS search n=requests.post("https://www.sigmaaldrich.com/catalog/search/", params=data_CAS.items()) #use selenium to click in the dropdown(only for the name search) driver=webdriver.Chrome(executable_path=r"C:\webdrivers\chromedriver.exe") driver.get(r.url) dropdown=driver.find_elements_by_class_name("expandArrow") for arrow in dropdown: arrow.click() As I said, after this I need to find a way to get the html code after opening the dropdowns so that I can look for the price class. I have tried different things but I don't seem to get any working solution. Thanks for your help.
has answer: http://stackoverflow.com/a/52650316
has answer: http://stackoverflow.com/a/52651131

http://stackoverflow.com/a/52694199
answers question: http://stackoverflow.com/q/52685896
has body: solarissmoke was correct in saying my User object wasn't the default Django model being imported. The models.py was autogenerated from an existing database and was defaulting to that User class. Once that class was removed from the models.py file, everything worked as it should. Thanks!
score: 0
type: Answer

http://stackoverflow.com/a/52673023
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92276210
has comment: http://stackoverflow.com/comment/92276316
type: Answer
has body: Edit : Under run configuration enable this - Emulate terminal in output console (see below) Remove extra indentation Error I get File "run.py", line 2 while True: ^ IndentationError: unexpected indent Code should be indented like this. Tested and it works. import msvcrt while True: if msvcrt.kbhit(): key = msvcrt.getch() print(key)
has comment: http://stackoverflow.com/comment/92275798
has comment: http://stackoverflow.com/comment/92276291
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52672817
has comment: http://stackoverflow.com/comment/92275837
has comment: http://stackoverflow.com/comment/92275925
accepted answer of: http://stackoverflow.com/q/52672817
downvote count: 0

http://stackoverflow.com/comment/92246436
score: 2
comment on: http://stackoverflow.com/q/52657962
has text: yes, but **note** that it is reference of list in above case. Suppose you change an element of `one` then, it effects `three`.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52697063
answers question: http://stackoverflow.com/q/52696711
type: Answer
has comment: http://stackoverflow.com/comment/92320776
has comment: http://stackoverflow.com/comment/92321088
has comment: http://stackoverflow.com/comment/92321246
has comment: http://stackoverflow.com/comment/92320610
score: 0
has body: actually, I should say that there is no faster way of doing your desired action other that loop because if you look closer to the problem you can see that by use of algorithm this action takes at least O(n) to be done. so all answers are right and will do as you want with Zip or map or ... but these solutions just make your implementing more beautiful and pythonic. not faster, in some cases, like blhsing answer, it is a little bit faster because of less line of code, not the time complexity.

http://stackoverflow.com/comment/92286311
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52666661
has text: Thank you. Your answer helped me a lot
type: Comment

http://stackoverflow.com/q/52665718
answer count: 1
downvote count: 0
has title: Is vscode-python pipenv auto-run behavior a security risk?
favorite count: 0
tagged with: python
has body: I have a project (created by a friend) that contains a Pipfile. I just opened the folder in VSCode and upon opening a file, got this message: Workspace contains pipfile but attempt to run 'pipenv --venv' failed with 'spawn pipenv ENOENT'. Make sure pipenv is on the PATH. Ignoring the fact that the project setup is borked, I am surprised and concerned that the VSCode python extension is automatically running pipenv. My Question is: should I not open untrusted folders in VSCode? My reasoning is that if I opened a malicious folder (e.g. pretending to be an open source library), then VSCode appears to auto-run pip installation, and from what I know of pip, it seems likely that you could place a malicious executable in the PATH (even if it's just in the VSCode workspace environment) that the user then invokes accidentally. So it seems like just by attempting to look at an untrusted folder I could get pwned. Thoughts?
type: AnsweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/52673458
type: Question
tagged with: visual-studio-code
accepted answer: http://stackoverflow.com/a/52673458
tagged with: security

http://stackoverflow.com/q/52730661
has comment: http://stackoverflow.com/comment/92386822
has comment: http://stackoverflow.com/comment/92386348
type: Question
upvote count: 0
score: -2
linked to: http://stackoverflow.com/q/7801586
has comment: http://stackoverflow.com/comment/92386379
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52730718
tagged with: scientific-notation
has body: Help! I am completely new to coding as you can see...lol I need help removing the scientific notation that my code outputs. I would like the results to be displayed as only real numbers...i.e (removing the "e")...I would like to show only maybe 2-4 numbers after the decimal point. Please if anyone can help me with that it would be greatly appreciated. Organism_A = 50 year = 1 for week in range(1,52*5 + 1): if week%2 == 0: Organism_A/=0.25 if week%4 == 0: Organism_A*=2 if week%52 == 0: print("At the end of year " + str(year) + " number of Organism A remaining = " + str(Organism_A)) year+=1 Organism_B = 250 year = 1 for week in range(1,52*5 + 1): if week%1 == 0: Organism_B/=0.25 if week%4 == 0: Organism_B*=3 if week%52 == 0: print("At the end of year " + str(year) + " number of Organism B remaining = " + str(Organism_B)) year+=1 Organism_C = 1000 year = 1 for week in range(1,52*5 + 1): if week%1 == 0: Organism_C/=0.13 if week%4 == 0: Organism_C*=0.75 if week%52 == 0: print("At the end of year " + str(year) + " number of Organism C remaining = " + str(Organism_C)) year+=1 Code OUTPUT
type: UnansweredQuestion
downvote count: 2
tagged with: python
duplicate of: http://stackoverflow.com/q/7801586
has title: I am trying to remove exponential numbers from the results
has comment: http://stackoverflow.com/comment/92386352

http://stackoverflow.com/a/52592662
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52590484
has body: You have to use jquery to dynamically update the page: ... Predict In the app: @app.route('/api') def predict(): text_input = request.args.get('text') return flask.jsonify({'name':parse(pd.Series([text_input]))}) Now, when the "Predict" button is clicked, the javascript takes the inputted text from the textarea and dynamically calls the route '/api' and updates the prediction div with the result.
downvote count: 0

http://stackoverflow.com/comment/92219039
comment on: http://stackoverflow.com/q/52642921
score: 0
type: Comment
has text: I'm not sure to understand what do you mean by "nothing happens". If you want the value returned, you have to fetch it: `con.execute(query).fetchall()`
type: QuestionComment

http://stackoverflow.com/q/52661127
tagged with: pandas
answer count: 1
tagged with: python
tagged with: dictionary
has title: How to remove one dictionary from dataframe
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52661186
tagged with: dataframe
has body: I have the following dataframe: And I made dictionaries from each unique appId as you see below: with this command: dfs = dict(tuple(timeseries.groupby('appId'))) After that I want to remove all dictionaries which have less than 30 rows from my dataframe. I removed those dictionaries from my dictionaries(dfs) and then I tried this code: pd.concat([dfs]).drop_duplicates(keep=False) but it doesn't work.
type: Question
accepted answer: http://stackoverflow.com/a/52661186
score: 0

http://stackoverflow.com/comment/92298665
score: 0
has text: Thanks for suggestion @jpp , i will incorporate it :-)
type: Comment
comment on: http://stackoverflow.com/a/52681689
type: AnswerComment

http://stackoverflow.com/comment/116907718
type: Comment
score: 7
type: AnswerComment
has text: Well, I tried it anyway in my conda shell window. It tried to download and install 11 packages, including pandas (?!) , ipython, notebook, tornado, requests and prompt_toolkit. It then failed to build wheel for pandas and declared an environmental error and unstalled about half of the packages, including tornado, google-auth and six. I suppose I should have taken the advice regarding pip: always or never, not sometimes.
comment on: http://stackoverflow.com/a/58110734

http://stackoverflow.com/a/75967124
type: Answer
has body: # load the input image image = cv2.imread(image_file) # Change to RGB space image_RGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #plt.imshow(image_RGB) #plt.show() # get pixel color pixel_colors = image_RGB.reshape((np.shape(image_RGB)0]*np.shape(image_RGB)[1], 3)) norm = colors.Normalize(vmin=-1.,vmax=1.) norm.autoscale(pixel_colors) pixel_colors = norm(pixel_colors).tolist() # Change to lab space image_LAB = cv2.cvtColor(image, cv2.COLOR_BGR2LAB ) (L_chanel, A_chanel, B_chanel) = cv2.split(image_LAB) fig = plt.figure(figsize=(8.0, 6.0)) axis = fig.add_subplot(1, 1, 1, projection="3d") axis.scatter(L_chanel.flatten(), A_chanel.flatten(), B_chanel.flatten(), facecolors = pixel_colors, marker = ".") axis.set_xlabel("L:ightness") axis.set_ylabel("A:red/green coordinate") axis.set_zlabel("B:yellow/blue coordinate") plt.show()
answers question: http://stackoverflow.com/q/52741742
score: 0

http://stackoverflow.com/q/52594959
upvote count: 2
has comment: http://stackoverflow.com/comment/92125398
accepted answer: http://stackoverflow.com/a/52595004
tagged with: python
has answer: http://stackoverflow.com/a/52595328
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92124815
has answer: http://stackoverflow.com/a/52595239
has comment: http://stackoverflow.com/comment/92125480
linked to: http://stackoverflow.com/q/42676982
type: Question
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/52595004
has comment: http://stackoverflow.com/comment/92124758
favorite count: 0
tagged with: series
tagged with: pandas
has body: I am combining two dataframe values from an Excel file to a new dataframe but the combined values changed to decimal number. Here are my codes: My dataframe that I wish to combine: cable_block pair 1 10 1 11 3 123 3 222 I insert a dataframe to have those two combined with a delimiter of /, so here is my code: df['new_col'] = df'cable_block', 'pair'.apply(lambda x: '/'.join(x.astype(str), axis=1)) The result I get is: cable_block pair new_col 1 10 1.0/10.0 1 11 1.0/11.0 3 123 3.0/123.0 3 222 3.0/222.0 After searching, I found good answer by here Psidom and Skirrebattie. So I tried: df['new_col'] = df['new_col'].applymap(str) and df['new_col'] = df['new_col'].astype(str) But it doesn't work the way it should. Looking by the codes, it should work and I find it weird that it doesn't. Is there another work around?
possible better answer: http://stackoverflow.com/a/52594997
answer count: 4
has answer: http://stackoverflow.com/a/52594997
has title: Combing dataframe values to a new dataframe

http://stackoverflow.com/comment/92151579
score: 0
type: Comment
has text: @neeraja - Really complicated, but need convert text file to dicts an then use my solution.
comment on: http://stackoverflow.com/a/52606956
type: AnswerComment

http://stackoverflow.com/comment/92291226
type: Comment
comment on: http://stackoverflow.com/a/52681308
score: 0
type: AnswerComment
has text: Last question bro, what if i want to change the date data delimiter "yyyy-mm-dd" into something like this "yyyy/mm/dd", how can i do it?

http://stackoverflow.com/comment/92251182
comment on: http://stackoverflow.com/q/52659132
type: Comment
has text: I think that python doesn't load the html and works like xml, php works like R in this case, loads html/head/body if not exists. Probe it adding by your own.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/94188579
type: Comment
has text: wrt/ "forgetting to add ()" being "an easy mistake", once you understand that the `obj.method()` expression is interpreted as an attribute lookup (`obj.method`) followed by a call (`()`), there's no reason you should forgot the call.
comment on: http://stackoverflow.com/a/52629279
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92402339
score: 2
comment on: http://stackoverflow.com/q/52738770
has text: @9769953 Fair enough, but more seriously, I don't like to post an answer unless I am reasonably sure that it isn't a duplicate, and I suspect that most Python 1-liner answers are already duplicates.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52709750
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92345789
has body: Need to achieve the from picture at top to the picture at the bottom. I tried many ways of pandas such as pandas.melt pandas.pivot pandas.pivot_table pandas.groupby Still couldnt achieve it What could be the way t achieve
type: Question
has title: How do I achieve the following result using python pandas?
score: 0
has answer: http://stackoverflow.com/a/52709910
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1

http://stackoverflow.com/a/52714801
answers question: http://stackoverflow.com/q/52705237
has body: top left: img.rotate(angle, resample=Image.BILINEAR, expand=True) top right: img.rotate(angle, resample=Image.BICUBIC, expand=True) bottom original. based on @Dinesh comment
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/92395634
has text: You will have to train the model, but basically, a set of lstm input nodes with a few hidden layers and the output layer giving you the different outputs you need is one approach.
comment on: http://stackoverflow.com/q/52733480
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52593764
tagged with: tuples
has comment: http://stackoverflow.com/comment/92122411
answer count: 5
has title: convert a tuple with three elements into dictionary
has answer: http://stackoverflow.com/a/52593882
tagged with: python
tagged with: dictionary
has body: This is my tuple (0, 7, 4) (1, 7, 4) (2, 7, 4) (3, 7, 4) (0, 4, 1) (0, 4, 3) (0, 6, 4) I want to convert this to a dictionary for for an example {0:(7,4), (4, 1), (4, 3), (6, 4), 1: (7, 4), 2:(7, 4), ....} basically first element of the tuple is key and second and third elements are values. The tuple was generated using : for i in range(len(vertices)): #print(i) for j in edges: d= (i, j[0], j[1]) print(d)
has answer: http://stackoverflow.com/a/52594349
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52594111
possible better answer: http://stackoverflow.com/a/52593854
has answer: http://stackoverflow.com/a/52594281
downvote count: 1
has answer: http://stackoverflow.com/a/52593854
type: Question
has comment: http://stackoverflow.com/comment/92123163
accepted answer: http://stackoverflow.com/a/52593882
score: -1
has comment: http://stackoverflow.com/comment/92122438
upvote count: 0
favorite count: 0

http://stackoverflow.com/q/52709627
type: Question
accepted answer: http://stackoverflow.com/a/52709799
tagged with: python
score: 0
has title: PLY token priority issue
answer count: 1
tagged with: ply
has answer: http://stackoverflow.com/a/52709799
type: AnsweredQuestion
has body: I'm using PLY to lex and parse some .tex files. For some unknown reasons token priority does not work as described in the documentation. Here are the tokens and the states: tokens = ('BT', 'BL', 'BD', 'BCONJ', 'BCOR', 'BE', 'ET', 'EL', 'ED', 'ECONJ', 'ECOR', 'EE', 'SEC', 'SSEC', 'SSSEC', 'ES', 'TEXT','ITEXT','BIBS','MT',) states = (('ig', 'exclusive'), ('sec', 'exclusive')) Here are the functions used by the lexer: def t_ig_BT(t): r'\\begin\{theorem\}' t.lexer.begin('INITIAL') return t def t_ig_BL(t): r'\\begin\{lemma\}' t.lexer.begin('INITIAL') return t def t_ig_BD(t): r'\\begin\{definition\}' t.lexer.begin('INITIAL') return t def t_ig_BCONJ(t): r'\\begin\{conjecture\}' t.lexer.begin('INITIAL') return t def t_ig_BCOR(t): r'\\begin\{corollary\}' t.lexer.begin('INITIAL') return t def t_ig_BE(t): r'\\begin\{example\}' t.lexer.begin('INITIAL') return t def t_ET(t): r'\\end\{theorem\}' t.lexer.begin('ig') return t def t_EL(t): r'\\end\{lemma\}' t.lexer.begin('ig') return t def t_ED(t): r'\\end\{definition\}' t.lexer.begin('ig') return t def t_ECONJ(t): r'\\end\{conjecture\}' t.lexer.begin('ig') return t def t_ECOR(t): r'\\end\{corollary\}' t.lexer.begin('ig') return t def t_EE(t): r'\\end\{example\}' t.lexer.begin('ig') return t def t_INITIAL_ig_SEC(t): r'\\section\{' t.lexer.begin('sec') return t def t_ig_SSEC(t): r'\\subsection\{' t.lexer.begin('sec') return t def t_ig_SSSEC(t): r'\\subsubsection\{' t.lexer.begin('sec') return t def t_sec_ES(t): r'\}' t.lexer.begin('ig') return t def t_ig_BIBS(t): r'\\bibliographystyle' t.lexer.begin('INITIAL') return t def t_INITIAL_MT(t): r'\\maketitle' t.lexer.begin('ig') return t def t_INITIAL_sec_TEXT(t): r'[\s\S]+' return t def t_ig_ITEXT(t): r'[\s\S]+' pass def t_ANY_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) The program is supposed to detect the beginning, the end, sections, subsections, subsubsections, theorems, lemmas, definitions, conjectures, corollaries and examples in a math paper and ignore t…

http://stackoverflow.com/comment/92171673
type: Comment
comment on: http://stackoverflow.com/a/52605127
score: 0
type: AnswerComment
has text: that's right! that was the problem. I have tried base64 encode on python side and decode it on nodejs, message parsed correctly. This problem have bothering me for 2-3 days. Thank you for you answer

http://stackoverflow.com/comment/92412470
type: QuestionComment
score: 2
has text: What's the range of `number`? BTW, you probably _don't_ want `bytes(number)`, since that returns a `bytes` string of zeroes of length `number`.
comment on: http://stackoverflow.com/q/52743006
type: Comment

http://stackoverflow.com/a/52618648
score: 1
has comment: http://stackoverflow.com/comment/92171521
answers question: http://stackoverflow.com/q/52618507
upvote count: 1
has comment: http://stackoverflow.com/comment/92171620
type: Answer
has body: class CLASS_INVENTORY(): maxcount_inventory = int(input("How many Inventories: ")) inventory=[] def __init__(self): for count_inventory in range(0, self.maxcount_inventory): add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1))) self.inventory.append(add_inventory)
has comment: http://stackoverflow.com/comment/92171970
downvote count: 0

http://stackoverflow.com/a/52664684
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/108533030
score: 64
has comment: http://stackoverflow.com/comment/92266190
has comment: http://stackoverflow.com/comment/92261548
upvote count: 64
has comment: http://stackoverflow.com/comment/92284720
type: Answer
has comment: http://stackoverflow.com/comment/106912981
accepted answer of: http://stackoverflow.com/q/52664293
has comment: http://stackoverflow.com/comment/92261891
has body: PATH is an environment variable that is a list of locations where executable programs lie (see also the wikipedia page. Whenever you are in your command line and try to execute some program, for example regedit, then the cmd does not magically know that you mean C:\Windows\regedit.exe. Instead, it searches all locations in your PATH for an executable named regedit and finds it in C:\Windows which is one of the standard parts of PATH in Windows. That is also, why messing with the PATH can be dangerous if you don't know what you are doing, because it might lead to things not working anymore if, for example you delete parts of the path or add custom directories to it. That being said, you should now have an idea what happens when you "Add anaconda to path". It simply means, that Anaconda adds the directory where its executables lie to the PATH, hence making it findable when, for example you type conda in your cmd. That being said, adding Anaconda to PATH is something that is convenient, because the commands can always be found automatically and they will also be found by other programs scanning your PATH for a python executable. At the same time it is not necessary. When you use e.g. pycharm, then you can specify the path to the interpreter inside of pycharm. it does not necessarily need to be present in your PATH. Note: I personally have it on my PATH because I am too lazy to open an Anaconda prompt each time I need it in a cmd and I do not see the harm in it if you understand the consequences and its my only python installation anyway. Also Helpful: On windows, you can use the where command to find out from where commands are loaded. For example: where regedit gives C:\Windows\regedit.exe This can be especially helpful when trying to debug PATH issues
answers question: http://stackoverflow.com/q/52664293
has comment: http://stackoverflow.com/comment/108546585

http://stackoverflow.com/comment/92141391
type: Comment
type: QuestionComment
has text: You should show what you've tried.
score: 0
comment on: http://stackoverflow.com/q/52603251

http://stackoverflow.com/a/52743441
accepted answer of: http://stackoverflow.com/q/52740436
answers question: http://stackoverflow.com/q/52740436
score: 0
has comment: http://stackoverflow.com/comment/92420651
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92416080
has comment: http://stackoverflow.com/comment/92415268
type: Answer
has body: You can do that with a TimeDistributed layer wrapper: from keras.layers import Input, Dense, TimeDistributed from keras.models import Sequential, Model N = None # Use fixed value if you do not want variable input size K = 20 def small_model(): inputs = Input(shape=(K,)) # Define the small model # Here it is just a single dense layer outputs = Dense(K, activation='relu')(inputs) return Model(inputs=inputs, outputs=outputs) def large_model(): inputs = Input(shape=(N, K)) # Define the large model # Just a single neuron here outputs = Dense(1, activation='relu')(inputs) return Model(inputs=inputs, outputs=outputs) def combined_model(): inputs = Input(shape=(N, K)) # The TimeDistributed layer applies the given model # to every input across dimension 1 (N) small_model_out = TimeDistributed(small_model())(inputs) # Apply large model outputs = large_model()(small_model_out) return Model(inputs=inputs, outputs=outputs) model = combined_model() model.compile(loss='mean_squared_error', optimizer='sgd') model.summary() Output: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, None, 20) 0 _________________________________________________________________ time_distributed_1 (TimeDist (None, None, 20) 420 _________________________________________________________________ model_2 (Model) (None, None, 1) 21 ================================================================= Total params: 441 Trainable params: 441 Non-trainable params: 0 _________________________________________________________________
has comment: http://stackoverflow.com/comment/92414347
has comment: http://stackoverflow.com/comment/92413375

http://stackoverflow.com/comment/92381699
type: QuestionComment
score: 0
has text: The file `top_level.txt` is not wheel specific. It even gets created in a virtualenv if you install PyYAML and if first deinstalled the wheel package. Under what circumstances do you think it is not created? Not sure though since when installing with pip does this (and/or if it is dependent on the version of setuptools as well).
type: Comment
comment on: http://stackoverflow.com/q/52723092

http://stackoverflow.com/a/52673473
accepted answer of: http://stackoverflow.com/q/52671392
upvote count: 1
answers question: http://stackoverflow.com/q/52671392
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92277207
type: Answer
has body: This may be too simplistic (or I'm still not understanding the details of what you want done, but it seems like this kind of approach would work). class BaseClass: list_1 = [...] dict_1 = {...} df_1 = pd.DataFrame(...) def aux_def_1(self): pass def aux_def_2(self): pass class MainDef_1(BaseClass) def __init__(self, parameter1, parameter2, parameter3): self.parameter1 = parameter1 self.parameter2 = parameter2 self.parameter3 = parameter3 def main(self): # whatever this version does...for example. self.list_1 # Accesses attribute of base class. x = self.parameter1 + 42 # Accesses attribute of this class. class MainDef_2(BaseClass) def __init__(self, parameter1, parameter3, parameter4): self.parameter1 = parameter1 self.parameter3 = parameter3 self.parameter4 = parameter4 def main(self): # whatever this version does...for example. result = self.aux_def_2() # Use method defined in base class. y = self.parameter4 + 13 # Accesses attribute of this class. Each subclass defines its own main() method. In it the needed parameters can be referenced via parameterN as well as the data and methods of the baseclass (again, just by prefixing their names with "self.".
has comment: http://stackoverflow.com/comment/92277355
downvote count: 0
score: 1

http://stackoverflow.com/comment/92204554
has text: Ok, so just checked my CSV output and it all looks good (no NaN). Is there a way i can share the file with you so you can see?
comment on: http://stackoverflow.com/q/52635163
score: 0
type: Comment
type: QuestionComment

file-io
tags question: http://stackoverflow.com/q/52597414
type: Tag
tag name: file-io
tags question: http://stackoverflow.com/q/52712201

http://stackoverflow.com/comment/92225820
type: Comment
comment on: http://stackoverflow.com/a/52646252
has text: @jpp Can you reference me something to read more on how to use it for more such manipulation
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92392568
comment on: http://stackoverflow.com/q/52733228
type: QuestionComment
type: Comment
score: 2
has text: `pct=True` gives you rank in percentages. If you want your ranks to be just whole numbers like `1.0, 2.0, 3.0`, you can simply remove the pct condition. If you want your rank in fractions, then I guess you need to apply some math on your rank logic as suggested in the answer by @helcode.

http://stackoverflow.com/a/52737775
answers question: http://stackoverflow.com/q/52735192
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52735192
type: Answer
has body: your problem is indeed the reshaping of X. Example: pd.DataFrame([[1,2],[3,4],[5,6]], columns = ["a", "b"]).values is a numpy array that looks like array([[1, 2], [3, 4], [5, 6]], dtype=int64) while pd.DataFrame([[1,2],[3,4],[5,6]], columns = ["a", "b"]).values.reshape(-1,1) doubles your amount of rows (because of two columns are reshaped into one) array([[1], [2], [3], [4], [5], [6]], dtype=int64) So in your case after reshaping your four columns into one you have four times more rows in X than in Y, while lm.fit(X, Y) needs you to have the same amount of rows in X and Y.
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92401767
has comment: http://stackoverflow.com/comment/92400974
score: 0

http://stackoverflow.com/a/52684222
type: Answer
answers question: http://stackoverflow.com/q/52683832
has body: I'm not sure why you want the output you've shown, because it is hard to read, but here is how to make it: &gt;&gt;&gt; Revenue = [400000000,10000000,10000000000,10000000] &gt;&gt;&gt; def revenue_formatted(rev): ... return "[" + ", ".join("{:,d}".format(n) for n in rev) + "]" ... &gt;&gt;&gt; print(revenue_formatted(Revenue)) [400,000,000, 10,000,000, 10,000,000,000, 10,000,000]
score: 0

http://stackoverflow.com/a/52729208
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92384496
has body: Have you tried the example in pysftp's documentation? import pysftp with pysftp.Connection('hostname', username='me', password='secret') as sftp: with sftp.cd('public'): # temporarily chdir to public sftp.put('/my/local/filename') # upload file to public/ on remote sftp.get('remote_file') # get a remote file
has comment: http://stackoverflow.com/comment/92384195
type: Answer
answers question: http://stackoverflow.com/q/52728414
downvote count: 0

http://stackoverflow.com/comment/92124985
has text: I'm pretty sure this isn't it. The "cleanup" you're talking about is garbage-collecting the previous result, but this would have to happen to every previous result on every iteration. In other words, if you do `X = small_test(1)` in a loop with one million iterations, then you have to clean up 999999 results within that loop. If you use the same variable name for the imported test, and run it a million times, then the imported version has 1000000 previous results to clean up instead of 999999. Not a big enough disadvantage to account for the difference.
comment on: http://stackoverflow.com/a/52592703
type: AnswerComment
score: 0
type: Comment

size
type: Tag
tags question: http://stackoverflow.com/q/52709642
tag name: size

http://stackoverflow.com/q/52687002
answer count: 1
has body: Why I am getting this kind mail from github? I am a Python/Django developer. Most of my project contains django dependencies in a requirements.txt file. And my requirements.txt file contains as follows - Django==1.11.9 pytz==2018.5 Subject: One of your dependencies may have a security vulnerability Body: shahjalalh, We found a potential security vulnerability in a repository for which you have been granted security alert access.
has answer: http://stackoverflow.com/a/52687071
favorite count: 0
downvote count: 1
tagged with: python
type: UnansweredQuestion
has title: potential security vulnerability mail from github for my django project
has comment: http://stackoverflow.com/comment/92301489
tagged with: django
type: Question
score: 1
upvote count: 2

http://stackoverflow.com/a/52589451
has body: I am not aware that you can restrict the coefficients easily , I have two solution alternatives , 1- Use the inverse(1/x) of the time series that results in negative coefficient. This will require you to do the normal regression first and than inverse the ones that has negative relationships. Get the weights and do wi/sum(wi). 2-It seems that you are dealing with time series, use logarithmic differences(np.log(ts).diff().dropna()) as inputs and get the weights. Divide it by sum of weights if necessary and revert back your estimations by np.exp(predicted_ts.cumsum()).
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92121151
answers question: http://stackoverflow.com/q/52589230

http://stackoverflow.com/comment/93931236
type: Comment
type: QuestionComment
has text: did you figure this out? could you share the solution if you have?
comment on: http://stackoverflow.com/q/52597523
score: 0

http://stackoverflow.com/comment/92356218
type: Comment
score: 0
has text: I didn't test it,but i'm sure @transaction.atomic at last will work.
comment on: http://stackoverflow.com/a/52715328
type: AnswerComment

http://stackoverflow.com/a/52655566
type: Answer
answers question: http://stackoverflow.com/q/52621063
has body: Welp, I'm still working on a way to refresh the browser making an AJAX request when I edit the quantity in admin detail view to see the updated changes to the cart's total price server-side. Not sure how long that will take, but I'll update this answer as soon as I figure it out. In the meantime, here's how I was able to get the subtotals and total: In models.py I added a the field 'subtotal' to my Entry model: subtotal = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) In admin.py: class EntryInline(admin.TabularInline): model = Entry extra = 0 # calls my helper method readonly_fields = ['get_subtotal'] # exclude redundant field being replaced by helper method exclude = ['subtotal'] # gets subtotal of each entry def get_subtotal(self, obj): # for a given entry, find that id entry = Entry.objects.get(id=obj.id) # subtotal the entry quantity * its related price entry_subtotal = obj.quantity * obj.inventory.price # check if entry obj has a subtotal and try to save to db if entry.subtotal != entry_subtotal: try: entry.subtotal = entry_subtotal entry.save() except DecimalException as e: print(e) # return a str representation of entry subtotal return "$" + str(entry_subtotal) # set helper method's description display get_subtotal.short_description = 'subtotal' # initialization of variable total_price = 0 class CartAdmin(admin.ModelAdmin): model = Cart inlines = [EntryInline] # calls get_total helper method below readonly_fields = ['get_total'] exclude = ['total_price'] def get_total(self, obj): # extend scope of variable global total_price # get all entries for the given cart entries = Entry.objects.filter(cart=Cart.objects.get(id=obj.id)) # iterate through entries for entry in entries: # if entry obj has a subtotal add it to total_price var if entry.subtotal: total_price += entry.subtotal print(obj.total_price) # assign cart obj's total_price field to total_price var obj.total_price = total_price # save to db obj.save() # reset total_price var…
score: 0

http://stackoverflow.com/comment/92159981
type: AnswerComment
type: Comment
has text: @Josh: You may want to replace anchors `^` and `$` with word boundary `\b` at the beginning and at the end of the regex.
comment on: http://stackoverflow.com/a/52608158
score: 0

http://stackoverflow.com/comment/92189991
comment on: http://stackoverflow.com/q/52627668
score: 0
has text: I already tried that that method is not working
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52613808
has comment: http://stackoverflow.com/comment/92178950
type: Answer
has comment: http://stackoverflow.com/comment/92163260
has comment: http://stackoverflow.com/comment/92163202
accepted answer of: http://stackoverflow.com/q/52613320
answers question: http://stackoverflow.com/q/52613320
has comment: http://stackoverflow.com/comment/92163125
has comment: http://stackoverflow.com/comment/92162221
has comment: http://stackoverflow.com/comment/92162245
has body: Here is one solution using a defaultdict of set objects and toolz.unique. toolz.unique is equivalent to the itertools unique_everseen recipe available in the docs. The idea is to find keys with lone values and also keys which do not have duplicate values. The union of these two categories make up your result. from collections import defaultdict from toolz import unique dd = defaultdict(set) for k, _, v in input_tuple: dd[k].add(v) lones = {k for k, v in dd.items() if len(v) == 1} uniques = set(unique(dd, key=lambda x: frozenset(dd[x]))) res = tuple(i for i in input_tuple if i[0] in lones | uniques) Result: print(res) ((1, 'name1', 'Noah'), (1, 'name2', 'Liam'), (2, 'name3', 'Mason'), (3, 'name4', 'Mason'), (5, 'name7', 'Elijah'), (5, 'name8', 'Noah'), (5, 'name9', 'Liam'))
score: 0
has comment: http://stackoverflow.com/comment/92164740
type: AcceptedAnswer

key-value-store
tags question: http://stackoverflow.com/q/52610400
type: Tag
tag name: key-value-store

http://stackoverflow.com/comment/92230474
type: Comment
has text: You're right! It does work with any other function! Thanks !
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52648384

http://stackoverflow.com/q/52643462
type: AnsweredQuestion
score: 0
downvote count: 1
has answer: http://stackoverflow.com/a/52645170
tagged with: sqlalchemy
tagged with: pyparsing
type: Question
has comment: http://stackoverflow.com/comment/92220052
answer count: 1
accepted answer: http://stackoverflow.com/a/52645170
tagged with: flask-sqlalchemy
favorite count: 0
tagged with: dsl
has body: I am writing an app using Flask and Flask-SQLAlchemy. I want the user to be able to be able to query the database using a domain specific query language, like parent.name = "foo" AND (name = "bar" OR age = 11). I have written a parser for this language using Pyparsing: import pyparsing as pp query = 'parent.name = "foo" AND (name = "bar" OR age = 11)' and_operator = pp.oneOf(['and', '&amp;'], caseless=True) or_operator = pp.oneOf(['or', '|'], caseless=True) identifier = pp.Word(pp.alphas + '_', pp.alphas + '_.') comparison_operator = pp.oneOf(['=','!=','&gt;','&gt;=','&lt;', '&lt;=']) integer = pp.Regex(r'[+-]?\d+').setParseAction(lambda t: int(t[0])) float_ = pp.Regex(r'[+-]?\d+\.\d*').setParseAction(lambda t: float(t[0])) string = pp.QuotedString('"') comparison_operand = string | identifier | float_ | integer comparison_expr = pp.Group(comparison_operand + comparison_operator + comparison_operand) grammar = pp.operatorPrecedence(comparison_expr, [ (and_operator, 2, pp.opAssoc.LEFT), (or_operator, 2, pp.opAssoc.LEFT) ]) result = grammar.parseString(query) print(result.asList()) This gives me the following output: [[['parent.name', '=', 'foo'], 'and', [['name', '=', 'bar'], 'or', ['age', '=', 11]]]] Now I don't know what to do. How can I dynamically generate a SQLAlchemy query? Are there any libraries that could help with this? Would it be easier to generate raw SQL?
upvote count: 1
tagged with: python
has title: Domain specific query language with Flask-SQLAlchemy

http://stackoverflow.com/comment/92226278
type: AnswerComment
comment on: http://stackoverflow.com/a/52638787
has text: I still find it confusing that the literal case does not require {{}} if I am not inserting a variable using .format. Is there a theoretical reason for that? But of course it works, and I can remember that.
score: 0
type: Comment

http://stackoverflow.com/comment/92272475
type: Comment
has text: so when i use the col.names above i get error message "Error in read.table(file = file, header = header, sep = sep, quote = quote, : more columns than column names"
comment on: http://stackoverflow.com/a/52670732
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92375262
score: 2
has text: What should happen if the file's name is something that can't be a Python identifier, for example `in.txt`, `or.txt`, `def.txt`, `this filename has spaces in it.txt`, `10_9_2018.txt` ...?
comment on: http://stackoverflow.com/q/52724963
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52686128
has answer: http://stackoverflow.com/a/52686137
upvote count: 1
has title: My while loop is infinite even when using digits with isdigit()
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/52686137
has body: Why is my while loop infinite when using bob and (5 for example)? New to python so if this is too basic of a question. from splashkit import * def read_string (prompt): write_line(prompt) result = read_line() return result def read_interger (prompt): line = read_string(prompt) while not line.isdigit(): print("Please enter a whole number") line = read_string(prompt) return int(line) name = read_string("Enter your name: ") age = read_interger("Enter your age: ") print("Hello", name) print("Aged: ", age)
type: Question

http://stackoverflow.com/q/52676110
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52676148
tagged with: python
score: 1
tagged with: pip
upvote count: 1
type: Question
has body: I am using Phyton 2.7 where actually I want to install pip, so that I got get-pip.py from the website and trying to install pip using this command: python get-pip.py But it getting failed after several retry and showing this problem Could not find a version that satisfies the requirement pip I searched different forums and found that maybe there is proxy problem as i am installing this behind a proxy so I found here, this command. python get-pip.py --proxy="http://192.9.210.10:80" But it is producing the same error. I have also tried this python get-pip.py --proxy=192.9.210.10:80 Here, is the the error details:
has comment: http://stackoverflow.com/comment/92290310
answer count: 1
downvote count: 0
has title: Could not find a version that satisfies the requirement pip - installing pip behind proxy in python 2.7
favorite count: 0
has comment: http://stackoverflow.com/comment/92281453
has comment: http://stackoverflow.com/comment/92282302

http://stackoverflow.com/q/52737213
score: 1
has comment: http://stackoverflow.com/comment/92399258
downvote count: 1
tagged with: face-recognition
type: Question
has comment: http://stackoverflow.com/comment/92399534
has answer: http://stackoverflow.com/a/52738055
has title: face_recognition and black&white images
linked to: http://stackoverflow.com/q/75926662
answer count: 1
has body: I'm using face_recognition library to recognise persons on images. According to the library documentation, it supports two input image formats for further processing: RGB (8 bit, 3 channels) and L (black and white). I tried to use face_recognition.api.load_image_file(file, mode='RGB') and it's ok. But I need to use L-mode and that's the point. Problem is that mode='RGB' generates numpy.array (x,y,3) and mode='L' generates numpy.array(x,y). Array should be input later to face_recognition.face_locations and face_recognition.face_encodings functions. If we put array, which was generated in L-mode to face_encodings, we get the following error: TypeError: compute_face_descriptor(): incompatible function arguments. The following argument types are supported: 1. (self: dlib.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),uint8], face: dlib.full_object_detection, num_jitters: int=0) -> dlib.vector 2. (self: dlib.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),uint8], faces: dlib.full_object_detections, num_jitters: int=0) -> dlib.vectors 3. (self: dlib.face_recognition_model_v1, batch_img: List[numpy.ndarray[(rows,cols,3),uint8]], batch_faces: List[dlib.full_object_detections], num_jitters: int=0) -> dlib.vectorss Any ideas, how should I use this library for black&amp;white images to obtain 128-dimensional facemaps? Full listing that throws an error (you can use any person's image as image.jpg): import face_recognition image = face_recognition.load_image_file('image.jpg', mode='L') face_locations = face_recognition.face_locations(image) face_encodings = face_recognition.face_encodings(image, face_locations) Traceback: File "D:/PythonProjects/face_recognition_grayscale_test.py", line 18, in face_encodings = face_recognition.face_encodings(image, face_locations) File "C:\ProgramData\Anaconda3\lib\site-packages\face_recognition\api.py", line 200, in face_encodings return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_ji…
favorite count: 0
has comment: http://stackoverflow.com/comment/133967855
upvote count: 2
tagged with: python
type: AnsweredQuestion
tagged with: dlib
accepted answer: http://stackoverflow.com/a/52738055
tagged with: python-imaging-library

http://stackoverflow.com/q/52707130
tagged with: raspberry-pi3
has body: I am new to python and also to raspberry pi, I have connected the High-Precision AD/DA Board to the RPI 3 model B, and I am looking to change the sampling time of the ADC and I am not sure if I need to change the RPI reading time as well, I have found some code such as byte drate_reg = 3; // Choosing Data Rate register = third register. byte drate_data = 0b11000000; // 11000000 = 3,750SPS SPI.transfer(0x50 | drate_reg); SPI.transfer(0x00); // 2nd command byte, write one register only SPI.transfer(drate_data); // write the databyte to the register delayMicroseconds(10); However when I run the sudo ./ads1256_test to verify if it is properly reading, I am getting this random voltages that are not changing even though I have run with no error the line byte drate_data = 0b11000000; // 11000000 = 3,750SPS. The reading I am getting are:
favorite count: 0
has title: ADC in python, change sampling time
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1
tagged with: raspberry-pi
tagged with: adc
downvote count: 0

http://stackoverflow.com/q/52623233
tagged with: python-3.x
downvote count: 0
possible better answer: http://stackoverflow.com/a/52625065
tagged with: python
has answer: http://stackoverflow.com/a/52625065
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52625133
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52625133
has body: I have some code thus: try: subprocess.check_call( "mysqldump {} {}".format(mysql_args, cmd), shell=True ) except Exception as e: raise Exception("Command failed") The problem is that Exception logging code elsewhere in the application catches this exception and helpfully prints it out - which in this case looks like this: Traceback (most recent call last): File "/apps/django/myapp/tasks.py", line 336, in _safe_mysqldump "mysqldump {} {}".format(mysql_args, cmd), shell=True File "/usr/lib/python3.6/subprocess.py", line 291, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command 'mysqldump -ufoo -pMYSECRETPASSWORD myappdb t1 t2 t3...' returned non-zero exit status 6. During handling of the above exception, another exception occurred: etc. The critical thing being it printed out the mysql connection string. How can I prevent it from doing this?
linked to: http://stackoverflow.com/q/9293042
has title: How can I swallow python exception messages?
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/92383554
comment on: http://stackoverflow.com/a/52728780
has text: That's it and being possible to add as many as you want, this squeleton would be very helpfull (nearly must have tuto). Agreed your github repo is quite large, just need to navigate inside. Qt doc is often in C++ and translation in python is not so easy for non programmers like me. Anyway thanks for the answers
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92874463
score: 0
type: AnswerComment
type: Comment
has text: Thanks! I actually didn't know how to mark the question answered. :)
comment on: http://stackoverflow.com/a/52619484

http://stackoverflow.com/comment/92271652
score: 0
type: Comment
has text: @wim Not sure. How could assigning something to `message` cause a problem? Unless it used to be a read-only attribute, I don't see what could go wrong.
comment on: http://stackoverflow.com/a/52670619
type: AnswerComment

http://stackoverflow.com/comment/92210515
score: 1
has text: I think you should take a look at the answer to the [question in this post](https://stackoverflow.com/questions/30228069/how-to-display-the-value-of-the-bar-on-each-bar-with-pyplot-barh).
comment on: http://stackoverflow.com/q/52638835
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92197852
score: 0
type: Comment
type: QuestionComment
has text: I am confused if you want to initialize `nameoflist` inside the function so what exactly you are passing in `createlist` function?
comment on: http://stackoverflow.com/q/52632240

http://stackoverflow.com/q/52642712
downvote count: 2
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/92217878
has comment: http://stackoverflow.com/comment/92229667
tagged with: list
score: 0
has comment: http://stackoverflow.com/comment/92217960
has answer: http://stackoverflow.com/a/52642738
has answer: http://stackoverflow.com/a/52642861
linked to: http://stackoverflow.com/q/5384570
has body: I am using Python 3 and I have this problem: ListA = [38,40,27,11,1,5,22,7,47,3,11] ListB = [12,16,38,5,40,27,3] I need to count how many times in a row any numbers from ListB appeared in ListA. The output, in this case, should be 3. Because 38, 40 and 27 are numbers that are in ListB, and are first 3 numbers in ListA. In case of no matches (if the first number in ListA is not in ListB), the output should be: 0.
answer count: 4
has comment: http://stackoverflow.com/comment/92224765
possible better answer: http://stackoverflow.com/a/52642738
has comment: http://stackoverflow.com/comment/92218247
has comment: http://stackoverflow.com/comment/92226736
has comment: http://stackoverflow.com/comment/92218067
accepted answer: http://stackoverflow.com/a/52642861
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52642890
has comment: http://stackoverflow.com/comment/92218189
has comment: http://stackoverflow.com/comment/92220811
has comment: http://stackoverflow.com/comment/92217824
favorite count: 0
has title: How many leading entries from a list are found in another list
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/59395567

http://stackoverflow.com/q/52658247
has comment: http://stackoverflow.com/comment/92268078
has comment: http://stackoverflow.com/comment/92268583
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92252561
favorite count: 0
has body: I imported a custom font called "Celtic-Bit Thin" from a website to use in a project. The file had the correct extension (.ttf) that pygame can import but when used, only the bottom half of the string of text that is displayed is shown (You can only see the bottom half of each letter in the string of text displayed in the font I chose). I'm not sure if it is a problem with the font or the way I implemented it. I tried: gameFont = pygame.font.Sysfont("Celtic-Bit Thin", 24) font.render("Hello world!", False, (0,0,0)) I also tried doing it with pygame.font.Font()but it didn't work either. Is the font simply incompatible with pygame or is there some other requirement for importing fonts? EDIT: Here is a minimal, runnable example: import pygame pygame.init() pygame.font.init() screen = pygame.display.set_mode((800,600)) gameFont = pygame.font.SysFont("Celtic-Bit Thin", 36) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: runnung = False screen.fill((255,255,255)) screen.blit(gameFont.render("Hello World!",False,(0,0,0)), (300, 300)) pygame.display.flip() pygame.quit() AND here is where I downloaded the font
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/52669667
has comment: http://stackoverflow.com/comment/92268959
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/92268427
has title: Top half of text in pygame is not being displayed
score: 1

http://stackoverflow.com/a/52658842
has body: You can do it with list comprehension, just by checking to see whether the nested list is empty or not, and, if not, replacing the outer list with the inner list (by index). data = [[], [], 'around_the_world', 'around_the_globe', [], [], [], []] result = [d[0] if d else d for d in data] print(result) # OUTPUT # [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52658767
has comment: http://stackoverflow.com/comment/92248329

http://stackoverflow.com/comment/135669069
type: Comment
comment on: http://stackoverflow.com/a/53373130
score: 1
type: AnswerComment
has text: In conclusion, the OP should have been asked WHY they wanted to change the calendar and then offering a more appropriate solution rather than coming up with simple mechanics without knowing the context.

http://stackoverflow.com/a/52630388
has body: You can add any number of filter transformations to a chart, by calling transform_filter multiple times. For example: chart.transform_filter( selection1 ).transform_filter( selection2 ) All transformations will be applied in the order that they are added to the chart. The other possible approach is to use boolean logic to combine multiple selections in a single filter transform; e.g. chart.transform_filter( selection1 &amp; selection2 ) In your case, this should have the same effect.
answers question: http://stackoverflow.com/q/52628405
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/52628405
type: Answer

http://stackoverflow.com/comment/92334040
has text: I now see E.Serra already posted this method in a comment to your question.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52703700
type: Comment

http://stackoverflow.com/q/52739632
favorite count: 0
tagged with: aws-lambda
has title: Lambda + Python + Exit Code
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52739848
type: Question
score: 9
upvote count: 9
tagged with: amazon-web-services
answer count: 1
downvote count: 0
has body: I've encountered an issue with a simple AWS Lambda function written in Python. When I run my Lambda function, my code is running as expected, the result is correct, but still ends with an error code (exit code): "Process exited before completing request", this is causing the Lambda to run 3 times (async). Do you have any best practice to manage the exit code for Lambda ? #!/usr/bin/python import boto3 import sys import tweepy import datetime session = boto3 # Init s3 client s3 = session.resource('s3') def get_data_and_push(s3_bucket, s3_key, user): # Retrieve CSV file try: dest = s3.Object(s3_bucket, s3_key) dest.download_file(tmpfile) except Exception, e: print 'An error occured while trying to download CSV file' print 'This exception has been thrown :' print e sys.exit(1) # Authenticate to Twitter try: auth = tweepy.OAuthHandler(t_consumer_key, t_consumer_secret) auth.set_access_token(t_access_token_key, t_access_token_secret) api = tweepy.API(auth) except Exception, e: print 'Cannot authenticate to Twitter.' print 'This exception has been thrown :' print e sys.exit(2) data = api.get_user(user) print 'User : ' + data.screen_name print 'Followers : ' + str(data.followers_count) print 'Friends : ' + str(data.friends_count) print '-----------' # Get today's date today = datetime.datetime.now().strftime("%Y-%m-%d") # Write result try: # Write result at the end of the file file = open(tmpfile, 'a') file.write(today + ',' + str(data.followers_count) + ',' + str(data.friends_count)+ '\n') file.close() except Exception, e: print 'Unable to write in temp file' print 'This exception has been thrown :' print e sys.exit(5) # Upload final file try: # Push file to S3 dest.upload_file(tmpfile) except Exception, e: print 'An error occured while trying to upload CSV file' print 'This exception has been thrown :' print e sys.exit(6) def main(event, context): for user in userlist: get_data_and_push(bucket, 'export_' + user + '.csv', user) sys.exit(0) Thanks for your help,
has answer: http://stackoverflow.com/a/52739848

http://stackoverflow.com/comment/92315016
comment on: http://stackoverflow.com/q/52694063
has text: Function name `process_order` gives an idea, that only one order has been processed. so it's not a good idea to process many orders there at once. Moreso, if you return an order total from this function, you can sum over it afterwards to have total: `total = sum(map(process_order, orders))`. This will save you a lot of time to improve your functions while line with counting total still be the same.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52608140
answers question: http://stackoverflow.com/q/52607849
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92150346
has comment: http://stackoverflow.com/comment/92160614
has comment: http://stackoverflow.com/comment/92160684
has comment: http://stackoverflow.com/comment/92151336
upvote count: 1
has comment: http://stackoverflow.com/comment/92158753
type: AcceptedAnswer
has body: No, there isn't really a way to do this with one loop, since the task involves a double loop, but you can make it more efficient, eg use a list comprehension to build each line so you only call print once per line. You could use recursion, but that's less efficient, and it doesn't really eliminate the loop, it just implements it in a different way. Here's a list comp version of your code, wrapped in a function. def show_pattern(n): for i in range(n, 0, -1): print(''.join([str(j)*i for j in range(n, 0, -1)])) FWIW, here's a one-liner version that's marginally more efficient, but of course the time complexity is still O(n²). And I think you'll agree that it's a bit harder to read. ;) print('\n'.join([''.join([str(j)*i for j in range(n, 0, -1)]) for i in range(n, 0, -1)])) One could argue that the complexity is actually O(n³), since str(j)*i is performed internally by a loop, but that loop runs at C speed, so we can pretend that it's a primitive operation.
has comment: http://stackoverflow.com/comment/92160344
accepted answer of: http://stackoverflow.com/q/52607849
has comment: http://stackoverflow.com/comment/92161007

http://stackoverflow.com/q/52707117
downvote count: 0
has comment: http://stackoverflow.com/comment/92343800
type: Question
has title: Extracting all Colors from Style of Span Class in web page using Python
accepted answer: http://stackoverflow.com/a/52709188
favorite count: 0
upvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/52709188
has body: This is my curent code ,im trying to import all the 'background-color rgb and values from the style in span class.from site below https://www.asianpaints.com/colour/colour-catalogue.html screenshot of page html import requests from bs4 import BeautifulSoup as bs import os URL = "https://www.asianpaints.com/colour/colour-catalogue.html" r = requests.get(URL) collec = bs(r.content, 'lxml') color= collec.find_all(class_='color-box3') print(color)
tagged with: beautifulsoup
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/52612012
has title: separate characters from borders after thresholding
tagged with: python
has answer: http://stackoverflow.com/a/52613594
favorite count: 0
type: UnansweredQuestion
upvote count: 3
tagged with: automatic-license-plate-recognition
has comment: http://stackoverflow.com/comment/92160107
tagged with: image-thresholding
tagged with: opencv
score: 3
tagged with: image-processing
type: Question
has comment: http://stackoverflow.com/comment/92177996
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92159117
has comment: http://stackoverflow.com/comment/92159259
has body: I would like to separate characters from borders after thresholding the images: Original image Touching areas Desired Output I'm using python and OpenCV to do the thresholding. Thanks in advance for your help. This is part of the code that makes the threshold def threshold_image(img): gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) resized_img = cv2.resize(gray_img , None , fx=5.0 , fy=5.0 , interpolation=cv2.INTER_CUBIC) resized_img = cv2.GaussianBlur(resized_img,(5,5),0)#(5,5) equalized_img = cv2.equalizeHist(resized_img) # height of the image alto = int(resized_img.shape[0]) # shape[0] = rows # width of the image ancho = int(resized_img.shape[1]) # shape[1] = cols reduced = cv2.cvtColor(reduce_colors(cv2.cvtColor(equalized_img, cv2.COLOR_GRAY2BGR), 6), cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(reduced, 110, 255, cv2.THRESH_BINARY)#64 cv2.imwrite('licence_plate_mask.png', mask) return mask

dicom
tag name: dicom
type: Tag
tags question: http://stackoverflow.com/q/52708245
tags question: http://stackoverflow.com/q/52725553
tags question: http://stackoverflow.com/q/52717604
tags question: http://stackoverflow.com/q/52633803

http://stackoverflow.com/comment/92212955
type: Comment
has text: Thank you! Did not notice that flag. It's nice solution since it does not add an extra step, but there is the downside that it really does not allow tab completion if there are multiple variable names starting with the same letter(s). It just prints the available options. I will add an example picture.
score: 0
comment on: http://stackoverflow.com/q/52626799
type: QuestionComment

http://stackoverflow.com/comment/92285802
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52678422
score: 1
has text: @fred.schwartz, i answered your question, does that help?, i used a sample dataframe. you can replace it with your dataframe read from a csv

http://stackoverflow.com/comment/120592730
has text: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.
type: Comment
comment on: http://stackoverflow.com/a/68222258
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92314718
has text: Just so I'm clear, you're trying to evaluate this string without using eval()?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52693933

http://stackoverflow.com/a/52711654
has body: Heres a simple, one, all it looks like you're doing is remove the number, and make "A1" to A01". It assumes that each item is a string, if that is wrong please tell me. def transItem(item): parts = item.split() aLet = parts[0][0] aNum = parts[0][1:] if len(aNum) &lt;=1: aNum = "0"*(2-len(aNum)) + aNum return aLet+aNum oldList = ["A1 (76113)","A2 (7614)","A11 (73887)"] newList = [transItem(itm) for itm in oldList]
answers question: http://stackoverflow.com/q/52711412
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/52711412
type: Answer

http://stackoverflow.com/q/52652264
accepted answer: http://stackoverflow.com/a/52656676
type: AnsweredQuestion
downvote count: 0
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52656676
type: Question
has title: Set custom seaborn color palette using hex codes, and name the colors
has comment: http://stackoverflow.com/comment/92238595
upvote count: 11
has body: My company has a formal color palette so I need to use these colors in my seaborn charts. I would therefore like to set the default seaborn color palette, and give these colors easy-to-use names such as 'p' for purple and 'g' for green. Here is what I have so far for code: # Required libraries import matplotlib.pyplot as plt import seaborn as sns # Wanted palette details enmax_palette = ["#808282", "#C2CD23", "#918BC3"] color_codes_wanted = ['grey', 'green', 'purple'] # Set the palette sns.set_palette(palette=enmax_palette) # Assign simple color codes to the palette Please help me to assign simple names to the colors using my "color_codes_wanted" list.
answer count: 1
has comment: http://stackoverflow.com/comment/92238739
favorite count: 0
has comment: http://stackoverflow.com/comment/92238684
tagged with: seaborn
has comment: http://stackoverflow.com/comment/92238530
tagged with: python
score: 11

http://stackoverflow.com/comment/92181424
type: Comment
type: QuestionComment
has text: your expected is a list, but you are mentioning a dictionary , is your main goal to achieve a dictionary with this format `{(len, sum) : word}`
comment on: http://stackoverflow.com/q/52623971
score: 0

http://stackoverflow.com/q/52621192
has comment: http://stackoverflow.com/comment/92176128
has body: I want to control the input of the class Webpage. Meaning, I want to be sure that the webpage's link is appropriately provided, e.g. 'http://example.com'. class Webpage(object): def __init__(self, link): prefix = ['http', 'https'] suffix = ['com', 'net'] try: if link.split(':')[0] in prefix and link.split('.')[-1] in suffix: self.link = link except: raise ValueError('Invalid link') def get_link(self): ''' Used to safely access self.link outside of the class Returns: self.link ''' return self.link def __str__(self): return str(self.link) However, when I try code: test_link = Webpage('example.com') I do not get ValueError, as I would expect. Call of methods: test_link.get_link() print(test_lint) result in AttributeError: 'Webpage' object has no attribute 'link' which indicates that try/except worked partially - try did not execute self.link = link, however except statement wasn't executed. An example: test_link = Webpage('http://example.com') works fine with get_link() and print methods of that class. Will appreciate any hint.
score: 4
type: Question
upvote count: 4
has title: OOP / try except statements in __init__ of class
downvote count: 0
has answer: http://stackoverflow.com/a/52621372
tagged with: init
has answer: http://stackoverflow.com/a/52621414
favorite count: 0
tagged with: python
answer count: 4
possible better answer: http://stackoverflow.com/a/52621508
has comment: http://stackoverflow.com/comment/92176234
has answer: http://stackoverflow.com/a/52621353
has answer: http://stackoverflow.com/a/52621508
tagged with: except
accepted answer: http://stackoverflow.com/a/52621353
tagged with: try-catch
type: AnsweredQuestion
tagged with: oop

http://stackoverflow.com/q/52717742
upvote count: 1
downvote count: 1
tagged with: quicksort
has title: how to sort a string into alphabetical order without inbuilt functions
has answer: http://stackoverflow.com/a/52718285
has body: My Code: alphabet = "abcdefghijklmnopqrstuvwxyz" def sort3(): string = input("please enter a 3 character string: ") string1 = string[0] string2 = string[1] string3 = string[2] stringpos1 = alphabet.index(string1) stringpos2 = alphabet.index(string2) stringpos3 = alphabet.index(string3) if stringpos3 &gt; stringpos2 &gt; stringpos1: # 123 print(string1 + string2 + string3) elif stringpos2 &gt; stringpos3 + stringpos1: # 132 print(string1 + string3 + string2) elif stringpos3 &gt; stringpos1 &gt; stringpos2: # 213 print(string2 + string1 + string3) elif stringpos1 &gt; stringpos3 &gt; stringpos2: # 231 print(string2 + string3 + string1) elif stringpos2 &gt; stringpos1 &gt; stringpos3: # 312 print(string3 + string1 + string2) elif stringpos1 &gt; stringpos2 &gt; stringpos3: # 321 print(string3 + string2 + string1) sort3() This is the way i did, i want to know how i can do this for any string (meaning any lengthen string)
type: Question
tagged with: string-length
tagged with: string
tagged with: sorting
favorite count: 0
has answer: http://stackoverflow.com/a/52718088
has comment: http://stackoverflow.com/comment/92360984
has answer: http://stackoverflow.com/a/72536057
has comment: http://stackoverflow.com/comment/92362932
score: 0
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/92361122
type: UnansweredQuestion

http://stackoverflow.com/a/53539051
upvote count: 2
answers question: http://stackoverflow.com/q/52666624
downvote count: 0
type: Answer
has body: I suggest you try using Anaconda See this tutorial Summarizing: 1. Install Miniconda or Anaconda and then go to "Anaconda Prompt": simple use Windows and start to write "anaconda" after installing: it should appear. 2. Now, simply run: conda create --name tf_gpu tensorflow-gpu Done! To be sure, you can test it: In "Anaconda Prompt": Activate environment using ‘activate tf_env’. Go to python console using ‘python’ In Python, just write: import tensorflow as tf sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) Info about your card should appear. Now, just create a new project in your IDE, choosing "Existing Interpreter", selecting the Virtual Envirment that we just created ("tf_gpu"), and your new files inside the project will run on the gpu. Hope I helped! Thanks to Harveen Singh (I tried many tutorials, before seeing one that worked and was easy)
score: 2

http://stackoverflow.com/comment/92303572
comment on: http://stackoverflow.com/a/52688207
type: Comment
score: 0
type: AnswerComment
has text: just now i have placed my code in your code. please have a look into it

http://stackoverflow.com/q/52682156
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/92294123
upvote count: 1
type: Question
has title: How do I get rid of these symbols from the text fields when reading a CSV file?
tagged with: python-unicode
has answer: http://stackoverflow.com/a/52686876
downvote count: 0
answer count: 1
has body: Every time I open a CSV in Python, I keep seeing these weird symbols that represent the punctuation and special characters within the text fields. For example: import pandas as pd import csv data = pd.read_csv("Test.csv", encoding="ISO-8859-1") #utf-8 encoding doesn't work data.head() The column with text will have something like "Assassinâ\x80\x99s creed origins". So I guess you're wondering how I created the csv in the first place? Here's the code I used: def updateSubs_file(): upload_count = 0 import csv location = "csvs" filename = "Test.csv" file = location + filename with open(file, 'w', newline='', encoding='utf-8') as file: a = csv.writer(file, delimiter=',') headers = ["Title","Url","Author","Score"] a.writerow(headers) for sub in subStats: a.writerow(subStats[sub][0]) upload_count+=1 print(str(upload_count) + " rows have been uploaded") updateSubs_file() So I can see there's already an encoding mismatch when creating the csv and opening but I added the encoding="" arguments initially to avoid Unicode Decode Errors. This may/may not be a factor in my issue. Your help would be appreciated in working out what is happening to my csvs when I'm uploading/reading them in Python.
score: 1
favorite count: 0

http://stackoverflow.com/q/52735231
has answer: http://stackoverflow.com/a/65483536
type: AnsweredQuestion
upvote count: 19
tagged with: image-processing
has answer: http://stackoverflow.com/a/52737768
has body: I am trying to get a list of an image's pixels that are different from a specific color using NumPy. For example, while processig the following image: I've managed to get a list of all black pixels using: np.where(np.all(mask == [0,0,0], axis=-1)) But when I try to do: np.where(np.all(mask != [0,0,0], axis=-1)) I get a pretty strange result: It looks like NumPy has returned only the indices were R, G, and B are non-0 Here is a minimal example of what I'm trying to do: import numpy as np import cv2 # Read mask mask = cv2.imread("path/to/img") excluded_color = [0,0,0] # Try to get indices of pixel with different colors indices_list = np.where(np.all(mask != excluded_color, axis=-1)) # For some reason, the list doesn't contain all different colors print("excluded indices are", indices_list) # Visualization mask[indices_list] = [255,255,255] cv2.imshow(mask) cv2.waitKey(0)
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52735832
accepted answer: http://stackoverflow.com/a/52737768
tagged with: image
has answer: http://stackoverflow.com/a/52735832
score: 19
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/54214017
has title: How to select all non-black pixels in a NumPy array?
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/130235092
comment on: http://stackoverflow.com/a/52629475
type: AnswerComment
type: Comment
score: 2
has text: using `list` instead of `List` as typing annotation in python 3.8 and older will cause `Typeerror: type object is not subscriptable `

http://stackoverflow.com/comment/92254509
has text: There is no error logged in the browser console ...
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52624102
type: QuestionComment

http://stackoverflow.com/comment/92397805
score: 0
has text: How you send data from `frontend`? can you show your request?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52733540

http://stackoverflow.com/a/52652153
accepted answer of: http://stackoverflow.com/q/52651905
type: Answer
has comment: http://stackoverflow.com/comment/92237636
has body: iter is expected to have no side effects. By violating this assumption, your code breaks all sorts of things. For example, the standard test for whether a thing is iterable: try: iter(thing) except TypeError: do_whatever() will reset your file. Similarly, the itertools consume recipe: def consume(iterator, n=None): "Advance the iterator n-steps ahead. If n is None, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to the empty slice starting at position n next(islice(iterator, n, n), None) will produce an incorrect file position instead of advancing n records after consume(your_file, n). Skipping the first few records with next before a loop will also fail: f = MySpecialFile(whatever) next(f) # Skip a header, or try, anyway. for record in f: # We get the header anyway. uhoh()
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/92236502
answers question: http://stackoverflow.com/q/52651905
has comment: http://stackoverflow.com/comment/92241315
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52605559
upvote count: 1
has comment: http://stackoverflow.com/comment/92163949
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52604956
type: Answer
has body: Here is what works for me (but it may not be the best performing solution): I assume you can somehow cast your input into a dict of the form: d = {'User 1': [123, 254, 225, 367, 125, 745, 587], 'User 2': [333, 444, 225, 123 ,254], ...} Now, with the given pattern pattern = [254, 225, 125, 587, 745] lets produce a second dict which holds the output: d_out = {} for key in d.keys(): d_out[key] = [] for value in pattern: d_out[key].append(value in d[key]) The performance maybe not optimal if your pattern list is big (because of the loop), it should be more or less independent of the size of the user data though. Now I take pattern as a mask and use a custom version of the itertools.compress function to get the result (the function produced an error on my machine and I could not use it directly, sorry): for key in d.keys(): print(key, [data for data, mask in zip(pattern, d_out[key]) if not mask]) which yields the output: User 1 [] User 2 [125, 587, 745] Maybe this is something you can start from.

http://stackoverflow.com/comment/92366344
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52720594
score: 1
has text: is that continuous space or discrete space?

http://stackoverflow.com/comment/92640501
score: 0
type: Comment
type: AnswerComment
has text: I don't know what the input strings can be like, it's hard to say.The regex101 matches `Article 13.2(k)(ii)` just as it matches `Section 13.2(k)(ii)`. If you want only a single digit after `Article`, leave off the `\.\d+` to match only whole numbers like 13.
comment on: http://stackoverflow.com/a/52705504

http://stackoverflow.com/comment/92335455
has text: Thanks for the response, it answer the question
comment on: http://stackoverflow.com/a/52704112
type: AnswerComment
score: 0
type: Comment

argparse
tags question: http://stackoverflow.com/q/52654217
tag name: argparse
tags question: http://stackoverflow.com/q/52690841
tags question: http://stackoverflow.com/q/52594207
type: Tag
tags question: http://stackoverflow.com/q/52636309
tags question: http://stackoverflow.com/q/52605094

http://stackoverflow.com/q/52690001
has body: I'm a novice to Python and Django. I am learning it from a tutorial but stuck in between. Already tried with some other StackOverflow solution but no luck. The following error I'm getting Error: NoReverseMatch at /catalog/ Someone, please help me with the mistake that I have made. url.py urlpatterns += [ path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'), ] view.py @permission_required('catalog.view_all_books') def renew_book_librarian(request, pk): """View function for renewing a specific BookInstance by librarian.""" book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): book_renewal_form = RenewBookForm(request.POST) # Check if the form is valid: if book_renewal_form.is_valid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) book_instance.due_back = book_renewal_form.cleaned_data['renewal_date'] book_instance.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-borrowed')) # If this is a GET (or any other method) create the default form. else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) book_renewal_form = RenewBookForm(initial={'renewal_date': proposed_renewal_date}) context = { 'form': book_renewal_form, 'book_instance': book_instance, } return render(request, 'catalog/book_renew_librarian.html', context) model.py class BookInstance(models.Model): """ Model representing a specific copy of a book (i.e. that can be borrowed from the library). """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignK…
type: Question
has answer: http://stackoverflow.com/a/71396140
has comment: http://stackoverflow.com/comment/92307782
has title: How to get solve NoReverseMatch Django 2.0
tagged with: django
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/92307853
has comment: http://stackoverflow.com/comment/92308910
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92307979

http://stackoverflow.com/comment/92298008
has text: What text editor/code editor/IDE do you use?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52685192
type: QuestionComment

http://stackoverflow.com/comment/131054248
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52655013
has text: cv2 Also has an issue with running in pythons on a MacOS `IDLE` app & when using `sublimeText4` using python3 build. but I confirm it works using `Terminal` application. directly calling the file or running the code inside terminal using python3 <then your code>.

http://stackoverflow.com/comment/92204054
has text: @zwer yes , its always at 3rd index.
comment on: http://stackoverflow.com/q/52635321
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92312577
has text: The one liner would *also* loop through it...
score: 2
comment on: http://stackoverflow.com/q/52692866
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92154851
type: Comment
has text: Could you provide the logs?
comment on: http://stackoverflow.com/q/52600262
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92211629
score: 0
type: Comment
type: QuestionComment
has text: Please add more information to this question. Do you want all all values in column 1 to be replaced with the values of column 2? While this can easily be done using `df[1] = df[2].apply(lambda x: x)`, it does not make any sense to do, so the question is are you trying to replace null values or what?
comment on: http://stackoverflow.com/q/52639563

http://stackoverflow.com/q/52746769
upvote count: 3
has answer: http://stackoverflow.com/a/66532786
has title: Random forest sklearn
has comment: http://stackoverflow.com/comment/92418595
has answer: http://stackoverflow.com/a/59598809
tagged with: scikit-learn
has body: I am confused if explicit cross validation is necessary for Random Forest? In random forest we have Out of Bag samples and this can be used for computing test accuracy. Is explicit cross validation necessary. Is there any benefit of explicitly using CV in Random forest? I find it confusing to understand how CV in Random forest works based on this code Here is my code: model = BaggingClassifier(base_estimator=cart, n_estimators=num_trees, random_state=seed) results = cross_validation.cross_val_score(model, X, Y, cv=kfold) print(results.mean())
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52822730
tagged with: python
has answer: http://stackoverflow.com/a/52753112
downvote count: 0
has answer: http://stackoverflow.com/a/62515471
has answer: http://stackoverflow.com/a/52772898
type: Question
score: 3
tagged with: random-forest
tagged with: cross-validation
answer count: 6

http://stackoverflow.com/comment/92348932
comment on: http://stackoverflow.com/q/52711297
score: 0
type: Comment
type: QuestionComment
has text: problem is how to append the header, :-)

http://stackoverflow.com/q/52685367
answer count: 1
has comment: http://stackoverflow.com/comment/92298340
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52685383
tagged with: python
has comment: http://stackoverflow.com/comment/92300621
has body: hi guys I need help understanding python functions! can the returned value of a python function be from a dictionary? also, is it really necessary for a python function to have a returned value?
has title: understanding python function; returned value
type: Question
score: 0

http://stackoverflow.com/q/52728119
score: 4
favorite count: 0
tagged with: pandas
has body: I am doing some simple ML project and I have a simple test scenario to test my code: import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from numpy.random import randn import random import matplotlib.pyplot as plt class Model(): def __init__(self, model_name): self.model_name = model_name self.model = LinearRegression() self.model_data = pd.DataFrame(columns=['X','Y']) def retrain(self): self.model.fit(self.model_data'X',self.model_data['Y']) def choose_value(self): y_intercept = self.model.intercept_ pass def accept_value(self,x_value,y_value): temp_df = pd.DataFrame(data=x_value,y_value,columns=['X','Y']) new_model.model_data = new_model.model_data.append(temp_df) def __str__(self): return f'The formula for the line is y = {list(self.model.coef_)[0]}x + {self.model.intercept_}' The scenario is as follows: df = pd.DataFrame(data = 5*randn(50,1),columns=['X']) new_list = [] for i in df['X']: new_list.append(-6.5*i + 100 + random.normalvariate(0,10)) df['Y'] = new_list new_model = Model('1') for i in range(len(df)): x_value, y_value = df.loc[i] new_model.accept_value(x_value,y_value) new_model.retrain() print(new_model) plt.scatter(x=df['X'],y=df['Y']) When I execute the scenario, everything works perfectly, but when I copy the same code inside of a method like this: def simulate(): df = pd.DataFrame(data = 5*randn(50,1),columns=['X']) new_list = [] for i in df['X']: new_list.append(-6.5*i + 100 + random.normalvariate(0,10)) df['Y'] = new_list new_model = Model('1') for i in range(len(df)): x_value, y_value = df.loc[i] new_model.accept_value(x_value,y_value) new_model.retrain() print(new_model) plt.scatter(x=df['X'],y=df['Y']) simulate() Then I get following error message: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-250-2d4e86d2a592&gt; in &lt;module&gt;() 14 plt.scatter(x=df['X'],y=df['Y']) 15 ---&gt; 16 simulate() &lt;ipython-i…
tagged with: python
has answer: http://stackoverflow.com/a/52728409
has title: Code works, but not when inserted inside of a method
type: AnsweredQuestion
tagged with: linear-regression
accepted answer: http://stackoverflow.com/a/52728409
type: Question
upvote count: 4
answer count: 1
downvote count: 0
tagged with: scikit-learn

http://stackoverflow.com/comment/92140955
type: QuestionComment
comment on: http://stackoverflow.com/q/52601437
has text: Can you provide a [mcve]?
score: 0
type: Comment

http://stackoverflow.com/q/52745665
type: Question
answer count: 2
downvote count: 0
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92416225
linked to: http://stackoverflow.com/q/26921651
has body: I have a dataframe with a multi index 'date' and 'time'. I would like to delete the 2 last rows of each days. For example: Date Time colA colB 01/01/2018 08:00 15 'abc' 01/01/2018 09:00 16 'abd' 01/01/2018 11:00 17 'abe' 01/01/2018 14:00 18 'abf' 03/01/2018 11:30 19 'abg' 03/01/2018 18:00 20 'abh' 03/01/2018 19:00 21 'abi' 03/01/2018 19:20 22 'abj' 04/01/2018 14:00 23 'abk' 04/01/2018 16:00 24 'abl' 04/01/2018 17:00 25 'abm' 04/01/2018 18:00 26 'abn' 04/01/2018 19:00 27 'abo' would become: Date Time colA colB 01/01/2018 08:00 15 'abc' 01/01/2018 09:00 16 'abd' 03/01/2018 11:30 19 'abg' 03/01/2018 18:00 20 'abh' 04/01/2018 14:00 23 'abk' 04/01/2018 16:00 24 'abl' 04/01/2018 17:00 25 'abm' How can I achieve this?
has title: Delete 2 last rows of each day in a dataframe
possible better answer: http://stackoverflow.com/a/52745764
tagged with: python
linked to: http://stackoverflow.com/q/38798058
has answer: http://stackoverflow.com/a/52745764
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: dataframe
has answer: http://stackoverflow.com/a/52746066
accepted answer: http://stackoverflow.com/a/52746066

http://stackoverflow.com/comment/92394649
type: Comment
has text: @toti08 First of all thank you for answer, I want to take elements of 00000001 0001000 and put in array be like dynamic_arraylisy[ "00000001"," 0001000"]
comment on: http://stackoverflow.com/q/52734754
score: 0
type: QuestionComment

http://stackoverflow.com/comment/92306999
score: 1
comment on: http://stackoverflow.com/q/52689967
type: Comment
type: QuestionComment
has text: Your sample string is invalid. Add single quotes around them.

http://stackoverflow.com/comment/92805266
type: QuestionComment
has text: @GuilhermeUzeda Session is not fork-safe, in this case Tensorflow stucks because of some lock. Or you mean `subrocess` can deal with it? https://github.com/tensorflow/tensorflow/issues/2448 https://stackoverflow.com/questions/37874838/forking-a-python-process-after-loading-tensorflow https://stackoverflow.com/questions/36610290/tensorflow-and-multiprocessing-passing-sessions
score: 0
comment on: http://stackoverflow.com/q/52700621
type: Comment

http://stackoverflow.com/q/52617658
downvote count: 1
score: -1
has body: This is my code and I keep getting a NoneType object is not iterable error on the second last line. for key, value in termdic.items(): # value = List of lists where 1st entry is a documentID and the second is a position i=0 temp = [] for v in value: # print(v) current_doc = v[0] if i==0: prev_doc = v[0] i+=1 if (prev_doc == current_doc): temp.append(v[1]) if (prev_doc != current_doc): if key not in term_position_dic: # initialize term_position_dic[key] = prev_doc,len(temp),temp # encode(temp) # delta_position_dic[key] = prev_doc,len(temp),temp else: term_position_dic[key].append([prev_doc,len(temp),temp]) # encode(temp) # delta_position_dic[key].append([prev_doc,len(temp),temp]) # We are in the reset phase prev_doc= current_doc temp = [v[1]] Note: Termdic is a dic of key= term and value = list of lists which = [[docID, number of occurrences, [list of the positions of the word in the document.] uncompressed_dic = {} for k, value in term_position_dic.items(): temparray = [] for v in value: docID = v[0] count = v[1] poslist = v[2] tarray = [docID, count].extend(poslist) temparray.extend(tarray) uncompressed_dic[k] = temparray Also, why would docID, count, posList be None after iteration, it shows as it is when I print it but when the final array is build all values are None.
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92169545
tagged with: nonetype
upvote count: 0
has answer: http://stackoverflow.com/a/52617718
favorite count: 0
has title: NoneType object is not iterable in python, I am avoiding the common mistakes like using assignment operator
tagged with: python
has answer: http://stackoverflow.com/a/52617689
type: UnansweredQuestion

http://stackoverflow.com/comment/92190925
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52628068
has text: Bazingaa, because I the tempfeatures list is edited randomly, but has to be cleared for the next character's feature randomisation.

http://stackoverflow.com/q/52600652
score: 0
has body: I am trying to plot a repeated periodic solution using matplotlib in python. I have the solution for one period, I have provided a sample test code below of the individual plot: import matplotlib import numpy as np from matplotlib import pyplot as plt File1 = np.genfromtxt('File1.dat') fig,(ax1) = plt.subplots() fig.subplots_adjust(hspace=1.0) A1 = ax1.imshow(File1.T,extent=[-1,1,-1,1],cmap='coolwarm',origin='lower') cbar = fig.colorbar(A1,orientation = 'vertical') ax1.set_xticks([-1,0.0,1],minor=False) ax1.set_yticks([-1,0.0,1],minor=False) ax1.set_yticklabels(['$-1$','$0$','$1$'],minor=False) ax1.set_yticklabels(['$-1$','$0$','$1$'],minor=False) plt.xlabel('x', fontsize=22) plt.ylabel('y', fontsize=22) plt.title('Title', fontsize = 24) plt.show() where the sample .dat file, File1.dat is given by 0.863 0.863 0.863 0.863 0.610 0.863 0.863 0.863 0.863 I want to plot this periodic solution now repeatedly on the same plot. To be specific, this plot ranges from x = [-1,1] and y = [-1,1], but I want to make it range from x = [-20,20] and y = [-20,20] repeating this same solution over and over (periodically). How can I code this efficiently? Copying the data in the .dat file may work for this simple example but my actual .dat file is very large and that method just isn't efficient. Thanks!
answer count: 1
accepted answer: http://stackoverflow.com/a/52600789
tagged with: python
tagged with: plot
type: AnsweredQuestion
tagged with: matplotlib
has title: plotting repeated periodic solution
type: Question
tagged with: periodicity
has answer: http://stackoverflow.com/a/52600789

http://stackoverflow.com/q/52598788
tagged with: matcher
accepted answer: http://stackoverflow.com/a/52599446
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52599446
tagged with: python
tagged with: nlp
has title: spaCy: custom attributes not matching correctly?
type: AnsweredQuestion
tagged with: spacy
downvote count: 0
score: 1
type: Question
has body: I have been having problems using custom extension attributes with the recently improved Matcher (spaCy 2.012). Even a simple example (mostly copied from here) is not working as I expected: import spacy from spacy.tokens import Token from spacy.matcher import Matcher nlp = spacy.load('en') text = 'I have apple. I have had nothing.' doc = nlp(text) def on_match(matcher, doc, id, matches): print('Matched!', matches) Token.set_extension('is_fruit', getter=lambda token: token.text in ('apple', 'banana')) pattern1 = [{'LEMMA': 'have'}, {'_': {'is_fruit': True}}] matcher = Matcher(nlp.vocab) matcher.add('HAVING_FRUIT', on_match, pattern1) matches = matcher(doc) print(matches) This gives the following output: [(13835066833201802823, 1, 2), (13835066833201802823, 5, 6), (13835066833201802823, 6, 7)] In other words, the rule correctly matches on the span 'have' (1, 2), but incorrectly matches 'have' (5, 6) and 'had' (6, 7). Furthermore, the callback function is not called. The custom attribute appears to be ignored. When I add a new pattern, as follows: Token.set_extension('nope', default=False) pattern2 = [{'LEMMA': 'nothing'}] matcher.add('NADA', on_match, pattern2) matches = matcher(doc) print(matches) I get the following output: [(12682145344353966206, 1, 2), (12682145344353966206, 5, 6), (12682145344353966206, 6, 7)] Matched! [(12682145344353966206, 1, 2), (12682145344353966206, 5, 6), (12682145344353966206, 6, 7), (5033951595686580046, 7, 8)] [(12682145344353966206, 1, 2), (12682145344353966206, 5, 6), (12682145344353966206, 6, 7), (5033951595686580046, 7, 8)] The first rule functions as above. Then the second rule triggers, along with the callback function (which prints the message). There is an additional correct match for the new pattern along with the correct and erroneous matches from the first rule. So, I have a few questions: why does pattern1 match incorrectly? (i.e. why does the _ custom attribute constraint not apply?) why does the callback function not work …

http://stackoverflow.com/q/52637807
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92208687
downvote count: 1
type: Question
tagged with: opencv
score: 3
has body: In OpenCV (Python), to convert RGB to YCbCr we use: imgYCC = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) What if i want to come back to RGB?
upvote count: 4
has title: Python OpenCV: How to convert YCbCr back to RGB?
answer count: 1
has answer: http://stackoverflow.com/a/52637949
favorite count: 0

http://stackoverflow.com/q/52614470
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52614549
upvote count: 0
has comment: http://stackoverflow.com/comment/92164578
has comment: http://stackoverflow.com/comment/92166408
favorite count: 0
has comment: http://stackoverflow.com/comment/92163319
tagged with: python
has title: Combination of lists in python?
has comment: http://stackoverflow.com/comment/92164654
type: UnansweredQuestion
downvote count: 3
score: -3
has comment: http://stackoverflow.com/comment/92163354
has answer: http://stackoverflow.com/a/52616157
has body: I am writing a python program which has lists: letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z', 'A', 'B', 'C' , 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z' ] digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ] How can I create a list or something so that my selection statement can identify Identifiers = Letter { Letter | Digit } Integers = Digit { Digit } Any help would be appreciated.
has comment: http://stackoverflow.com/comment/92164458
has comment: http://stackoverflow.com/comment/92165448

http://stackoverflow.com/a/52597460
answers question: http://stackoverflow.com/q/52596765
score: 2
downvote count: 0
has body: If ths code is for academic purposes and you don't want to involve third party libraries, the eval() function in Python is built just for this. You can create a function which evaluates a string expression expr for a value x as such: def func(expr, x): return eval(expr) input_expr = input('Enter an expression in x: ') val = 5 print(func(input_expr, val)) Input: x*x*x - x*x + 2 Output: 102 eval() treats the string passed to it as a right hand side expression and evaluates it. So, when the user-input string 'x*x*x - x*x + 2' is passed to the function, the statement return eval('x*x*x - x*x + 2') is equivalent to return x*x*x-x*x+2. Note that this means there must be a variable x in scope, which we handle by wrapping the eval() function in the function eval_expr(). A problem would arise however, if the user input something like y*y*y+y*y-2 as y isn't declared in the scope. If you need to handle such cases, then you would need to write additional code that converts the input string by replacing any alphabetical character in it to x. It should be noted that eval generally isn't considered safe, and if this code is not for academic purposes and needs to be safe, you should consider using python libraries like numexpr or pyparsing. numexpr should be fairly easy to use and would suffice for your application.
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52596765
type: Answer

http://stackoverflow.com/q/52623056
has title: tkinter PIL image is not shown up in class
has answer: http://stackoverflow.com/a/52624717
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/92187155
score: 1
has body: I can't show up the Image in tkinter PIL class. Image is packed or placed successfully but it is not showing up. windowxp wall paper and a man's face are not shown. I made message box when click his face. So if I click the location, message box is showing up. But picture is not showing up. Just location :( I use windows 64bit and Python 3.6 I am Korean. I'm not goot at English.... Please understand me. Please help me This is right display: screenshot from tkinter import * import tkinter as tk from tkinter import messagebox from PIL import Image, ImageTk ##함수 class Mainwindow(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("김상곤이 좋아하는 꿈꾸는 학과 과목 문제 맞추기♡") self.geometry("1600x900") self.resizable(width=FALSE, height=FALSE) wall = tk.PhotoImage(file="gif/bg.gif") labelwall = tk.Label(self, image = wall) labelwall.place(x=0, y=0) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) def func_make(): messagebox.showinfo("제작자", "김재온, 정성윤, 안예진, 이소유, 우연서") def func_exit(): window.quit() window.destroy() mainMenu=Menu(self) fileMenu=Menu(mainMenu) self.config(menu=mainMenu) mainMenu.add_cascade(label="파일", menu=fileMenu) fileMenu.add_command(label="제작자", command=func_make) fileMenu.add_separator() fileMenu.add_command(label="종료", command=func_exit) self.frames={} for F in (MainPage, QuizPage): page_name=F.__name__ frame = F(parent=container, controller=self) self.frames[page_name]=frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame("MainPage") def show_frame(self, page_name): frame = self.frames[page_name] frame.tkraise() def 국어(): page == 1 subject=['국어', '과학', '역사', '사회', '기술'] #색이나 위치 숫자 설정 mint="#99FFFF" subjectsize=30 subjectbutton=60 ##위젯 class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller=controller def clickksk(event): messagebox.showinfo("김…
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92186421
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/92187067
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52705953
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92341381
upvote count: 5
tagged with: pandas
tagged with: python
has title: Python Pandas adds column header as entry instead of actual data after adding new column
has body: I have an unexpected behavior when adding a new row to a pre-allocated DataFrame after I added a new column to this DataFrame. I created the following minimal example (using Python 3.6.5 and Panda 0.23.0): First, I create a pre-allocated DataFrame with 3 columns import pandas as pd df = pd.DataFrame(columns=('A', 'B', 'C'), index=range(5)) # The resulting DataFrame df # A B C #0 NaN NaN NaN #1 NaN NaN NaN #2 NaN NaN NaN #3 NaN NaN NaN #4 NaN NaN NaN Then, I am adding a few rows, which works like expected new_row = {'A':0, 'B':0, 'C':0} df.loc[0] = new_row df.loc[1] = new_row df.loc[2] = new_row # The resulting DataFrame df # A B C #0 0 0 0 #1 0 0 0 #2 0 0 0 #3 NaN NaN NaN #4 NaN NaN NaN Then, I am adding a new column with a default value df['D'] = 0 # The resulting DataFrame df # A B C D #0 0 0 0 0 #1 0 0 0 0 #2 0 0 0 0 #3 NaN NaN NaN 0 #4 NaN NaN NaN 0 And eventually, adding a new row after adding the new column, I get this new_row = {'A':0, 'B':0, 'C':0, 'D':0} df.loc[3] = new_row # The resulting DataFrame df # A B C D #0 0 0 0 0 #1 0 0 0 0 #2 0 0 0 0 #3 A B C D #4 NaN NaN NaN 0 So it seams that, for some reason the DataFrame header is added as the new row instead of the actual values. Am I doing something wrong? I noted that this only happens when I set the size of the table with index=range(5). If I do not set the size of the table adding columns and rows is working like expected. However, I would like to pre-allocate the table due to performance issues.
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52707595
linked to: http://stackoverflow.com/q/38383127
has comment: http://stackoverflow.com/comment/92338384
type: Question
has answer: http://stackoverflow.com/a/52707595
score: 5

http://stackoverflow.com/comment/92347268
type: Comment
type: AnswerComment
has text: Thank you, jlaur! The code works - really odd that the website would take this approach when other stats on their pages come back in a straightforward manner.
comment on: http://stackoverflow.com/a/52678824
score: 0

http://stackoverflow.com/comment/92195135
comment on: http://stackoverflow.com/q/52629035
score: 0
type: Comment
has text: @aj1000 Try running your code line by line and tell us which line produces the error
type: QuestionComment

http://stackoverflow.com/q/52734889
tagged with: hudson-plugins
tagged with: hudson
has answer: http://stackoverflow.com/a/52735098
tagged with: hudson-api
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I Have a python script ready and I need to run using Hudson CI. I can see configure job having the only environment supported is an executable shell. How can I run a python script in the executable shell (Bash shell)? any idea or suggestions?
has title: How to run python script in linux Executable shell
type: Question
has answer: http://stackoverflow.com/a/52734983
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/92394618

http://stackoverflow.com/comment/92299521
type: AnswerComment
comment on: http://stackoverflow.com/a/52685957
score: 0
type: Comment
has text: `super()` takes two things, (a) the current class, and (b) the `self` instance -- it uses the MRO of (b) and the position of (a) on it to find the next class in the MRO. In Python3 these things don't need to be explicitly supplied.

http://stackoverflow.com/a/52641255
has body: Try this as well: import csv myFile = open('testnew2.csv', 'wb+') writer = csv.writer(myFile) reader2 = open('names.csv').readlines() with open('test.csv') as File1: reader1 = csv.reader(File1) for row in reader1: name = "" for record in reader2: record = record.replace("\n","") if record in row: row.append(record) writer.writerow(row) break
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52639573

http://stackoverflow.com/comment/92307225
type: QuestionComment
has text: [Cross-posted to Computer Science](https://cs.stackexchange.com/q/98240/9550) (where, IMO, it's off-topic). Please don't post the same question to multiple Stack Exchange sites. It fragments answers and wastes people's time when they put effort into answering questions that already have answers elsewhere.
comment on: http://stackoverflow.com/q/52684993
score: 2
type: Comment

http://stackoverflow.com/comment/92199994
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52629906
has text: @thedatasleuth absolutely :) happy coding!
type: Comment

http://stackoverflow.com/comment/92553377
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52728368
has text: ```sum([i for i in range(x,y+1) if i%2])```
score: 0

integer
tags question: http://stackoverflow.com/q/52685135
tags question: http://stackoverflow.com/q/52669198
tags question: http://stackoverflow.com/q/52745589
tag name: integer
type: Tag

http://stackoverflow.com/a/52591727
answers question: http://stackoverflow.com/q/52590439
type: AcceptedAnswer
downvote count: 0
has body: This solution solves the exact match task (Code complexity is very high and not recommended): #First create a dummy column of Productdetailed which is sorted df2['dummy'] = df2['Productdetailed'].apply(sorted) #Create Matching column which stores index of first matched list df2['Matching'] = np.nan #Code for finding the exact matches and assigning indices in Matching column for index1,lst1 in enumerate(df2['dummy']): for index2,lst2 in enumerate(df2['dummy']): if index1&lt;index2: if (lst1 == lst2): if np.isnan(df2.loc[index2,'Matching']): df2.loc[index1,'Matching'] = index1 df2.loc[index2,'Matching'] = index1 #Finding the sum of total exact matches print(df2['Matching'].notnull().sum()) 5 #Deleting the dummy column del df2['dummy'] #Final Dataframe print(df2) ID Productdetailed Matching 0 1 [Phone, Watch, Pen] 0.0 1 2 [Pencil, fork, Eraser] 1.0 2 3 [Apple, Mango, Orange] NaN 3 4 [Something, Nothing, Everything] NaN 4 5 [Eraser, fork, Pencil] 1.0 5 6 [Phone, Watch, Pen] 0.0 6 7 [Apple, Mango] NaN 7 8 [Pen, Phone, Watch] 0.0 For both Fully and Partially Match use (If atleast 2 values matches it is partially matched, can also be changed): #First create a dummy column of Productdetailed which is sorted df2['dummy'] = df2['Productdetailed'].apply(sorted) #Create Matching column which stores index of first matched list df2['Matching'] = np.nan #Create Column Stating Status of Matching df2['Status'] = 'No Match' #Code for finding the exact matches and assigning indices in Matching column for index1,lst1 in enumerate(df2['dummy']): for index2,lst2 in enumerate(df2['dummy']): if index1&lt;index2: if (lst1 == lst2): if np.isnan(df2.loc[index2,'Matching']): df2.loc[index1,'Matching'] = index1 df2.loc[index2,'Matching'] = index1 df2.loc[[index1,index2],'Status'] = 'Fully Matched' else: count = sum([1 for v1 in lst1 for v2 in lst2 if v1==v2]) if count&gt;=2: if np.isnan(df2.loc[index2,'Matching']): df2.loc[index1,'Matching'] = index1 df2.loc[index2,'Matching'] = index1 df2.loc[…
type: Answer
accepted answer of: http://stackoverflow.com/q/52590439
has comment: http://stackoverflow.com/comment/92146098
has comment: http://stackoverflow.com/comment/92121191
has comment: http://stackoverflow.com/comment/92146049
upvote count: 1
has comment: http://stackoverflow.com/comment/92121121
score: 1
has comment: http://stackoverflow.com/comment/92146081
has comment: http://stackoverflow.com/comment/92120469
has comment: http://stackoverflow.com/comment/92120030

http://stackoverflow.com/comment/92217468
has text: You are using `closestPoint` on your `y` data. Shouldn't you use it on your `x` data and read the according values using the index found?
comment on: http://stackoverflow.com/q/52636081
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52701354
has comment: http://stackoverflow.com/comment/92329349
has comment: http://stackoverflow.com/comment/92329120
type: Question
tagged with: session-hijacking
has comment: http://stackoverflow.com/comment/92329415
score: 0
tagged with: rest
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: backend
has body: While doing a POST request we've noticed that the user and data were changed. in the dev tools we saw the the session_id that came back from the server was different from the request. What can cause such a behavior? we are using Django 1.6
answer count: 0
has comment: http://stackoverflow.com/comment/92329146
has title: Session Id changes in Django POST response

http://stackoverflow.com/q/52730262
type: UnansweredQuestion
tagged with: tornado
has title: Using tornado, creating an asynchronous function for a blocker function which uses sqlalchemy fetchmany()
tagged with: asynchronous
type: Question
has answer: http://stackoverflow.com/a/52741746
tagged with: python
has comment: http://stackoverflow.com/comment/92425967
has body: I'm currently using tornado to develop an API that will have multiple users. For performance reasons, it would be beneficial for the entire API to be asynchronous. In the current code, I utilize cursor.fetchmany(# of rows) to fetch many lines from a database and write to a specified file (csv,json). I am attempting to make this process asynchronous but am having trouble doing so. The fetch deals with a large amount of data so if multiple people use the API, it will significantly slow it down as people are "waiting" for the fetch of other users to be completed. I have tried using IOLoop with little success Also I tried something like this async def loop(self): I = await val.cursor.fetchmany(100) But there are errors with this because the function fetchmany isn't a native tornado function and isn't structured to support this. Some of my questions are... 1)Has anyone been able to implement a solution to make this async fetching process possible 2) Is this even possible or does the database limit the functionality of tornado asynchronous coding 3) If this is not possible, could I implement something like "ThreadPoolExecutor"to speed up the process by multithreading, or using a substitute for fetchmany? (I don't think this is possible but just trying to outline some of my thought process) Any help would be greatly appreciated.
score: 0
answer count: 1
tagged with: sqlalchemy
linked to: http://stackoverflow.com/q/16491564

http://stackoverflow.com/comment/92342756
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52707701
has text: That doesn't answer the questions...
type: Comment

http://stackoverflow.com/a/52734940
score: 0
has body: try this for i in a[:]: tmp = a[:] a.remove(i) print(a) a = tmp
answers question: http://stackoverflow.com/q/52734503
type: Answer

http://stackoverflow.com/q/52615056
has body: I want to generate a list of floats of size M, where each item in the list is greater than the other proceeding items i.e. Descending order. and the sum of the list must sum to 1. and for the same M magnitude can I generate more than one list that obey to the given constraints. I'm thinking of an equation in the following form: Xi+1 = compute([Xi,Xi-1...X0], M, Random) But I am not able to figure out the extent of this function. Thank you in advance.
downvote count: 3
tagged with: equation
type: Question
upvote count: 4
possible better answer: http://stackoverflow.com/a/52615262
has answer: http://stackoverflow.com/a/52615262
has comment: http://stackoverflow.com/comment/92164600
linked to: http://stackoverflow.com/q/588004
tagged with: series
has title: How to generate list of floats in descending order that sum to 1?
has comment: http://stackoverflow.com/comment/92164430
has comment: http://stackoverflow.com/comment/92164497
answer count: 3
has answer: http://stackoverflow.com/a/52616826
has comment: http://stackoverflow.com/comment/92164442
has answer: http://stackoverflow.com/a/52615139
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92164463
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52615139
score: 1
tagged with: math
has comment: http://stackoverflow.com/comment/92164407

http://stackoverflow.com/a/52594648
answers question: http://stackoverflow.com/q/52594544
has body: try nil_mask = df['value'] == '-' df['value'][nil_mask] = 0 this is only set to zero instances where the whole value is '-', will that work?
score: 0
type: Answer

http://stackoverflow.com/comment/92127065
type: QuestionComment
score: 0
has text: But I don't want to loose apostrophe, single and double inverted commas. So basically ignoring the error wont work.
comment on: http://stackoverflow.com/q/52595809
type: Comment

http://stackoverflow.com/comment/92418679
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52744816
type: QuestionComment
has text: I edited theteh code. have you tried it ? any promising solution?

http://stackoverflow.com/comment/92158740
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52612059
has text: @Ruzihm It explains how to match a word starting with specific letter(s). OP here knows how to replace, hence, it is a valid dupe.

http://stackoverflow.com/q/52657092
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52663023
has body: Private messages or Direct messages can be found with methods such as im.history and converstation.history. How to find thread message? I want to find thread messages and delete them.
has title: I want to find thread message and delete it with slack-api
downvote count: 1
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/52663023
answer count: 1
tagged with: slack-api
favorite count: 0
score: 3
tagged with: python

http://stackoverflow.com/a/52665094
has comment: http://stackoverflow.com/comment/92264265
has body: As the description is a html element just brew it as a soup with BeautifulSoup and extract text from it. desc = BeautifulSoup(item.description.text, 'html.parser') content['description'].append(desc.text[:50]+"..") If you are feeling that as complicated you can use regular expressions to get rid of them. But i would not personally suggest it because your text may contain normal texts with the same pattern. import re desc = re.sub("(&lt;.*?&gt;)", "", str(item.description.text), 0, re.IGNORECASE | re.DOTALL | re.MULTILINE) content['description'].append(desc.text[:50]+"..") The &lt;.*?&gt; will select all the HTML tags and replace them with empty string. Hope this helps! Cheers!
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52664414
answers question: http://stackoverflow.com/q/52664414
type: AcceptedAnswer

http://stackoverflow.com/comment/92406950
has text: I'd say `enumerate` is not ideal here as you don't need to extract index *and* value.
comment on: http://stackoverflow.com/a/52740999
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/92311914
comment on: http://stackoverflow.com/a/52692468
has text: There is a [`Counter.most_common`](https://docs.python.org/2/library/collections.html#collections.Counter.most_common) method.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92243795
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52656307
has text: sorry but i want to loop through each row and set array = [ [0,1,2] , [1,2,3]] and each array is a row in the table

file-writing
tags question: http://stackoverflow.com/q/52681344
type: Tag
tags question: http://stackoverflow.com/q/52652066
tag name: file-writing
tags question: http://stackoverflow.com/q/52637488

http://stackoverflow.com/q/52665338
type: UnansweredQuestion
tagged with: regression
has comment: http://stackoverflow.com/comment/92260494
linked to: http://stackoverflow.com/q/893657
has body: I'm trying to find the goodness of fit for a model I have generated. Premise: I used scipy.optimize.minimize to find the coefficients of the following regression: Y = B * X + e where B and X have between 3 and 5 elements depending on the iteration. I used the minimize package to comply with the following constraints b &gt;= 0 sum(b) = 1 Therefore, now as I know the value of the coefficients, I need to calculate the r-sq to assess which model has the best fit. Is this possible to do in python?
has title: Python: Running a linear regression where the coefficients are known?
downvote count: 0
has comment: http://stackoverflow.com/comment/92261477
tagged with: linear-regression
score: 1
tagged with: scipy
type: Question
upvote count: 1
tagged with: coefficients
has comment: http://stackoverflow.com/comment/92265050
favorite count: 0
tagged with: python
answer count: 0

http://stackoverflow.com/comment/119708453
has text: I have tested this blockparser. All it is is a wrapper of sorts on the blockchain-cli. It cannot return all block hashes. Only block hashes from your wallet
score: 0
type: Comment
comment on: http://stackoverflow.com/a/53226809
type: AnswerComment

http://stackoverflow.com/comment/92405141
has text: Excellent! Can you mark the answer as correct? Someone downvoted it but it is correct.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52720214
type: AnswerComment

http://stackoverflow.com/q/52651427
tagged with: python
has title: Why cant I install mysqlclient==1.3.10
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
score: 2
tagged with: mysql
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52660030
has body: I'm using a new MacOS High Sierra 10.13.5. I first installed python3 using Homebrew: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew install python then I cloned my python project repository from github which has a requirements.txt file which has the line: mysqlclient==1.3.10 I then created a virtual env and ran pip install: python3 -m venv venv pip install -r api/requirements.txt and then I get the following error: ... ... Installing collected packages: six, python-dateutil, aniso8601, appdirs, jmespath, docutils, botocore, s3transfer, boto3, click, Werkzeug, itsdangerous, MarkupSafe, Jinja2, Flask, Flask-Cors, blinker, Flask-Mail, jsonschema, pytz, flask-restplus, Flask-Script, SQLAlchemy, Flask-SQLAlchemy, Flask-SQLAlchemy-Session, Mako, python-editor, alembic, Flask-Migrate, PyJWT, Flask-JWT-Simple, idna, pycparser, cffi, asn1crypto, cryptography, chardet, certifi, urllib3, requests, nexmo, pyparsing, packaging, Pillow, phonenumbers, numpy, timezonefinder, decorator, ratelim, geocoder, SQLAlchemy-Utils, mysqlclient, pycrypto, simple-crypt, suds-jurko, Salesforce-FuelSDK, schedule, python-utils, progressbar2, timeago Running setup.py install for aniso8601 ... done Running setup.py install for itsdangerous ... done Running setup.py install for MarkupSafe ... done Running setup.py install for blinker ... done Running setup.py install for Flask-Mail ... done Running setup.py install for Flask-Script ... done Running setup.py install for SQLAlchemy ... done Running setup.py install for Flask-SQLAlchemy-Session ... done Running setup.py install for Mako ... done Running setup.py install for python-editor ... done Running setup.py install for Flask-JWT-Simple ... done Running setup.py install for pycparser ... done Running setup.py install for geocoder ... done Running setup.py install for SQLAlchemy-Utils ... done Running setup.py install for mysqlclient ... error Complete output from command /Users/mvi/mvi/server/venv/bi…
answer count: 1
tagged with: mysql-python

http://stackoverflow.com/a/52709376
score: 7
type: Answer
upvote count: 7
answers question: http://stackoverflow.com/q/52706049
has body: CliRunner and a proper unit test framework is the way to go. Here is an example setup for PyTest which uses the PyTest Coverage plugin test_click.py from click.testing import CliRunner from click_prog import hello def test_hello_world(): runner = CliRunner() result = runner.invoke(hello, ['--opt', 'An Option', 'An Arg']) assert result.exit_code == 0 assert result.output == 'Opt: An Option Arg: An Arg\n' result = runner.invoke(hello, ['An Arg']) assert result.exit_code == 0 assert result.output == 'Opt: None Arg: An Arg\n' if __name__ == '__main__': test_hello_world() click_prog.py import click import sys @click.command() @click.option('--opt') @click.argument('arg') def hello(arg, opt): """A Simple program""" click.echo('Opt: {} Arg: {}'.format(opt, arg)) if __name__ == '__main__': hello(sys.argv[1:]) pytest.ini [pytest] # -- recommended but optional: # python_files = tests.py test_*.py *_tests.py Test Results: ===================== test session starts ===================== platform darwin -- Python 3.6.5, pytest-3.7.1, py-1.5.4, pluggy-0.7.1 rootdir: /Users/strauch/dev/fix_windows, inifile: pytest.ini plugins: xdist-1.22.5, forked-0.2, cov-2.6.0 collected 1 item test_click.py . [100%] ---------- coverage: platform darwin, python 3.6.5-final-0 ----------- Name Stmts Miss Cover ------------------------------------ click_prog.py 8 1 88% test_click.py 12 1 92% ------------------------------------ TOTAL 20 2 90% ================== 1 passed in 0.07 seconds ===================
downvote count: 0

http://stackoverflow.com/comment/92467868
score: 0
comment on: http://stackoverflow.com/a/52741343
type: AnswerComment
type: Comment
has text: No, its different, that's just an example. In the end the script needs to go through all the files that are in a specific folder and edit them. Each file has a unique name. While the script is running through all files i filter the name and search for that unique part in the files name to remove the correct amount of spaces in the right place. Right now the script is almost done.

http://stackoverflow.com/comment/92345756
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52709618
type: AnswerComment
has text: I get the same error in the post. This snippet also pulls in the what you see in the screenshot.

http://stackoverflow.com/comment/92241456
type: Comment
type: QuestionComment
has text: Hi thank you for pointing that out. Do you think a structure with defer could do the job? For a quick test, I changed the "time.sleep(10)" to "for i in range(100000): pass" to simulate the processing time. But I notice that the "lineReceived" function still doesn't respond to other requests before it finishes the current one.
score: 0
comment on: http://stackoverflow.com/q/52653374

http://stackoverflow.com/comment/92120529
score: 0
type: Comment
type: QuestionComment
has text: Flip your redirection operator around: `>&` (for bash) instead of `&>`. The latter one puts the program in the background, then redirects stdout to the file.
comment on: http://stackoverflow.com/q/52590944

http://stackoverflow.com/a/52686369
type: Answer
accepted answer of: http://stackoverflow.com/q/52686194
score: 2
answers question: http://stackoverflow.com/q/52686194
downvote count: 0
has comment: http://stackoverflow.com/comment/92300319
has comment: http://stackoverflow.com/comment/92307981
has comment: http://stackoverflow.com/comment/92302232
has comment: http://stackoverflow.com/comment/92300371
upvote count: 2
has comment: http://stackoverflow.com/comment/92308123
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92300268
has comment: http://stackoverflow.com/comment/92300347
has body: Clearly, for any price we can buy, we would want to sell it at the highest price. Fortunately, we are given that highest price. So, iterating backwards, we know the highest future price seen at any point we visit in our travel "back in time." Python code: def stockmax(prices): n = len(prices) highest = prices[n - 1] m = [0] * n # Travel back in time, # deciding whether to buy or not for i in xrange(n - 2, -1, -1): # The most profit buying stock at this point # is what we may have made the next day # (which is stored in m[i + 1]) # and what we could make if we bought today m[i] = m[i + 1] + max( # buy highest - prices[i], # don't buy 0 ) # Update the highest "future price" highest = max(highest, prices[i]) return m[0]

http://stackoverflow.com/q/52696414
type: Question
tagged with: pyspark
answer count: 1
tagged with: apache-spark
has answer: http://stackoverflow.com/a/52699896
downvote count: 0
favorite count: 0
has body: I understand whats happening if I define a Python function and use it for a PySpark UDF. However, its not fully clear to me, what PySpark is doing when calling a method of an instantiated object like: class Foo: _const = 1 def f(x): return x +_const foo_object = Foo() f_udf = pyspark.functions.udf(foo_object.f) How is the function brought to the executors? Does the object stay on the manager or is it copied to the executors?
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52699896
has title: What happens exactly if I use a class method as an udf in pyspark?

http://stackoverflow.com/q/52703206
has comment: http://stackoverflow.com/comment/92332825
tagged with: python
has answer: http://stackoverflow.com/a/52703342
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52703379
score: 1
has body: I have this model: class Task(MPTTModel, TimeStampedModel, StartFinishModel): name = models.CharField(max_length=256) start_after_end = models.ManyToManyField('self', related_name='s2e_relation', blank=True) #s2e means that task can't start before related tasks end How can I get all tasks, which can't start before this task ends and all tasks, which have to end before this task can start. Let's say 1 -&gt; 2 -&gt; 3 I have id 2. I want to find 3 and with another query 1. To find 3 I can use Task.objects.get(id = 2).start_after_end.all() How can I find 1? UPDATE 1 Actually find out bigger problem - if I select 2 related to 1 - 1 immidiately changes relation to 1 is related to 2
has comment: http://stackoverflow.com/comment/92332813
tagged with: django
type: Question
has title: Forward and reverse query to ManyToMany relation Django
possible better answer: http://stackoverflow.com/a/52703342
answer count: 2
upvote count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52703379

http://stackoverflow.com/q/52738880
favorite count: 0
tagged with: pycharm
type: UnansweredQuestion
tagged with: python
score: 1
has title: Numpy import error in PyCharm (Importing the multiarray numpy extension module failed)
has answer: http://stackoverflow.com/a/52739175
upvote count: 1
linked to: http://stackoverflow.com/q/52672463
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52739922
duplicate of: http://stackoverflow.com/q/52672463
answer count: 2
downvote count: 0
has body: I've happily used PyCharm professional for a while. Following a fresh reinstall of miniconda and PyCharm, importing numpy in any conda environment leads to the following error: 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: DLL load failed: The specified module could not be found. The python interpreter is set properly (and is printed at the top of the PyCharm console). Importing numpy works just fine outside of PyCharm. Does anyone have any insights as to why this is now happening? Python 3.7 with numpy 1.15.2 and PyCharm professional 2018.2.4 on Windows 10. Thanks!

http://stackoverflow.com/q/52629063
has answer: http://stackoverflow.com/a/52629447
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52630653
has comment: http://stackoverflow.com/comment/92191571
has title: How to calculate average a dictionary from list of dictionary data?
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52629236
score: -1
tagged with: average
upvote count: 2
has comment: http://stackoverflow.com/comment/92191653
favorite count: 0
has body: student_data = [{'id':1, 'Hacker' : 'DOSHI', 'Rank' : 43}, {'id':2, 'Hacker' : 'JOSHI', 'Rank' : 45}, {'id':3, 'Hacker' : 'MOSHI', 'Rank' : 41}, {'id':4, 'Hacker' : 'LOSHI', 'Rank' : 98}, {'id':5, 'Hacker' : 'AOSHI', 'Rank' : 14}] 1. Here I want to calculate average of 'Rank' ? 2. In other word, I want to get the average of (43,45,41,98,14)?
linked to: http://stackoverflow.com/q/1115313
downvote count: 3
has answer: http://stackoverflow.com/a/52629129
has answer: http://stackoverflow.com/a/52629170
answer count: 5

http://stackoverflow.com/comment/92195955
comment on: http://stackoverflow.com/q/52629275
type: Comment
has text: With no indication on the table(s), the fields you want to extract from the CSV files, and where they should go in the table(s), the question is just *unclear*. I may help you with the Python part, but only if you make clear what you want to do...
score: 0
type: QuestionComment

restsharp
tags question: http://stackoverflow.com/q/52692806
tag name: restsharp
type: Tag

http://stackoverflow.com/comment/92359844
score: 0
has text: @HåkenLid I meant as straight line: the line1's and line2's end positions are in closer distance to each other and start positions distance is not.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52716299

http://stackoverflow.com/a/52735507
score: 5
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52734928
type: Answer
has body: If you are using Jupyter Notebook, then tf.Print() so far isn't compatible and would be printing the output to Notebook's server output as is described in the docs In the tensorflow documentation, here is how Tensors are described: When writing a TensorFlow program, the main object you manipulate and pass around is the tf.Tensor. A tf.Tensor object represents a partially defined computation that will eventually produce a value. Hence, you would have to initialize them with a tf.Session() to get their value. To print the value, you eval() Here is the code you want: import tensorflow as tf from keras import backend as K x= K.abs(-2.0) with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) print(x.eval()) The initializer is important to actually initialize x.
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52734928

http://stackoverflow.com/comment/92276124
type: Comment
type: QuestionComment
score: 0
has text: @ClaireNielsen See my example. I want it to be cleaner and more pythonic.
comment on: http://stackoverflow.com/q/52673080

http://stackoverflow.com/a/52748303
score: 6
has body: In case anyone stumbles upon this in run.py, this is the only change I made to get to the desired result. from samo.core import APP as app, DB from flask_wtf.csrf import CSRFProtect from samo.config import config from samo.models import Log import traceback import logging class SQLAlchemyHandler(logging.Handler): def emit(self, record): trace = None exc = record.__dict__['exc_info'] if exc: trace = traceback.format_exc() ##CHANGE HERE, removed exc parameter log = Log( logger=record.__dict__['name'], level=record.__dict__['levelname'], trace=trace, msg=record.__dict__['msg'],) DB.session.add(log) DB.session.commit() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) ch = SQLAlchemyHandler() ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) loggers = [logger, logging.getLogger('werkzeug'), logging.getLogger('sqlalchemy'), logging.getLogger('flask.app')] for l in loggers: l.addHandler(ch) csrf = CSRFProtect() if __name__ == '__main__': csrf.init_app(app) logger.critical('TEST CRITICAL ERROR') app.run(host=config['ENV']['HOST']) Problem solved.
accepted answer of: http://stackoverflow.com/q/52728928
answers question: http://stackoverflow.com/q/52728928
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6

http://stackoverflow.com/a/52667949
downvote count: 0
has comment: http://stackoverflow.com/comment/92265859
has comment: http://stackoverflow.com/comment/92268837
has comment: http://stackoverflow.com/comment/92267355
score: 5
has comment: http://stackoverflow.com/comment/92266946
has comment: http://stackoverflow.com/comment/92265943
answers question: http://stackoverflow.com/q/52667328
upvote count: 5
type: Answer
has body: Here is your original array: x = np.array(['16.37.235.200', '17.37.235.200']) which is displayed like this when printed: print(x) &gt;&gt;&gt; ['16.37.235.200' '17.37.235.200'] In order to display it with comma as a delimiter and without quotes around strings we can use np.array2string: print(np.array2string(x, separator=',', formatter={'str_kind': lambda x: x})) &gt;&gt;&gt; [16.37.235.200,17.37.235.200] I don't like that lambda x: x formatter but couldn't come up with something better to remove the quotes. You can find more here: How to pretty-printing a numpy.array without scientific notation and with given precision?

http://stackoverflow.com/comment/92149433
type: QuestionComment
comment on: http://stackoverflow.com/q/52607350
has text: I'm not sure I understand the question. Do you want the latest transaction for each client, given that the transaction occurred before the given date?
score: 0
type: Comment

http://stackoverflow.com/a/52682095
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52681731
has body: First duplicate values of df1 by length of df2 and then use list comprehesion and chain for Colour as: from itertools import chain df = pd.DataFrame({'Product': df1['Product'].values.tolist()*len(df2), 'Price' : df1['Price'].values.tolist()*len(df2), 'Colour' : list(chain.from_iterable([[v]*len(df1) for v in df2['Colour'].values.tolist()]))}) print(df) Product Price Colour 0 Book 5 Blue 1 Table 10 Blue 2 Chair 7 Blue 3 Book 5 Red 4 Table 10 Red 5 Chair 7 Red 6 Book 5 Green 7 Table 10 Green 8 Chair 7 Green
has comment: http://stackoverflow.com/comment/92336659
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52681731
type: Answer
score: 1

http://stackoverflow.com/comment/92377404
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52725584
has text: @DawidFerenczy How i can check if pyinstaller is available on my machine?I'm not sure about this and macOS 10.13.5 is locked and doesn't permit to install using the pip installer command any dependencies.

http://stackoverflow.com/comment/92310647
score: 2
comment on: http://stackoverflow.com/q/52691809
has text: Did you try running it? What happened?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92146230
has text: It's annoying ; *I almost always find an answer on my own a few moments after having officially searched for help online, even if it has been for days I was stuck!*
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52606077
type: Comment

http://stackoverflow.com/comment/92359346
score: 0
has text: @npe I know how to solve the problem that way, I'm hoping for a way where I don't have to inject anything
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52714549

http://stackoverflow.com/a/52659904
upvote count: 1
answers question: http://stackoverflow.com/q/52652617
has body: Assume that you have installed the extension for python3.6. Then in your run.cmd file, you should add this line of code: D:\home\python364x64\python.exe my_file.py, then put your run.cmd and the my_file.py in the same .zip file. Upload it to webjob and install required libraries as you did before. I have tested on my side, it works.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/52652617

http://stackoverflow.com/a/52624754
type: Answer
score: 2
upvote count: 2
has body: Simple, verbose way: SKIP_PREV = 5 x = [1,2,3,4,5,6,7,5,4,3] prev = -1 s = 0 for num in x: if prev != SKIP_PREV: s += num prev = num print(s) # 30 Compact, maybe less clear way: SKIP_PREV = 5 x = [1,2,3,4,5,6,7,5,4,3] s = sum(num for i, num in enumerate(x) if i == 0 or x[i - 1] != SKIP_PREV) print(s) # 30
downvote count: 0
answers question: http://stackoverflow.com/q/52624673

http://stackoverflow.com/a/52636907
has comment: http://stackoverflow.com/comment/92211187
score: 0
answers question: http://stackoverflow.com/q/52636708
has comment: http://stackoverflow.com/comment/92218597
type: Answer
has comment: http://stackoverflow.com/comment/92241352
has body: According to the documentation it appears that the sessionmaker() initialization automatically 'flushes' sessions, so if you want to reference your session again later in the program you may want to try adding autoflush=False to the argument of sessionmaker() in line 6. That is, try replacing line 6 with: session_maker = sessionmaker(bind=engine,autoflush=False) Hope this helps! I used the documentation on this page, in particular referring to the first code chunk referring to global scope and the listing of arguments. EDIT: This approach did not work. As was noted in the comments, autoflush refers to something else. The same documentation page also shows expire_on_commit=True is auto-set unless otherwise specified, so my new answer is to replace the original code snippet I suggested with: session_maker = sessionmaker(bind=engine,expire_on_commit=False)
has comment: http://stackoverflow.com/comment/92208222
has comment: http://stackoverflow.com/comment/92231130

http://stackoverflow.com/a/52629774
has body: My 2 cents. :-) arr = np.array([[1,2],[3,4]]) np.logical_or(arr==2,arr==3) output: array([[False, True], [ True, False]])
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52629222

http://stackoverflow.com/comment/92287050
type: AnswerComment
comment on: http://stackoverflow.com/a/52679091
type: Comment
has text: @EzraLazuardy what makes you think you need to provide a range to the map function? Doku: https://docs.python.org/3/library/functions.html#map
score: 1

http://stackoverflow.com/comment/92209352
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52637128
has text: I could get your code to work for file uploads (dragging and dropping an image in the chat window, for example.) So for a file named `image.png` i could get an embed with that filename as a link to the image.

http://stackoverflow.com/comment/92280688
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52675628
score: 0
has text: yes temperature is name of column

http://stackoverflow.com/comment/92175050
score: 0
type: Comment
type: QuestionComment
has text: Yes. Exactly. I have some data in that sheet. I want to add to that. But, it is creating a new sheet with the name Attribute Analysis1
comment on: http://stackoverflow.com/q/52620354

http://stackoverflow.com/q/52705218
answer count: 0
tagged with: installation
has body: I just started a new job and I have to set up my geospatial environment in Windows (I was a mac user before). I am having trouble navigating around geopandas bug #830. Based on the comments for the bug, it looks like if I can downgrade pyproj to version 1.9.4 it will fix the issue. BUT, I cannot get 1.9.4 installed for one reason or another. I have tried the following without success: conda install -c conda-forge pyproj==1.9.4 When I try this, it gets hung up in the "Solving Environment" stage. I then tried this: pip install pyproj==1.9.4 but, I get this error: Collecting pyproj-1.9.4 Could not find a version that satisfies the requirement pyproj-1.9.4 (from versions: ) No matching distribution found for pyproj-1.9.4 So, I tried downloading the tar file and doing the following: pip install "C:\Users\myname\Downloads\pyproj-1.9.4.tar" but got this error: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\Users\myname\Downloads\pyproj-1.9.4.tar' I have actually done more than this (it has been a long 8 hours), but I am hoping that somebody smarter than I can put me out of my misery :-) I am using conda version 4.5.11 and python 3.5.6. Thanks in advance for any help.
type: UnansweredQuestion
has title: Geospatial Conda Environment Setup in Python
has comment: http://stackoverflow.com/comment/92354299
tagged with: conda
type: Question
score: 0
tagged with: pyproj
has comment: http://stackoverflow.com/comment/92367668
has comment: http://stackoverflow.com/comment/92373828
tagged with: geopandas
tagged with: python
has comment: http://stackoverflow.com/comment/92367772

http://stackoverflow.com/q/52643188
favorite count: 0
has answer: http://stackoverflow.com/a/52643495
accepted answer: http://stackoverflow.com/a/52643495
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question
score: 1
has title: How to search using SQLAlchemy in a mutable array
has body: I am trying to use a mutable array to store data with SQLAlchemy and Postgres and have written these classes: class MutableList(Mutable, list): def append(self, value): list.append(self, value) self.changed() def pop(self, index=0): value = list.pop(self, index) self.changed() return value @classmethod def coerce(cls, key, value): if not isinstance(value, MutableList): if isinstance(value, list): return MutableList(value) return Mutable.coerce(key, value) else: return value class Lead(db.Model): __tablename__ = 'leads' ... starred = db.Column(MutableList.as_mutable(db.ARRAY(db.Integer))) And I can update the starred property, both appending and popping items from it. The question I have is how to search for row that has a particular item inside the array. Here's my query: leads = Lead.query.order_by(Lead.post_date.desc()).filter(Lead.starred.contains(current_user.id)).all() But that gives me the following error: ARRAY.contains() not implemented for the base ARRAY type; please use the dialect-specific ARRAY type What am I missing here?
tagged with: sqlalchemy
upvote count: 1
answer count: 1
tagged with: flask-sqlalchemy

http://stackoverflow.com/comment/92462124
has text: If you want both versions to match, you can build your own Python distribution from the source code, but beware that C extensions built with that distribution will not be compatible with older ABIs.
type: Comment
comment on: http://stackoverflow.com/q/52728792
type: QuestionComment
score: 1

http://stackoverflow.com/q/52710315
has comment: http://stackoverflow.com/comment/92346988
has comment: http://stackoverflow.com/comment/92346877
type: Question
has answer: http://stackoverflow.com/a/52710402
has title: Is there any more elegant way to reduce this positive/negative logic?
has answer: http://stackoverflow.com/a/52710441
has answer: http://stackoverflow.com/a/52710439
score: 0
possible better answer: http://stackoverflow.com/a/52710441
has answer: http://stackoverflow.com/a/52710545
tagged with: python-3.x
tagged with: logic
answer count: 5
has answer: http://stackoverflow.com/a/52710636
tagged with: python
accepted answer: http://stackoverflow.com/a/52710439
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92346980
has body: Is there any more elegant way to reduce the code below, which should reverse a direction from left to right and vice versa, based on the size of a line? if right_length &gt; left_length: direction = -1 elif right_length &lt; left_length: direction = 1 else: direction = 0

http://stackoverflow.com/comment/92396382
has text: Get a warning from who? The python interpreter? Your python IDE? A tool made specifically to detect this kind of thing?
comment on: http://stackoverflow.com/q/52735770
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52671405
has body: I am trying to fit the data of soccer goal using both Poisson distribution and the Weibull count process model taken from the following paper: http://www.blakemcshane.com/Papers/jbes_weibull.pdf The code in Python is showed below: from math import exp from scipy.special import gamma, gammaln from scipy.misc import factorial import numpy as np from scipy.optimize import minimize # definition of the Weibull count model Acache = dict() def A(n, j,rate,shape): if not (n, j,rate,shape) in Acache: if n == 0: Acache[(n, j,rate,shape)] = exp(gammaln(shape*j+1) - gammaln(j+1)) else: Acache[(n, j,rate,shape)] = sum( A(n-1, m,rate,shape) * exp(gammaln(shape*(j-m)+1) - gammaln(j-m+1)) for m in range(n-1, j) ) return Acache[(n, j,rate,shape)] def Cn(t, n,rate, shape,J=20): return sum( ( (-1)**(j+n) * (rate * t**shape)**j * A(n, j,rate,shape) )/gamma(shape*j+1) for j in range(n, n+J) ) def E(t,rate,shape,J=20, N=20): return sum( (n * Cn(t, n,rate,shape, J)) for n in range(0, N) ) #finish Weibul count model #definition of the poisson distribution def poisson(k, lamb): """poisson pdf, parameter lamb is the fit parameter""" return (lamb**k/factorial(k)) * np.exp(-lamb) def negLogLikelihood(params1,data): """ the negative log-Likelohood-Function""" lnl = - np.sum(np.log(poisson(data,params1[0]))) return lnl def negLogLikelihoodweibull(params,data): """ the negative log-Likelohood-Function of weibull count model""" #Is it correct for i in range(len(data)): lnl = - np.sum((np.log(Cn(1,data[i],params[0],params[1])))) return lnl # get poisson deviated random numbers data = np.random.poisson(1.5, 100) print(data) #print for debug print(negLogLikelihood([1.5],data)) print(Cn(1,3,1.1,1,20)) print(len(data)) print(negLogLikelihoodweibull([1.5,1],data)) # minimize the negative log-Likelihood result = minimize(negLogLikelihood, # function to minimize x0=np.ones(1), # start value args=(data,), # additional arguments for function method='Powell', # minimization method, see docs ) print(result) #…
tagged with: python
has comment: http://stackoverflow.com/comment/92368418
answer count: 0
type: UnansweredQuestion
tagged with: count
tagged with: data-fitting
has comment: http://stackoverflow.com/comment/92360700
has comment: http://stackoverflow.com/comment/92292175
tagged with: weibull
type: Question
has title: Fitting a Count Models Based on Weibull Interarrival Times in Python?
tagged with: model-fitting
score: 0

http://stackoverflow.com/q/52677558
answer count: 1
tagged with: python-2.x
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92284466
has title: pip is showing error after downloading OPENSSL
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52677807
has body: pip command is showing error. i downloaded libraries from https://github.com/rajpaul/igotoeurope/blob/master/requirements.txt then it started showing error in pip. i tried uninstalling the pip command and reinstalling the same still it didn't work. Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/_vendor/init.py", line 33, in vendored import(vendored_name, globals(), locals(), level=0) ModuleNotFoundError: No module named 'pip._vendor.cachecontrol' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/pip3", line 9, in &lt;module&gt; from pip import main File "/usr/lib/python3/dist-packages/pip/__init__.py", line 22, in &lt;module&gt; from pip._vendor.requests.packages.urllib3.exceptions import DependencyWarning File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 64, in &lt;module&gt; vendored("cachecontrol") File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored __import__(modulename, globals(), locals(), level=0) File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 656, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 626, in _load_backward_compatible File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/__init__.py", line 9, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 656, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 626, in _load_backward_compatible File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/wrapper.py", line 1, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_loa…
type: AnsweredQuestion
tagged with: ubuntu-18.04
accepted answer: http://stackoverflow.com/a/52677807
type: Question
downvote count: 0
tagged with: ubuntu
tagged with: openssl

http://stackoverflow.com/comment/92196977
type: QuestionComment
comment on: http://stackoverflow.com/q/52630256
has text: This gives me following error: ValueError: columns overlap but no suffix specified: Index(['EURCAD'], dtype='object') in one file. Rest of them works great
type: Comment
score: 0

http://stackoverflow.com/q/52729806
type: Question
score: 0
upvote count: 1
answer count: 1
favorite count: 0
tagged with: tuples
has answer: http://stackoverflow.com/a/52729823
accepted answer: http://stackoverflow.com/a/52729823
tagged with: python
has title: how to check if the first or the second element of a tuple matches a given value in python?
has comment: http://stackoverflow.com/comment/92384736
duplicate of: http://stackoverflow.com/q/49666523
has body: I want to find if the first element or the second element matches 3, if so I want to append the tuple to mytuple_with_3. mytuple=[(1,3),(4,9),(3,8)] mytuple_with_3 = [] c = 0 for x in mytuple: if x[0][c] == 3 or x[c][1] == 3: mytuple_with_3.append(x) c += 1 result show show (1,3) and (3,8)
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49666523
downvote count: 1

http://stackoverflow.com/q/52623178
upvote count: 2
tagged with: multithreading
has comment: http://stackoverflow.com/comment/92194114
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/92196056
type: Question
has comment: http://stackoverflow.com/comment/92195564
tagged with: threadpool
accepted answer: http://stackoverflow.com/a/52635055
has comment: http://stackoverflow.com/comment/92194778
has comment: http://stackoverflow.com/comment/92201281
has comment: http://stackoverflow.com/comment/92201821
has comment: http://stackoverflow.com/comment/92201972
has comment: http://stackoverflow.com/comment/92188646
has body: I've written a script in python using multiprocessing.pool.ThreadPool to handle multiple requests concurrently and do the scraping process robust. The parser is doing it's job perfectly. As I have noticed in several scripts that there should be a delay within the scraping process when it is created using multiprocessing, I would like to put a delay within my below script as well. However, This is where I'm stuck and can't find out the right position to put that delay. This is my script so far: import requests from urllib.parse import urljoin from bs4 import BeautifulSoup from multiprocessing.pool import ThreadPool url = "http://srar.com/roster/index.php?agent_search=a" def get_links(link): completelinks = [] res = requests.get(link) soup = BeautifulSoup(res.text,'lxml') for items in soup.select("table.border tr"): if not items.select("td a[href^='index.php?agent']"):continue data = [urljoin(link,item.get("href")) for item in items.select("td a[href^='index.php?agent']")] completelinks.extend(data) return completelinks def get_info(nlink): req = requests.get(nlink) sauce = BeautifulSoup(req.text,"lxml") for tr in sauce.select("table[style$='1px;'] tr")[1:]: table = [td.get_text(strip=True) for td in tr.select("td")] print(table) if __name__ == '__main__': ThreadPool(20).map(get_info, get_links(url)) Once again: all i need to know is the right position within my script to put a delay.
has comment: http://stackoverflow.com/comment/92196334
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/92195743
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92202271
has comment: http://stackoverflow.com/comment/92195199
has title: How to delay execution within ThreadPool?
tagged with: python
has answer: http://stackoverflow.com/a/52635055
score: 2
type: AnsweredQuestion

image-scanner
tag name: image-scanner
type: Tag
tags question: http://stackoverflow.com/q/52719371

http://stackoverflow.com/comment/92158515
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52612059
has text: Use `re.sub(r"\bdiag\w*", "diagnose", text)`
score: 0

http://stackoverflow.com/comment/92170948
type: QuestionComment
has text: Your regex matches the entire string if it matches at all. Get rid of the `.*`s at both ends.
type: Comment
comment on: http://stackoverflow.com/q/52618381
score: 0

http://stackoverflow.com/comment/92193777
type: QuestionComment
comment on: http://stackoverflow.com/q/52630059
has text: @mad_ Right, I see the data is different. He's looking to make a set of dicts,
score: 0
type: Comment

http://stackoverflow.com/q/52638519
has answer: http://stackoverflow.com/a/55947196
has title: How to ensure python code is terminated with vbscript when I am uploading vbscript to secure crt using pyautogui module?
tagged with: pyautogui
type: Question
has body: I am trying to create an RPA based automation for running a vbscript in Secure CRT. In that, I am uploading vbscript to Secure CRT using pyautogui module. Now, my code ends even before all the logs download from vbscript is completed. How can I ensure that my python ends only after vbscript has run successfully and all the download is completed so that I can close secure CRT?
tagged with: secure-crt
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52641139
type: Answer
score: 0
has body: Please refer the below codes.This is exactly what I was looking for a unified credit debit balance statement.Whenever there is inflow of money, the debit is forced to be zero and whenever there is an expenditure,the credit is forced to be zero.Both credit and debit remain zero only in the first line of the output which is carry forward from the previous month.This is similar to the concept whenever there is an input,the output is disabled and whenever there is output, the input is disabled.Please run Cash_001.py file. #Classdef_Cash_001.py class Cash: def __init__(self, DATE, VOUCHER, SPECIFICATION, INITIAL_AMOUNT, CREDIT,DEBIT, REMARKS, BALANCE): self.DATE = DATE self.VOUCHER = VOUCHER self.SPECIFICATION = SPECIFICATION self.CREDIT = CREDIT self.DEBIT = DEBIT self.REMARKS = REMARKS self.BALANCE = INITIAL_AMOUNT def Spending(self,DATE,VOUCHER,SPECIFICATION,DEBIT,CREDIT,REMARKS): self.DATE = DATE self.VOUCHER = VOUCHER self.SPECIFICATION = SPECIFICATION self.REMARKS = REMARKS self.DEBIT = DEBIT self.CREDIT = 0 self.BALANCE -= DEBIT def CashInflow(self,DATE,VOUCHER,SPECIFICATION,CREDIT,DEBIT,REMARKS): self.DATE = DATE self.VOUCHER = VOUCHER self.SPECIFICATION = SPECIFICATION self.REMARKS = REMARKS self.CREDIT = CREDIT self.DEBIT = 0 self.BALANCE += CREDIT def dump(self): s = 'DATE: %s, VOUCHER: %s, SPECIFICATION: %s , CREDIT: %s ,DEBIT: %s ,REMARKS :%s ,BALANCE :%s ' % \ (self.DATE,self.VOUCHER, self.SPECIFICATION, self.CREDIT, self.DEBIT, self.REMARKS, self.BALANCE) print s #Cash_001.py from Classdef_Cash_001 import Cash p1=Cash('01/10/2018','000','CARRY FORWARD',2000,0,0,'REMAINDER',0) p1.dump() p1.Spending('01/10/2018','001','OIL',200,0,'JOHN') p1.dump() p1.CashInflow('02/10/2018','002','SALES',1000,0,'REF179800') p1.dump() p1.Spending('03/10/2018','003','GAS',200,0,'GEORGE') p1.dump() p1.CashInflow('03/10/2018','004','SALES',5000,0,'REF179801') p1.dump()
answers question: http://stackoverflow.com/q/52623935

http://stackoverflow.com/comment/92208537
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52637763
has text: yes, this is for learning purposes and I am currently taking a data structures course. the restaurant data was presented in an a 2-D array. if i had the choice, I personally wouldn't represent my data inside arrays, but rather in objects. thanks for any help!
score: 0

http://stackoverflow.com/comment/92348325
type: Comment
has text: @HBat: my own experience is that typically *one* query is not that problematic, it is more the *N+1* problem that is problematic, but with proper `.select_related(..)` and `.prefetch_related(..)` the amount of time for JOINing is normally quite limited.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52710771

http://stackoverflow.com/comment/92488757
score: 0
type: QuestionComment
type: Comment
has text: @jdamp, yes I added a sample code in the post above. I modified it a bit, I just want to get the value of a between 0 and 6 that will give the minimum value of the randomForest_b function given the parameters.
comment on: http://stackoverflow.com/q/52742336

http://stackoverflow.com/q/52744766
upvote count: 4
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52745405
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I have the following code: from bokeh.plotting import curdoc from bokeh.layouts import widgetbox from bokeh.layouts import column as bokehCol from bokeh.models.layouts import Column from bokeh.models.widgets import DatePicker from datetime import date from datetime import timedelta as td from datetime import datetime as dt from bokeh.io import output_notebook from bokeh.plotting import show output_notebook() crnt_date=dt.now() dt_pckr_strt=DatePicker(title='Select start of sync date',min_date=date(2017,1,1),max_date=date.today()) def callback(attr,old,new): print(type(old)) print('old was {} and new is {}'.format(old,new)) dt_pckr_strt.on_change('value',callback) curdoc().add_root(bokehCol(dt_pckr_strt)) show(widgetbox(dt_pckr_strt, width=300)) The output is showing weird instead of conventional datepicker. I believe it's in show function I am doing some mistake. Where am I going wrong?
has title: How to show datepicker widget?
tagged with: bokeh
type: Question
has answer: http://stackoverflow.com/a/54556985
score: 4

http://stackoverflow.com/a/52631233
has comment: http://stackoverflow.com/comment/92196288
has body: You can use the following generator expression: next(i for i, a in enumerate(ListA) for b in ListB if a == b) Given your sample input, this returns: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52631029
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92195727
has comment: http://stackoverflow.com/comment/92195706
type: Answer

http://stackoverflow.com/comment/92229321
comment on: http://stackoverflow.com/q/52648720
score: 0
type: Comment
has text: How do you want to magically run the functionality of the reset method without calling it?
type: QuestionComment

http://stackoverflow.com/comment/92124774
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52595012
has text: Can you use third-party packages? Python's `lxml` maintains a *pretty_print* handler.

http://stackoverflow.com/comment/92138603
type: AnswerComment
comment on: http://stackoverflow.com/a/52601914
type: Comment
has text: @David542 It supports almost every common types. https://pandas.pydata.org/pandas-docs/stable/api.html#input-output
score: 0

http://stackoverflow.com/comment/92340651
type: QuestionComment
comment on: http://stackoverflow.com/q/52693742
has text: Sure, I'll write code for you a bit later
score: 0
type: Comment

http://stackoverflow.com/comment/92363974
type: Comment
comment on: http://stackoverflow.com/a/52719350
has text: Can I select the attributes that I want to create a list with? For example, if I have atr1, atr2 and atr3, create a list with atr1 and atr2?
type: AnswerComment
score: 0

http://stackoverflow.com/a/52625821
has comment: http://stackoverflow.com/comment/92184969
answers question: http://stackoverflow.com/q/52625673
has body: Do you need to reproduce the exact order? You could use something like this to traverse the data structure: def recurse(data, level): if type(data) is dict: if "name" in data: print("-" * level + data["name"]) for (key, value) in data.items(): recurse(value, level + 1) recurse(partners, 1)
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52625673
upvote count: 5

jpype
tag name: jpype
tags question: http://stackoverflow.com/q/52644215
type: Tag

http://stackoverflow.com/comment/92206988
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52636881
type: Comment
has text: Thank you! Indeed, I'm looking for such a parser for a superset of JSON.

http://stackoverflow.com/q/52710975
favorite count: 0
has body: I want to do the following: out = sess.run(operation, feed_dict={x: x_value, , y: y_value}) Somewhere in the model definition, I have used this: x = tf.placeholder(tf.float32, shape=(None, None, 3)) y = tf.placeholder(tf.float32, shape=(None, None, 3)) operation = some_function(x, y) where x and y are images. How do I rewrite my code so that I can evaluate multiple ys with a single x. I want to do something like this: x = tf.placeholder(tf.float32, shape=(None, None, 3)) y = [] x = [] for _y in y: operation = some_function(x, _y) z.append(operation) Right now I just do this: x = tf.placeholder(tf.float32, shape=(None, None, 3)) y = tf.placeholder(tf.float32, shape=(None, None, None, 3)) #add extra dimension z = tf.unstack(tf.map_fn(some_function, y)) But the problem is when I do that, tf.unpack throws an error says its not aware of the size of y and fails. This is solved by doing this, where I initialize y's 0 index with the total number of images. x = tf.placeholder(tf.float32, shape=(None, None, 3)) y = tf.placeholder(tf.float32, shape=(2, None, None, 3)) #add extra dimension z = tf.unstack(tf.map_fn(some_function, y)) and I eval the values using: y_values = np.stack([y_value1, y_value2]) out = sess.run(operation, feed_dict={x: x_value, , y: y_values }) Ideally I want this to be variable and me not having to initialize the value of the placeholder. Lets say I want it to do a weighted sum of all the different y values. Each time just 1y or 5ys, etc.
has comment: http://stackoverflow.com/comment/92364790
answer count: 0
has comment: http://stackoverflow.com/comment/92364969
type: UnansweredQuestion
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/92367164
has comment: http://stackoverflow.com/comment/92360636
score: 2
downvote count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/92365131
has title: How do I accept a list of tensors in a placeholder in tensorflow?
tagged with: python

http://stackoverflow.com/q/52614241
linked to: http://stackoverflow.com/q/22444
has body: As of my understanding \2 represents the contents of group 2. So, the expression r'(\w*)(\w)\2' should return the contents of group2( i.e \w) but when we use the word having repeated characters it is returning repeated characters. example: re.search(r'(\w*)(\w)\2','finally').group(2) -&gt; 'l' re.search(r'(\w*)(\w)\2','finallyy').group(2) -&gt;'y' In the 1st example the output is 'l' instead of 'y'. Can anyone tell me what exactly \2 mean in regular expression and where does my understanding is wrong.
has comment: http://stackoverflow.com/comment/92162903
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/22937618
has answer: http://stackoverflow.com/a/52614380
accepted answer: http://stackoverflow.com/a/52614380
has comment: http://stackoverflow.com/comment/92163147
tagged with: python
duplicate of: http://stackoverflow.com/q/22444
tagged with: regex
duplicate of: http://stackoverflow.com/q/21880127
type: AnsweredQuestion
score: 2
has title: \2 mean in regular expression
upvote count: 3
downvote count: 1
type: Question

http://stackoverflow.com/q/52712687
has body: System：win server 2008 python：3.5.3
tagged with: python
has answer: http://stackoverflow.com/a/52712770
has comment: http://stackoverflow.com/comment/92351148
tagged with: sha256
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/92351524
score: -5
downvote count: 5
upvote count: 0
has title: Why does python install sha256 always fail?
answer count: 1
has comment: http://stackoverflow.com/comment/92351193
favorite count: 0
has comment: http://stackoverflow.com/comment/92351605

http://stackoverflow.com/a/52702498
has body: If your columns are ordered and you want lettered columns, don't type names out manually. This is prone to error. You can use string.ascii_lowercase, assuming you have a maximum of 26 columns: from string import ascii_lowercase df = pd.DataFrame(columns=['a', 'b', 'b1']) df.columns = list(ascii_lowercase[:len(df.columns)]) print(df.columns) Index(['a', 'b', 'c'], dtype='object')
score: 0
answers question: http://stackoverflow.com/q/52702247
type: Answer

http://stackoverflow.com/q/52703476
has comment: http://stackoverflow.com/comment/92333592
has answer: http://stackoverflow.com/a/52703746
has comment: http://stackoverflow.com/comment/92333531
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52703721
has answer: http://stackoverflow.com/a/52703762
answer count: 3
has body: So i might have a tag such as: bla bla bla I want to be able to select by the margin-right:5pt Any tag that has this style I would like to extract please. At the moment I have this code but it isn't extracting anything: p_tag = name.find_all('p', {'style':'margin-right:5.5pt'}) print(p_tag) Here is more of the html code that I have: Some header tag Some namesome place they work short description about the person some more info... Can I merge all the p tags with the specific margin until the tag appears again?
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/html
has title: How to select a html tag by its style? With Beautifulsoup and Python
tagged with: python

http://stackoverflow.com/comment/92331977
has text: Waited 10 minutes..Any way to make pip show more information, so that I can see that it is still doing something?
comment on: http://stackoverflow.com/q/52702676
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92126766
type: Comment
comment on: http://stackoverflow.com/a/52591963
type: AnswerComment
has text: @Martin Evans can you help ? i am still looking
score: 0

http://stackoverflow.com/q/52622302
type: Question
accepted answer: http://stackoverflow.com/a/52622383
answer count: 1
tagged with: postgresql
has title: Why am I getting a null constraint error?
tagged with: django
tagged with: python
has body: I'm Trying to add comments to Facts(posts). When I try to submit a comment I get the following error? I'm using Postgres FYI IntegrityError at /fc/2/comment/ null value in column "comment_id" violates not-null constraint DETAIL: Failing row contains (8, It has plugins too, 2018-10-03 07:41:25.249524+00, 1, null). Exception Value: null value in column "comment_id" violates not-null constraint DETAIL: Failing row contains (8, It has plugins too, 2018-10-03 07:41:25.249524+00, 1, null). Model: class Fact(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Comment(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) comment = models.ForeignKey('fc.Fact', on_delete=models.CASCADE, related_name='comments') text = models.TextField() created_date = models.DateTimeField(default=timezone.now) View: def add_comment_to_post(request,pk): fc = get_object_or_404(Fact, pk=pk) if request.method =="POST": form =CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.fc = fc comment.save() return redirect('fc_detail',pk=fc.pk) else: form =CommentForm() return render(request,'add_comment_to_post.html',{'form':form}) Form view: {% extends 'base.html' %} {% block content %} Check this fact {% csrf_token %} {{ form.as_p }} Save {% endblock %} Form: class FcForm(forms.ModelForm): class Meta: model = Fact fields = ('title', 'text',) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) Why is the comment_id null, I would have thought Django auto-populates this as it did with my Fact model. Appreciate help on this. Thank you.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52622383
score: 0

http://stackoverflow.com/a/52646925
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52646581
has body: You can try of OR "|" Operation in regex with multiple conditions re.findall('\d{2,} \d{2,}/\d{3,} | \d{2,}/\d{3,} | \d{2,}/\d{1,} \d{1,}',a) outL [' 50325/654 ', '56 968/325 ', '259 65/456 ', ' 54654/65 4']
has comment: http://stackoverflow.com/comment/92226868
has comment: http://stackoverflow.com/comment/92227076
has comment: http://stackoverflow.com/comment/92225839

http://stackoverflow.com/q/52618700
has answer: http://stackoverflow.com/a/52618746
has title: How to sort MNIST digits into each class label?
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I'm importing mnist dataset from Keras using (x_train, y_train), (x_test, y_test) = mnist.load_data() and what I want to do is sort each sample by it's corresponding digit. I'm imagining some trivial way to do this but I can't seem to find any label attribute of the data. Any simple way to do this?
type: Question
score: 3
tagged with: mnist
accepted answer: http://stackoverflow.com/a/52618746
upvote count: 3
answer count: 1
tagged with: keras
favorite count: 0

http://stackoverflow.com/q/52695234
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52695246
score: 0
tagged with: pandas
answer count: 1
has title: Find the columns with True value
has body: I have a DataFrame with columns that there is only a True in a row (like the df below). How may I form a column with the column index that has True for that row? In real life the matrix is big, so I avoid using for loop and apply. df = pd.DataFrame([[True,False,False], [True,False,False], [False,True,False], [False,False,True], [True,False,False], ]) The answer shall be sth like: df['TrueColIndex'] = [0,0,1,2,1] Thanks!
tagged with: python
has answer: http://stackoverflow.com/a/52695246

http://stackoverflow.com/q/52675556
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
score: 3
tagged with: pypdf
tagged with: http://stackoverflow.com/tag/json
has body: I am using PyPDF2 to extract the data from PDF file and then converting into Text format? PDF format for the file is like this: Name : John Address: 123street , USA Phone No: 123456 Gender: Male Name : Jim Address: 456street , USA Phone No: 456899 Gender: Male In Python I am using this code: import PyPDF2 pdf_file = open('C:\\Users\\Desktop\\Sampletest.pdf', 'rb') read_pdf = PyPDF2.PdfFileReader(pdf_file) number_of_pages = read_pdf.getNumPages() page = read_pdf.getPage(0) page_content = page.extractText() page_content This is the outcome which I get from page_content: 'Name : John \n \nAddress: 123street , USA \n \nPhone No: 123456\n \nGender: Male \n \n \nName : Jim \n \nAddress: 456street , USA \n \nPhone No: 456899\n \nGender: Male \n \n \n' How do I format it in a JSON or XML format so that I could use extracted data in SQL server database. I tried using this approach as well import json data = json.dumps(page_content) formatj = json.loads(data) print (formatj) Output: Name : John Address: 123street , USA Phone No: 123456 Gender: Male Name : Jim Address: 456street , USA Phone No: 456899 Gender: Male This is the same output which I have in my word file, but I don't think that this is in JSON format.
has answer: http://stackoverflow.com/a/52676433
type: Question
has comment: http://stackoverflow.com/comment/92280508
has title: How to convert the extracted text from PDF to JSON or XML format in Python?
has comment: http://stackoverflow.com/comment/92280493

http://stackoverflow.com/q/52731429
score: 0
has comment: http://stackoverflow.com/comment/92387998
answer count: 1
has comment: http://stackoverflow.com/comment/92387967
has body: Hi i have been trying to get the mean of each sub-list using sum/length. vectors = [[2.731018, 1.7550012, 2.3455532], [2.9210236, 3.2172325], [2.9255183, 2.66712, 2.7174947]] mean_vec = [sum(i)/len(i) for i in vectors] Currently i am using the code above, however i am being prompted with this error message: ZeroDivisionError: division by zero The list above is just a sample. i have a much larger list of numbers. please advice me on how i should solve this
has title: Python - How to divide numbers in list of lists?
tagged with: division
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52731513
accepted answer: http://stackoverflow.com/a/52731513
type: Question
has comment: http://stackoverflow.com/comment/92388082
tagged with: arraylist

http://stackoverflow.com/q/52737772
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/92401519
tagged with: python
has title: 403 Missing or insufficient permissions
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92401671
type: Question
has body: I am running datastore emulator. When I run "dev_appserver.py app.yaml" command, I get this error 403 Missing or insufficient permissions. This is the warning I get. I know there is a problem with authentication. I have gone through this. But couldn't end up finding a solution. Some details: I am using MySQL databases for some apps. For others I want to use datastore. I am running datastore emulator on one tab, Google cloud proxy on another, dev_appserver on the third one. I have set the environment variables using the command gcloud beta emulators datastore env-init. My settings.py if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/&lt;your-cloudsql-connection string&gt; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/connectionname', 'NAME': 'db_name', 'USER': 'username', 'PASSWORD': 'password', } } else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: # # $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306 # # See https://cloud.google.com/sql/docs/mysql-connect-proxy DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3307', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'password', } } # [END db_setup] My app.yaml runtime: python37 handlers: - url: /static static_dir: static/ - url: /.* script: auto Technology background: Django 2.1 Python 3.5.2 Stack trace: Traceback (most recent call last): File "/tmp/tmpIZrOSY/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/tmp/tmpIZrOSY/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/tmp/tmpIZrOSY/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_re…
linked to: http://stackoverflow.com/q/39978077
tagged with: google-cloud-datastore
downvote count: 0
has answer: http://stackoverflow.com/a/53074974
has comment: http://stackoverflow.com/comment/92401327
has comment: http://stackoverflow.com/comment/92401488
tagged with: google-cloud-platform
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92195744
has text: What's the issue? Where are you running into trouble?
comment on: http://stackoverflow.com/q/52631022
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52690293
type: UnansweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52729393
has answer: http://stackoverflow.com/a/53964885
tagged with: tensorflow
type: Question
upvote count: 2
answer count: 2
tagged with: debian-stretch
tagged with: python-3.6
has title: Tensorflow: AttributeError: 'NoneType' object has no attribute 'original_name_scope'
tagged with: python
favorite count: 0
tagged with: jupyter-notebook
has body: I am trying to run some python tensorflow code on a debian 9.5 stretch system on google cloud. I am Using tensorflow GPU version of this (the latest version) with the approriate CODA and cuDNN software installed. Here is my code: import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train = tf.keras.utils.normalize(x_train, axis=1) # scales all values between 0 and 1 on pixel image x_test = tf.keras.utils.normalize(x_test, axis=1) model = tf.keras.models.Sequential() model.add (tf.keras.layers.Flatten()) # flattens the 28x28 pixels into long flat vector model.add(tf.layers.Dense(128, activation=tf.nn.relu))# builds hidden layer 128 neurons (we can tweak) and activation func - use this as default, sigmoid function model.add(tf.layers.Dense(128, activation=tf.nn.relu)) # second layer model.add(tf.layers.Dense(10, activation=tf.nn.softmax)) # output layer - number of output neurons =classes model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics = ['accuracy']) # adam is least squares test model.fit(x_train, y_train, epochs=3) #model.fit(x_train, y_train, epochs=3) However, I get the following error: AttributeError Traceback (most recent call last) &lt; ipython-input-1-3604b3cbf07d&gt; in &lt;module&gt; 16 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics = ['accuracy']) # adam is least squares test 17 ---&gt; 18 model.fit(x_train, y_train, epochs=3) 19 #model.fit(x_train, y_train, epochs=3) 20 ~/Python-3.6.4/py_36_env/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 1507 steps_name='steps_per_epoch', 1508 steps=steps_per_epoch, -&gt; 1509 validation_split=validation_split) 1510 1511 # Prepare validation data. ~/Python-3.6.4/py_36_env/lib/python3.…

http://stackoverflow.com/a/52727420
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52723482
answers question: http://stackoverflow.com/q/52723482
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: You are trying to represent an unknown function by two arrays inside of a list. It must be a one-dimensional array. So, instead of 3 X-variables and 9 Y-variables it must be a flat list of 12 variables. Like this: def dZdt(Z, t): X = Z[:3] Y = Z[3:].reshape(3, 3) F = 4 d_x = np.zeros(3) d_y = np.zeros((3, 3)) # Compute the Y values for k in range(3): for j in range(3): d_y[k, j] = X[k] - Y[k, j] # X values d_x[k] = Y[k].mean() + F d = np.concatenate((d_x.ravel(), d_y.ravel())) return d # Initial conditions X0 = np.random.uniform(size=3) Y0 = np.random.uniform(size=(3, 3)) Z0 = np.concatenate((X0.ravel(), Y0.ravel())) t = range(20) Z = odeint(dZdt, Z0, t) NumPy arrays are indexed as Y[k, j], not Y[k][j]. And there are ample vectorization opportunities that would eliminate the loops in the computation of dZdt. Like this: def dZdt(Z, t): X = Z[:3] Y = Z[3:].reshape(3, 3) F = 4 d_y = X[:, None] - Y d_x = Y.mean(axis=1) + F d = np.concatenate((d_x.ravel(), d_y.ravel())) return d

http://stackoverflow.com/comment/92365502
has text: Could not reproduce - works fine for me.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52719986
score: 1

http://stackoverflow.com/a/52743675
answers question: http://stackoverflow.com/q/52743119
type: Answer
has comment: http://stackoverflow.com/comment/92412011
upvote count: 7
has body: I'm not sure there's such a function, but you could always create one, for example: import matplotlib as mpl import matplotlib.pyplot as plt def add_interval(ax, xdata, ydata, caps=" "): line = ax.add_line(mpl.lines.Line2D(xdata, ydata)) anno_args = { 'ha': 'center', 'va': 'center', 'size': 24, 'color': line.get_color() } a0 = ax.annotate(caps[0], xy=(xdata[0], ydata[0]), **anno_args) a1 = ax.annotate(caps[1], xy=(xdata[1], ydata[1]), **anno_args) return (line,(a0,a1)) fig, ax = plt.subplots() add_interval(ax, (3,7), (3,3), "()") add_interval(ax, (2,6), (2,2), "[]") add_interval(ax, (1,5), (1,1), "(]") plt.xlim((0,8)) plt.ylim((0,4)) plt.show() Produces:
score: 7
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52743119

http://stackoverflow.com/q/52609750
tagged with: node.js
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: socket.io
type: Question
has title: SocketIO emit from Node server to Python client
has answer: http://stackoverflow.com/a/52610311
tagged with: python-2.7
has body: I'm looking for a way to emit an instruction from my NodeJS server to my client Python. My server receive the 'instruction' from a Web Interface, and the connection works. But I am not able to emit this instruction to my client which is in Python. Main idea : - NodeJS socket.on('instruction', function (jsonMessage){ ... socket.emit('deleteFile', jsonMessage); }; - Python from socketIO_client_nexus import SocketIO import json ... def on_deleteF(*args): #I just try to print something first print('test delete') ... mainSocket = SocketIO('0.0.0.0', 3000) mainSocket.on('deleteFile', on_deleteF) I don't know if I made a mistake in my way of thinking socket.emit('deleteFile'), or on the '.on' in Python, or on both. So if you can explain me the good way to do, the good way to think. Thanks
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52610311
tagged with: python

http://stackoverflow.com/comment/92169929
comment on: http://stackoverflow.com/q/52604824
score: 0
type: QuestionComment
type: Comment
has text: It is possible your subscription does not allow creating python functions. Please open an issue here: https://github.com/Azure/azure-functions-python-worker/issues

http://stackoverflow.com/q/52746279
tagged with: random-seed
upvote count: 10
has title: How to get absolutely reproducible results with Scikit Learn?
type: Question
has body: Regarding the seeding system when running machine learning algorithms with Scikit-Learn, there are three different things usually mentioned: random.seed np.random.seed random_state at SkLearn (cross-validation iterators, ML algorithms etc) I have already in my mind this FAQ of SkLearn about how to fix the global seeding system and articles which point out that this should not be simply a FAQ. My ultimate question is how can I get absolutely reproducible results when running an ML algorithm with SkLearn? In more detail, If I only use np.random.seed and do not specify any random_state at SkLearn then will my results be absolutely reproducible? and one question at least for the sake of knowledge: How exactly np.random.seed and random_stateof SkLearn are internally related? How np.random.seed affects the seeding system (random_state) of SkLearn and makes it (at least hypothetically speaking) to reproduce the same results?
score: 10
has answer: http://stackoverflow.com/a/52747730
answer count: 3
downvote count: 0
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/70959246
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52747871

http://stackoverflow.com/comment/92154510
comment on: http://stackoverflow.com/a/52609340
type: AnswerComment
score: 0
type: Comment
has text: ok try replacing the formdata back to body and pass "data" as it is. if this works then i ll explain the reasoning.

http://stackoverflow.com/comment/92222258
comment on: http://stackoverflow.com/q/52643763
type: QuestionComment
has text: I have created the frame and a labelframe inside the frame. So, inside the label frame I have inserted a button. By clicking the button, i want to open and see the content of the given path but not opening the files in that path. I have used the command in the ttk.Button, and have defined inside the command name.
score: 0
type: Comment

boolean
tags question: http://stackoverflow.com/q/52655912
tags question: http://stackoverflow.com/q/52593399
tags question: http://stackoverflow.com/q/52641263
tags question: http://stackoverflow.com/q/52596340
tag name: boolean
tags question: http://stackoverflow.com/q/52697433
tags question: http://stackoverflow.com/q/52610400
type: Tag

http://stackoverflow.com/a/52733191
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52733169
type: Answer
answers question: http://stackoverflow.com/q/52733169
score: 4
has body: Dont use loops with iterrows, because exist vectorized solution. You need to_timedelta with parameter unit: EmpComm = pd.DataFrame({ 'Duration (secs)':[3488, 2994,0, 0], 'Duration (hh:mm)':['0:58:08','0:49:54',np.nan,np.nan], }) EmpComm['Duration (hh:mm)'] = pd.to_timedelta(EmpComm['Duration (secs)'], unit='s') print (EmpComm) Duration (secs) Duration (hh:mm) 0 3488 00:58:08 1 2994 00:49:54 2 0 00:00:00 3 0 00:00:00
upvote count: 4

http://stackoverflow.com/q/52684950
tagged with: python
tagged with: valueerror
has comment: http://stackoverflow.com/comment/92298589
downvote count: 2
type: Question
has body: This is my source code: def farmer_johns(): r = int(input('Enter the radius of the circle in feet:')) #check for valid input try: while input &gt;= 0 : # area of brown #area of square - area of circle import math pi = math.pi area_square = (r+r)**2 area_circle = pi* r**2 area_brown = area_square - area_circle print('The area of the brown shaded region is {:.2f} feet^2.'.format(area_brown)) #turtle graphics set up import turtle wn = turtle.Screen() a = turtle.Turtle() a.pensize(5) #draw circles a.pencolor('green') a.penup() a.goto(r,r) a.pendown() a.circle(r) a.penup() a.goto(r,-r) a.pendown() a.circle(r) a.penup() a.goto(-r,-r) a.pendown() a.circle(r) a.penup() a.goto(-r,r) a.pendown() a.circle(r) #square a.pencolor('blue') a.penup() a.goto(r,r+r) a.pendown() a.goto(-r,r+r) a.goto(-r,-r+r) a.goto(r,-r+r) a.goto(r,r+r) #middle region a.pencolor('#654321') a.fillcolor('#b5651d') a.begin_fill() a.penup() a.goto(r,r) a.pendown() a.circle(r,-90) a.penup() a.goto(0,r+r) a.right(180) a.pendown() a.circle(r,-90) a.penup() a.goto(-r,r) a.left(-180) a.pendown() a.circle(r,-90) a.penup() a.goto(0,0) a.left(180) a.pendown() a.circle(r,-90) a.end_fill() #writing # a.write('The area of the brown shaded region is {:.2f} feet^2.'.format(area_brown)) except ValueError: print('invaild input') except TypeError: print('invaild input') The problem is when I enter in letters as a input I get this: farmer_johns() Enter the radius of the circle in feet:Ee Traceback (most recent call last): File "", line 1, in File "C:\Users\SueAnn\Desktop\Comp Sci\Projects\project_3\farmer john again.py", line 19, in farmer_johns r = int(input('Enter the radius of the circle in feet:')) ValueError: invalid literal for int() with base 10: 'Ee' The "Except:TypeError" line of code works but the 'Except: ValueError
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/92297504
tagged with: typeerror
has comment: http://stackoverflow.com/comment/92298561
answer count: 1
has comment: http://stackoverflow.com/comment/92297765
has title: Why is the Except:ValueError not working in my code?
favorite count: 0
has answer: http://stackoverflow.com/a/52687157
type: UnansweredQuestion

http://stackoverflow.com/a/52670427
score: 1
has body: I figured it out. The reason is because when I initialized textLabel I did not call self. This is a classic noob mistake. I'll leave this post up in case it helps anyone. self.textLabel = ttk.Label(self, text="Test File:" , font=NORM_FONT) self.textLabel.pack()
downvote count: 0
answers question: http://stackoverflow.com/q/52669006
type: Answer
upvote count: 1

http://stackoverflow.com/comment/92298859
type: Comment
comment on: http://stackoverflow.com/a/52685383
score: 1
has text: Unless your function doesn't need to interact with anything, it is almost always good practice to be accepting arguments and returning values from functions. Certainly, do no use global variables. The other alternative is to use a class.
type: AnswerComment

http://stackoverflow.com/q/52737997
has body: I have a list like below, ['Message-ID: &lt;5525962.1075855679785.JavaMail.evans@thyme&gt;\r\n', 'Date: Wed, 13 Dec 2000 07:04:00 -0800 (PST)\r\n', 'From: phillip.allen@enron.com\r\n', 'To: christi.nicolay@enron.com, james.steffes@enron.com, jeff.dasovich@enron.com, \r\n', '\tjoe.hartsoe@enron.com, mary.hain@enron.com, pallen@enron.com,\r\n', '\tpkaufma@enron.com, richard.sanders@enron.com, \r\n', '\trichard.shapiro@enron.com, stephanie.miller@enron.com, \r\n', '\tsteven.kean@enron.com, susan.mara@enron.com, \r\n', '\trebecca.cantrell@enron.com\r\n', 'Subject: \r\n', 'Mime-Version: 1.0\r\n'] In that To attribute contains only 3 e-mail ids, followed by that elements some elements starts with \t. Actually those \t list elements continuation of To attribute. My objective is I want to merge all the missing elements from the To attribute. So far I used this below code to solve my problem. l=['Message-ID: &lt;5525962.1075855679785.JavaMail.evans@thyme&gt;\r\n', 'Date: Wed, 13 Dec 2000 07:04:00 -0800 (PST)\r\n', 'From: phillip.allen@enron.com\r\n', 'To: christi.nicolay@enron.com, james.steffes@enron.com, jeff.dasovich@enron.com, \r\n', '\tjoe.hartsoe@enron.com, mary.hain@enron.com, pallen@enron.com,\r\n', '\tpkaufma@enron.com, richard.sanders@enron.com, \r\n', '\trichard.shapiro@enron.com, stephanie.miller@enron.com, \r\n', '\tsteven.kean@enron.com, susan.mara@enron.com, \r\n', '\trebecca.cantrell@enron.com\r\n', 'Subject: \r\n', 'Mime-Version: 1.0\r\n'] act= [ele.rstrip('\r\n') for ele in l if ele.startswith('To: ')] rem=[ele.lstrip('\t').rstrip('\r\n') for ele in l if ele.startswith('\t')] act.extend(rem) act=[''.join(act)] l=[ele for ele in l if not ele.startswith('To: ') and not ele.startswith('\t')] l.extend(act) print l Output: ['Message-ID: &lt;5525962.1075855679785.JavaMail.evans@thyme&gt;\r\n', 'Date: Wed, 13 Dec 2000 07:04:00 -0800 (PST)\r\n', 'From: phillip.allen@enron.com\r\n', 'Subject: \r\n', 'Mime-Version: 1.0\r\n', 'To: christi.nicolay@enron.com, james.stef…
favorite count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/52739904
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/52739475
score: 1
accepted answer: http://stackoverflow.com/a/52739904
has answer: http://stackoverflow.com/a/52739475
tagged with: list-comprehension
type: Question
has answer: http://stackoverflow.com/a/52738272
downvote count: 0
has title: transform list elements based on the string type (style)
answer count: 3
tagged with: python

http://stackoverflow.com/q/52687737
upvote count: 1
duplicate of: http://stackoverflow.com/q/5389507
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Python - Converting list to dict pairwise
downvote count: 0
score: 1
has body: I have a list that looks like this: mylist = [1, 'a', 2, 'b', 3, 'c'] and would like to end up with a dictionary: mydict = { 'a': 1, 'b': 2, 'c': 3,} At the moment I'm achieving it like so: mydict = {} for i, k in enumerate(mylist): if i == len(mylist)/2: break v = 2 * i mydict[mylist[v+1]] = mylist[v] Is there a more pythonic way of achieving the same thing? I looked up the itertools reference but didn't find anything in particular that would help with the above. Note: I'm happy with what I have in terms of achieving the goal, but am curious if there is anything that would be more commonly used in such a situation.
has answer: http://stackoverflow.com/a/52687770
type: Question
tagged with: optimization

http://stackoverflow.com/q/52636943
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92207274
has body: In several parts of the documentation (e.g. Dataset Iterators here) there are references to Stateful Objects. What exactly are they and what role do they play in the graph? To clarify, in the Dataset documentation there's an example with the one_shot_iterator that works because it's stateless: dataset = tf.data.Dataset.range(100) iterator = dataset.make_one_shot_iterator() what makes the iterator stateless?
accepted answer: http://stackoverflow.com/a/52643573
tagged with: tensorflow
type: Question
has title: What is a "stateful object" in tensorflow?
has comment: http://stackoverflow.com/comment/92207104
has comment: http://stackoverflow.com/comment/92207473
has comment: http://stackoverflow.com/comment/92207127
has comment: http://stackoverflow.com/comment/92206965
linked to: http://stackoverflow.com/q/41695117
has comment: http://stackoverflow.com/comment/92207578
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52643573

http://stackoverflow.com/q/52685458
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52685716
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has body: I am trying to read and put in a variable only the page number from an URL link.. which I scraped from a website. below is the print output of the variable which I scraped from the website Last › I need to put the per_page= value into a variable.. I tried to scrape only the number but no luck
accepted answer: http://stackoverflow.com/a/52685716
score: 1
upvote count: 1
tagged with: web-scraping
has title: Read the page number while scraping a website using BeautifulSoup

http://stackoverflow.com/comment/92159241
score: 1
has text: it does, I knew of the existence of groupby, but never had an instance of where it could be applied (I guess I didn't know we could use it that way). And I knew about .unique(), but not .nunique(), so I was always doing len(data.unique())... so I learned two things today, not too bad ^^
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52611800

http://stackoverflow.com/a/52709188
type: Answer
has comment: http://stackoverflow.com/comment/92345243
score: 2
accepted answer of: http://stackoverflow.com/q/52707117
has comment: http://stackoverflow.com/comment/92344875
downvote count: 0
answers question: http://stackoverflow.com/q/52707117
has body: The RGB values are all done using Javascript which Python or BeautifulSoup will not process which is why you will not see the information you want in the HTML that is returned. An alternative and easier approach is to spot the request the webpage is making to get the list of colours in the form of a JSON response. The data can then easily be converted to a Python dictionary using the json() requests function and then accessed as a Python dictionary: import requests URL = "https://www.asianpaints.com/content/ap/en/home/colour/colour-catalogue/jcr:content/oneColumnParsys/colourcatalog.colourfamily.json" data = requests.get(URL).json() for shade in data['shades']: name = shade['shadeName'] rgb = f"({shade['shadeR']}, {shade['shadeG']}, {shade['shadeB']})" print(f"{name} - {rgb}") Giving you the shades starting as follows: Raven Song - (64, 64, 64) Platinum Blue - (56, 61, 103) Black Currant - (65, 64, 67) Stormy Sky - (58, 65, 80) Armada - (55, 70, 91) Navy Blue - (56, 67, 90) Blue Mountain - (51, 73, 95) Rich Berry - (77, 67, 72) Tested on Python 3.6.6
has comment: http://stackoverflow.com/comment/92414710
has comment: http://stackoverflow.com/comment/92344927
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/92148387
type: Comment
score: 0
has text: this works with global function, thank you. If you can - just update your answer with id_strings instead of names, as I have updated my question - for convenience of future readers.
type: AnswerComment
comment on: http://stackoverflow.com/a/52605517

http://stackoverflow.com/a/52692339
type: Answer
answers question: http://stackoverflow.com/q/52689716
score: 0
has body: Can you provide an example of input data? Anyway, you don't need regex here, just split each email address on its @ and get the domains. If you have a string with one address per line, you can do the following. hosts = {} for address in addresses.splitlines(): _, host = address.split('@') if host not in hosts: hosts[host] = [address] else: hosts[host].append(address)

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/52593584
tags question: http://stackoverflow.com/q/52658396
tags question: http://stackoverflow.com/q/52658246
tags question: http://stackoverflow.com/q/52653339
type: Tag

http://stackoverflow.com/q/52612841
has answer: http://stackoverflow.com/a/67233384
tagged with: machine-learning
has title: How to cluster *features* based on their correlations to each other with sklearn k-means clustering
type: Question
score: 2
has answer: http://stackoverflow.com/a/67232608
answer count: 2
tagged with: k-means
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/92277209
favorite count: 0
has comment: http://stackoverflow.com/comment/92161235
has body: I have a pandas dataframe with rows as records (patients) and 105 columns as features.(properties of each patient) I would like to cluster, not the patients, not the rows as is customary, but the columns so I can see which features are similar or correlated to which other features. I can already calculate the correlation each feature with every other feature using df.corr(). But how can I cluster these into k=2,3,4... groups using sklearn.cluster.KMeans? I tried KMeans(n_clusters=2).fit(df.T) which does cluster the features (because I took the transpose of the matrix) but only with a Euclidian distance function, not according to their correlations. I prefer to cluster the features according to correlations. This should be very easy but I would appreciate your help.
upvote count: 3
downvote count: 1
tagged with: python
tagged with: sklearn-pandas
type: UnansweredQuestion

http://stackoverflow.com/q/52654280
tagged with: python
answer count: 0
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/92240493
upvote count: 6
linked to: http://stackoverflow.com/q/7670280
has title: Visualizing decision tree not using graphviz/web
has body: Due to some restriction I cannot use graphviz , webgraphviz.com to visualize decision tree (work network is closed from the other world). Question: Is there some alternative utilite or some Python code for at least very simple visualization may be just ASCII visualization of decision tree (python/sklearn) ? I mean, I can use sklearn in particular: tree.export_graphviz( ) which produces text file with tree structure, from which one can read a tree, but doing it by "eyes" is not pleasant ... PS Pay attention that graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) Image(graph.create_png()) will NOT work, since create_png uses implicitly graphviz
has comment: http://stackoverflow.com/comment/92250364
tagged with: visualization
tagged with: scikit-learn
tagged with: decision-tree
has comment: http://stackoverflow.com/comment/92284965
linked to: http://stackoverflow.com/q/20224526
favorite count: 0
has comment: http://stackoverflow.com/comment/92240457
type: UnansweredQuestion
score: 6

http://stackoverflow.com/q/52595385
type: Question
tagged with: python-import
linked to: http://stackoverflow.com/q/14132789
downvote count: 0
tagged with: relative-path
has answer: http://stackoverflow.com/a/52595448
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/92126859
upvote count: 1
has title: How to reference a module in its own folders?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52595448
score: 1
has body: I have python module, that i added to some other source root folder like this MyProject/my_new_file.py MyProject/MyModule/__init__.py MyProject/MyModule/script1.py MyProject/MyModule/script2.py And because root source is folder "MyProject", script1.py cannot include script2.py file like this: from script2 import my_awesome_function Does someone know a way that my modules imports are isolated within their own folder, so i dont have to reference import path from source root

http://stackoverflow.com/a/52612348
answers question: http://stackoverflow.com/q/52612286
score: 6
type: Answer
downvote count: 0
upvote count: 6
has body: When you trying to pass arguments like this **args to print() this arguments will be unpacked as keyword arguments, and this will raise the error, since print() doesn't expect such arguments as mutate() method has. So you need to remove **args: print('args', args)

http://stackoverflow.com/comment/92196665
type: Comment
type: QuestionComment
has text: @Mona just posted an answer
comment on: http://stackoverflow.com/q/52616414
score: 0

http://stackoverflow.com/comment/92165411
comment on: http://stackoverflow.com/q/52614955
score: 0
type: Comment
has text: @Sraw, go to the `upload` folder [of web2py framework] of pythonanywhere.com file system and download - http://joxi.ru/n2Yzp84cow0V5A
type: QuestionComment

http://stackoverflow.com/comment/92387113
type: Comment
has text: The code you show should *not* have given a key error, so there's something you're not telling us. Do all the items in your dict have at least 4 elements?
type: QuestionComment
comment on: http://stackoverflow.com/q/52730850
score: 0

http://stackoverflow.com/comment/92186197
type: Comment
comment on: http://stackoverflow.com/q/52625544
score: 1
has text: If you want the address of the actual data buffer you can use `x.ctypes.data`
type: QuestionComment

http://stackoverflow.com/comment/92250364
score: 0
type: QuestionComment
has text: Also here some info: https://stackoverflow.com/questions/20224526/how-to-extract-the-decision-rules-from-scikit-learn-decision-tree?noredirect=1&lq=1
type: Comment
comment on: http://stackoverflow.com/q/52654280

http://stackoverflow.com/a/52654860
answers question: http://stackoverflow.com/q/52654797
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92241208
has comment: http://stackoverflow.com/comment/92241295
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52654797
has body: Your result appears to be a string in YYYY-mm-dd format with time, so just slice it. {{price_level.modified[:10] }}

http://stackoverflow.com/q/52678722
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52683510
has answer: http://stackoverflow.com/a/52678956
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/92286446
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has body: I need to save some variables to a file. I can can write to the file but I don't know how to order the contents of the file in python. The file will contain a string paired with an integer and I want to order it from the highest integer to lowest. Data in the file: 3 third string 1 first string 2 second string Expected Output: 1 first string 2 second string 3 third string Any help is greatly appreciated.
has title: How to save ordered variables to a file

http://stackoverflow.com/a/52702443
answers question: http://stackoverflow.com/q/52702247
upvote count: 0
type: Answer
has body: You can simply do: df.columns = ['a','b','c']
downvote count: 1
score: -1

http://stackoverflow.com/q/52663701
score: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/92260891
has comment: http://stackoverflow.com/comment/92257466
has title: ValueError: Only call `sigmoid_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...)
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92257745
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92260045
has body: I have just build my first model using Phyton, Keras and Tensorflow. My model looks like this: model = Sequential() model.add(Convolution2D(32, 3, 3, input_shape=(img_width, img_height,3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(32, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(64, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) Now i'm trying to compile it, model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) but i got this error: ValueError: Only call sigmoid_cross_entropy_with_logits with named arguments (labels=..., logits=..., ...) I can't seem to find what the problem is. Please let me know what I'm doing wrong..

http://stackoverflow.com/q/52593916
has comment: http://stackoverflow.com/comment/92122689
possible better answer: http://stackoverflow.com/a/52594037
tagged with: python
has answer: http://stackoverflow.com/a/52594037
has answer: http://stackoverflow.com/a/52595089
score: -1
accepted answer: http://stackoverflow.com/a/52595089
downvote count: 1
type: AnsweredQuestion
has body: I could do this same task in C++; But I am learning python newly, I just want to try out the similiar code I used in C++ - but I am having some problems in this code, Can you help out what wrong I did; def constructPalin(string,length): i = 0 j = length - 1; while(i &lt; j): if (string[i] == string[j] and string[i] != '.'): continue elif (string[i] == string[j] and string[i] == '.'): string[i] = 'a' string[j] = 'a' continue elif (string[i] == '.'): string[i] = string[j] continue elif (string[j] == '.'): string[j] = string[i] continue else: string="-1" return string i=i+1 j=j-1 return string string=input() length = len(string) string=constructPalin(string,length) print(string) I am getting correct output only for -1;Help me out in other cases
type: Question
has title: Print lexicographically smallest palindrome after filling each '.' character, if it possible to construct one. Print -1 otherwise in python
answer count: 2
upvote count: 0
favorite count: 0

http://stackoverflow.com/q/52688019
type: Question
has answer: http://stackoverflow.com/a/62479637
score: 5
has comment: http://stackoverflow.com/comment/92500994
answer count: 3
has body: I am currently using Windows OS. I have installed Anaconda for creating environments. I have successfully created another environment with python 2.7. I have also installed spacy on that environment using: conda install --name myenv -c spacy spacy But now I need to download 'en module to run it. On spacy official site they have mentioned the following commands for the same: conda install -c conda-forge spacy python -m spacy download en then I activated the 2nd environment using: activate myenv But running the second command(python -m spacy..)it gives me an error: No module named spacy.__main__; 'spacy' is a package and cannot be directly executed Please help me..
favorite count: 0
upvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92303180
has title: How do I download en for spacy using conda?
tagged with: python
tagged with: nlp
has answer: http://stackoverflow.com/a/55068728
tagged with: spacy
downvote count: 0
has answer: http://stackoverflow.com/a/52769941

http://stackoverflow.com/comment/92298328
comment on: http://stackoverflow.com/q/52600305
has text: @AjayShah I'm adding them to an Amazon S3 bucket, so storage isn't much of an issue as I have a tonne of space there. Will try out the renaming strategy, thanks for the help
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/52698147
answers question: http://stackoverflow.com/q/52698027
downvote count: 0
has comment: http://stackoverflow.com/comment/92323197
has body: List comprehensions are all about appending to the list in a for loop (creating the list at the start, returning that list as a result), but you need to convert your logic a little first. A list comprehension basically is a series of nested loops and if filters, and a single expression that determines the values to append: for ... in ...: if ...: for ... in ...: expression_generating_value_to_append with a minimum of one loop, with zero or more if filters and additional loops. If you can convert your code to such a structure, you can make it a list comprehension. Your code isn't quite there yet, because you have substring = s[g:o+1] passable = True for char in substring: if char == "i": passable = False if passable: subs.append(substring) but that can easily be transformed to a simple in containment test: if "i" not in s[g:o + 1]: subs.append(s[g:o + 1]) That's basically the same thing; if the character "i" is not in the substring, then the substring is passable and can be appended: So now you have subs = [] for g in range(len(s)): for o in range(g, len(s)): if "i" not in s[g:o+1]: subs.append(s[g:o+1]) which can be converted to a list comprehension; use the same loops and if tests, but move the part in subs.append() to the front; that's the part that produces each value in the output list: subs = [ s[g:o+1] for g in range(len(s)) for o in range(g, len(s)) if "i" not in s[g:o+1] ] or on one line: subs = [s[g:o+1] for g in range(len(s)) for o in range(g, len(s)) if "i" not in s[g:o+1]] and this indeed produces the same output as your loop: &gt;&gt;&gt; s = "lallalaiial" &gt;&gt;&gt; subs = [] &gt;&gt;&gt; for g in range(len(s)): ... for o in range(g, len(s)): ... substring = s[g:o+1] ... passable = True ... for v in range(len(substring)): ... if(substring[v] == "i"): ... passable = False ... if(passable): ... subs.append(substring) ... &gt;&gt;&gt; subs ['l', 'la', 'lal', 'lall', 'lalla', 'lallal', 'lallala', 'a', 'al', 'all', 'alla', 'allal', 'allala', 'l', 'll', 'l…
has comment: http://stackoverflow.com/comment/92323195
upvote count: 3
has comment: http://stackoverflow.com/comment/92323148
has comment: http://stackoverflow.com/comment/92323013
has comment: http://stackoverflow.com/comment/92323222
type: Answer
has comment: http://stackoverflow.com/comment/92322909
score: 3

http://stackoverflow.com/q/52723416
type: UnansweredQuestion
tagged with: tensorflow
score: 1
has body: I am currently working on a project to classify different upper body exercises using 2 gyroscopes and 1 accelerometer (9 channels of data). My approach is to use a sliding window approach for 6 exercises, and feed the windows to the CNN. The data is collected at 25Hz, and I created windows of 64 samples (2.56 seconds, with 50% overlap -> 32 samples) 9 channels. The dimensions of the windows are thereby 9x64 (Rows correspond to the different sensors and the columns to the readings), the reason for this is to be able to perform the convolution operations in the time domain (horizontal axis). With that being said I have created a small database with 60 windows per exercise, for a total of 360 windows. The data set contains 2 folders (Train, Test), where each of these two folders has 6 folders within (Each corresponding to the different exercises). In each exercise folder I have 48 windows for the Training samples and 12 windows for the testing samples. Each window is saved as a CSV file, with the dimensions of 9x64. My question is, what is the best solution to import the data using keras into the CNN. I have done a similar project using JPEG images, using the ImageDataGenerator prepossessing class from keras. For this project I had two folders (Test, Train) and each folder contain a folder for Cat and Dog pictures. My question is if there's a similar approach to import the data using CSV files :)
type: Question
upvote count: 1
tagged with: keras
has title: How to import data window sensor data into python to be fed to a CNN for HAR
tagged with: python
tagged with: har
favorite count: 0
answer count: 0
downvote count: 0

http://stackoverflow.com/q/52726049
has body: I have a C library that I am writing a wrapper for. Most of the functions in this library take 'an out arguments' (the result is returned in the variable passed). So how do I test the case when: - self._system returned as None (from C as a side effect), but - the function returns success Please see the code below for more details main.py myLibDLL = CDLL('mylib.dll') class System(): _system = None def __init__(self): self._system = c_void_p(None) def GetSys(self): # - The C function prototype # ERROR_CODE XXX_API CGetSys(void* phSys) # - myLibDLL.CGetSys() is the call to mock retErr = myLibDLL.CGetSys(byref(self._system)) checkReturnErr(retErr) if self._system.value == None: raise BaseException('Failed to Get Sys') # case to test unit tests file @patch("main.myLibDLL.CGetSys") def test_GetSys_sysIsNone_afterCGetSysisCalled(self, mock_CGetSys): self.sys = System() # What expectations shoudl I set here? mock_CGetSys.return_value = 0 # to pass checkReturnErr() mock_CGetSys.??? = None # the question # test with self.assertRaises(BaseException): self.system.GetSys()
type: Question
has comment: http://stackoverflow.com/comment/92521994
tagged with: ctypes
has answer: http://stackoverflow.com/a/52878883
has comment: http://stackoverflow.com/comment/92377352
has comment: http://stackoverflow.com/comment/92377891
tagged with: mocking
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52878883
has comment: http://stackoverflow.com/comment/92386095
has title: Python : Mocked return value of parameter passed by reference to a C library
tagged with: python
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/92377349
score: 1
downvote count: 1

openmpi
tags question: http://stackoverflow.com/q/52589839
type: Tag
tag name: openmpi

scipy
tags question: http://stackoverflow.com/q/52703946
tags question: http://stackoverflow.com/q/52674527
tags question: http://stackoverflow.com/q/52671502
tags question: http://stackoverflow.com/q/52713261
tags question: http://stackoverflow.com/q/52668072
tags question: http://stackoverflow.com/q/52720016
tags question: http://stackoverflow.com/q/52709037
tags question: http://stackoverflow.com/q/52733969
tags question: http://stackoverflow.com/q/52630865
tags question: http://stackoverflow.com/q/52634225
tags question: http://stackoverflow.com/q/52727388
tags question: http://stackoverflow.com/q/52678356
tags question: http://stackoverflow.com/q/52629524
tags question: http://stackoverflow.com/q/52639150
tags question: http://stackoverflow.com/q/52595611
tags question: http://stackoverflow.com/q/52745546
type: Tag
tags question: http://stackoverflow.com/q/52689140
tag name: scipy
tags question: http://stackoverflow.com/q/52672516
tags question: http://stackoverflow.com/q/52723212
tags question: http://stackoverflow.com/q/52685069
tags question: http://stackoverflow.com/q/52690110
tags question: http://stackoverflow.com/q/52649815
tags question: http://stackoverflow.com/q/52676798
tags question: http://stackoverflow.com/q/52723383
tags question: http://stackoverflow.com/q/52591979
tags question: http://stackoverflow.com/q/52665338
tags question: http://stackoverflow.com/q/52631878
tags question: http://stackoverflow.com/q/52723482
tags question: http://stackoverflow.com/q/52743352
tags question: http://stackoverflow.com/q/52635241
tags question: http://stackoverflow.com/q/52594235
tags question: http://stackoverflow.com/q/52665131
tags question: http://stackoverflow.com/q/52715626
tags question: http://stackoverflow.com/q/52670362
tags question: http://stackoverflow.com/q/52693899
tags question: http://stackoverflow.com/q/52617334
tags question: http://stackoverflow.com/q/52602576
tags question: http://stackoverflow.com/q/52649191
tags question: http://stackoverflow.com/q/52642945
tags question: http://stackoverflow.com/q/52690580
tags question: http://stackoverflow.com/q/52683117
tags question: http://stackoverflow.com/q/52653371
tags question: http://stackoverflow.com/q/52710223
tags question: http://stackoverflow.com/q/52742336
tags question: http://stackoverflow.com/q/52618490
tags question: http://stackoverflow.com/q/52700878
tags question: http://stackoverflow.com/q/52691465
tags question: http://stackoverflow.com/q/52692315

http://stackoverflow.com/a/52631703
downvote count: 0
has body: I believe that a query will always return an iterator. See this page on the google.cloud.datastore.query.Iterator. The iterator allows you to step through the results. This includes a query response where there are no results. It looks like the property called num_results may be of value to us as it seems to return the count of results that are available to be iterated over. If num_results is 0, then the query returned no items.
type: Answer
answers question: http://stackoverflow.com/q/52631422
score: 2
upvote count: 2

http://stackoverflow.com/comment/92148463
type: AnswerComment
comment on: http://stackoverflow.com/a/52607173
score: 0
type: Comment
has text: @user2883215 put comma ! other wise it's working thanks

tcp
type: Tag
tags question: http://stackoverflow.com/q/52672847
tags question: http://stackoverflow.com/q/52681921
tags question: http://stackoverflow.com/q/52597436
tags question: http://stackoverflow.com/q/52680888
tag name: tcp

http://stackoverflow.com/a/52644115
upvote count: 16
has body: # Declare table class SomeTable(Table): status = Col('Customer') city = Col('City') product_price = Col('Country') # Convert the pandas Dataframe into dictionary structure output_dict = output.to_dict(orient='records') # Populate the table table = SomeTable(output_dict) return (table.__html__()) or as pandas return static HTML file you can render it as page using Flask @app.route('/&lt;string:filename&gt;/') def render_static(filename): return render_template('%s.html' % filename) It's the Idea of how we can do it in Flask. Hope you can understand this and let me know if it's not helping! Update: import pandas as pd df = pd.DataFrame({'col1': ['abc', 'def', 'tre'], 'col2': ['foo', 'bar', 'stuff']}) from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return df.to_html(header="true", table_id="table") if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) But I'd go with Flask HTML feature rather than DataFrame to HTML (due to styling)
type: Answer
answers question: http://stackoverflow.com/q/52644035
has comment: http://stackoverflow.com/comment/101085940
downvote count: 0
has comment: http://stackoverflow.com/comment/92220661
score: 16
has comment: http://stackoverflow.com/comment/92220581

http://stackoverflow.com/comment/92438222
type: AnswerComment
has text: NaN comes from the column which does not have any value. Table contains 3 columns. 2nd column had no values. In place of empty space, NaN is displayed.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52717840

http://stackoverflow.com/a/52657911
has comment: http://stackoverflow.com/comment/92246774
score: 0
has comment: http://stackoverflow.com/comment/92247008
has comment: http://stackoverflow.com/comment/92246615
has comment: http://stackoverflow.com/comment/92246704
type: Answer
answers question: http://stackoverflow.com/q/52657839
has comment: http://stackoverflow.com/comment/92247557
has body: I'm not entirely familiar with the tweepy's response object but if it's as you described above i.e.the User object, then you can probably try this: import json response = "{'response':" + User._json + "}" data = json.loads(response) data['in_reply_to_status_id'] &gt;&gt;&gt;1048042979359936513 Edit: If in_reply_to_status_id is an attribute of User then you should be able to call it by just User.in_reply_to_status_id
has comment: http://stackoverflow.com/comment/92247404
has comment: http://stackoverflow.com/comment/92246425
has comment: http://stackoverflow.com/comment/92246825

http://stackoverflow.com/a/52690612
type: Answer
has comment: http://stackoverflow.com/comment/92308421
accepted answer of: http://stackoverflow.com/q/52690580
downvote count: 0
score: 3
has body: What you need is exactly the outer method of ufuncs: ufunc.outer(A, B, **kwargs) Apply the ufunc op to all pairs (a, b) with a in A and b in B. values = scipy.special.eval_chebyt.outer(degs, pnts) #array([[ 1. , 1. , 1. ], # [ 0. , 0.1 , 0.2 ], # [-1. , -0.98 , -0.92 ], # [-0. , -0.296 , -0.568 ], # [ 1. , 0.9208, 0.6928]]) UPDATE For more parameters, you must broadcast by hand. meshgrid often help for that,spanning each parameter in a dimension. For exemple : n=3 alpha = numpy.array(range(5)) beta = numpy.array(range(3)) x = numpy.array(range(2)) data = numpy.meshgrid(n,alpha,beta,x) values = scipy.special.eval_jacobi(*data)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52690580
has comment: http://stackoverflow.com/comment/92308178
upvote count: 3

http://stackoverflow.com/a/52734395
downvote count: 1
has comment: http://stackoverflow.com/comment/98134254
answers question: http://stackoverflow.com/q/52731302
has comment: http://stackoverflow.com/comment/98133924
upvote count: 2
has comment: http://stackoverflow.com/comment/98134060
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/92393563
has body: You aren't using the Lambda layer correctly, it should be like this: input_result = Input(shape=(int(outputs.shape[0]), int(outputs.shape[1]),int(outputs.shape[2]))) outputs = Lambda(self.convert_tensor, output_shape=(10, 15, 9488))(input_result) model = Model(input_result, outputs) You have to pass the function to the lambda, not a function call, and then you "call" the lambda with the appropriate input.

http://stackoverflow.com/comment/92290176
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52680611
has text: I did try but stack overflow not taking my upvote i dont know why @pygo
score: 0

http://stackoverflow.com/q/52714095
type: Question
upvote count: 1
downvote count: 0
tagged with: python
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: why appium Typing Chinese garbled in Sina News Text Box
has body: Appium v1.9.0 windows10 python3.6 I'm using appium to test Sina News app. It's Chinese garbled. my code #-*-coding:utf-8-*- #import package from selenium.webdriver.support.ui import WebDriverWait from appium import webdriver #create desired_caps desired_caps = {} desired_caps['platformName'] = 'Android' #devicename desired_caps['deviceName'] = 'TGIRPJOBFUZ9IJSW' #platformVersion desired_caps['platformVersion'] = '6.0' #appPackage name desired_caps['appPackage'] = 'com.sina.news' desired_caps['appActivity'] = 'com.sina.news.ui.MainActivity' desired_caps['noReset'] = True desired_caps['unicodeKeyboard'] = True desired_caps['resetKeyboard'] = True #start up appium driver = webdriver.Remote('http://192.168.54.56:4723/wd/hub', desired_caps) #check xpath if WebDriverWait(driver,20).until(lambda x:x.find_element_by_xpath("//android.widget.TextView[@resource-id='com.sina.news:id/avl']")): #click driver.find_element_by_xpath("//android.widget.TextView[@resource-id='com.sina.news:id/avl']").click() #send keys driver.find_element_by_xpath("//android.widget.EditText[@resource-id='com.sina.news:id/ajg']").send_keys('汉能') while driver.find_element_by_xpath("//android.widget.EditText[@resource-id='com.sina.news:id/ajg']").text != "汉能": driver.find_element_by_xpath("//android.widget.EditText[@resource-id='com.sina.news:id/ajg']").send_keys('汉能') driver.find_element_by_xpath("//android.widget.ListView[@resource-id='com.sina.news:id/avn']/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]").click() why appium Typing Chinese garbled in Sina News Text Box?
tagged with: appium-desktop
score: 1

http://stackoverflow.com/comment/92256391
type: QuestionComment
comment on: http://stackoverflow.com/q/52662758
has text: I added information about the library version and the backend, thanks for your comment!
score: 0
type: Comment

http://stackoverflow.com/comment/92485201
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52705417
has text: @StarBright `isdigit` is the function, `isdigit()` is the result, a boolean value

http://stackoverflow.com/q/52729163
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/92384119
answer count: 1
has comment: http://stackoverflow.com/comment/92384788
has comment: http://stackoverflow.com/comment/92384475
has title: NCCL install / Tensorflow complie error with RTX 2080ti
has comment: http://stackoverflow.com/comment/92383879
has comment: http://stackoverflow.com/comment/92383744
has answer: http://stackoverflow.com/a/52729902
tagged with: python
has comment: http://stackoverflow.com/comment/92383970
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92384156
tagged with: tensorflow
type: Question
has body: I am installing Cuda 10, CuDnn 7.3 and NCCL 2.3 on Ubuntu 18.04 with a 2080ti. I am having trouble with the NCCL part. When i try to compile Tensorflow it says error and cannot find NCCL-SLA.txt file. But when i search for that file i cant find it anywhere either? So when i look online people say you can move it from another directory but its not there for me so i do not know what to do. Here is the error code i am getting: ERROR: missing input file '@local_config_nccl//:nccl/NCCL-SLA.txt' ERROR: /home/josh/tensorflow/tensorflow/tools/pip_package/BUILD:166:1: //tensorflow/tools/pip_package:build_pip_package: missing input file '@local_config_nccl//:nccl/NCCL-SLA.txt' Target //tensorflow/tools/pip_package:build_pip_package failed to build Use --verbose_failures to see the command lines of failed build steps. ERROR: /home/josh/tensorflow/tensorflow/tools/pip_package/BUILD:166:1 1 input file(s) do not exist INFO: Elapsed time: 17.209s, Critical Path: 11.30s INFO: 353 processes, local. FAILED: Build did NOT complete successfully

http://stackoverflow.com/comment/92181854
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52624063
type: Comment
has text: @CIsForCookies: yep, `defaultdict` is useful very often

bar-chart
tags question: http://stackoverflow.com/q/52638835
tags question: http://stackoverflow.com/q/52614194
tags question: http://stackoverflow.com/q/52670304
type: Tag
tags question: http://stackoverflow.com/q/52625307
tag name: bar-chart
tags question: http://stackoverflow.com/q/52687936

http://stackoverflow.com/comment/92114719
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52589520
has text: No, it didn't as I am using a big machine. I was just a bit curious , hence I asked.

http://stackoverflow.com/comment/92246352
has text: okay, I understand, and if you press a fifth item should that item be painted too?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52656840
type: Comment

http://stackoverflow.com/comment/94263008
has text: Does `root.pem` directly sign `client.pem ` or is there an intermediate certificate?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52680044
type: QuestionComment

http://stackoverflow.com/comment/92414210
score: 3
has text: The reason the while loop doesn't exit when it finds an invalid score is because your for loop is still going to run to completion from 0 to 6 before the while loop checks if it is valid. You probably want to break out of the for loop when you find an invalid score. I also do not see the point of the while loop as you set valid_score to False at the end always so the while loop only ever runs once.
comment on: http://stackoverflow.com/q/52744812
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92742709
comment on: http://stackoverflow.com/a/52815854
type: AnswerComment
type: Comment
score: 0
has text: I'm not sure really what happened behind the scenes, on the first try as I changed the heavy object it changed automatically without any call in the workers. Later when I tried to reproduce I couldn't change it even when I called reloading function (which alters the Borg's shared state). I'm assuming that each process gets its own borg and the shared states is per worker process, and I need all processes to use the same object

http://stackoverflow.com/comment/92116108
type: Comment
type: QuestionComment
has text: *I* would prefer Debian, but this really depends on what you do. The key is that the base image must be consistent with the PGDG repository you enable and use to install PostgreSQL.
comment on: http://stackoverflow.com/q/52589268
score: 0

http://stackoverflow.com/a/52670968
has body: I think that you better create an SQL View for this scenario and associate it with the model tpt.product.inventory and you could remove all of the code you are using to match the records(delete and create the new ones) You could find a very similar example here: https://github.com/odoo/odoo/blob/695050dd10e786d7b316f6e7e40418441cf0c8dd/addons/stock/report/report_stock_forecast.py
score: 0
answers question: http://stackoverflow.com/q/52639434
type: Answer

http://stackoverflow.com/comment/92274649
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52672369
type: Comment
has text: For the record, making a function take input via `input` from the user directly is not making it more friendly. It's making it *less* reusable. 99% of functions can and should receive input as arguments and `return` values. The other 1% are functions that do nothing but accept user input and provide output, with all use of the input and production of the output values handled by calling other normal functions in between. Usually, the other functions logically fit into the `main` method of your program (they may be factored out for cleanliness, but they're logically part of `main`).

http://stackoverflow.com/q/52598416
score: 1
has body: I have created two lists of tensors that are multiple sizes, for example: n=5 x=[placeholder(tf.float64,[i*2,None]) for i in range(n)] y=[placeholder(tf.float64,[i*2,None]) for i in range(n)] I want to use x as the input to an auto-encoder, and y as the output: 1) Is there a better way to group my tensors instead of using a list? 2) How can I ask tesnsorflow to learn simultaneously from all the tensors within x? should I use tf.group? or is there a better way? Thanks
tagged with: tensorflow
type: Question
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52600329
has title: Tensorflow to optimize a list of tensors
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52600329

http://stackoverflow.com/comment/92263989
type: QuestionComment
comment on: http://stackoverflow.com/q/52667035
score: 1
has text: https://gist.github.com/ or use a paste-bin type website
type: Comment

http://stackoverflow.com/q/52675886
has title: Dominant 3 frequencies in the DFT and Energy of the 3 dominant frequencies from a list
tagged with: python
type: AnsweredQuestion
tagged with: dft
has comment: http://stackoverflow.com/comment/92281157
has answer: http://stackoverflow.com/a/52676777
type: Question
has body: data = [222, 251,212,188 , 244, 202, 198, 244, 175, 216] import numpy as np print("Discrete fourier transform") print(np.fft.fft(data)) print("Inverse discrete fourier transform") print(np.fft.ifft(data)) Above code is the dft code using numpy. The Question is: How to find Dominant 3 frequencies in the DFT and Energy of the 3 dominant frequencies such like 1-D list? Additionally: Is there anyway DFT and IDFT from 2-D or 3-D list and corresponding Dominant 3 frequencies in the DFT and Energy of the 3 dominant frequencies?
tagged with: numpy
score: 0
accepted answer: http://stackoverflow.com/a/52676777
answer count: 1
has comment: http://stackoverflow.com/comment/92281194
tagged with: fft

http://stackoverflow.com/q/52720016
has body: I've been looking for a way to (efficiently) compute a distance matrix from a target value and an input matrix. If you consider an input array as: [0 0 1 2 5 2 1] [0 0 2 3 5 2 1] [0 1 1 2 5 4 1] [1 1 1 2 5 4 0] Ho do you compute the spatial distance matrix associated to the target value 0? i.e. what is the distance from each pixel to the closest 0 value? Thanks in advance
type: Question
tagged with: scipy-spatial
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52720340
accepted answer: http://stackoverflow.com/a/52720340
tagged with: scipy
has title: How to compute a spatial distance matrix from a given value
tagged with: numpy
tagged with: distance
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
upvote count: 1

http://stackoverflow.com/comment/92599083
has text: Guilherme, I've circled the code, both the first and the one with an input image, and there is no output or error msg.
type: AnswerComment
comment on: http://stackoverflow.com/a/52841259
score: 0
type: Comment

http://stackoverflow.com/a/52744152
has body: Code works well with python2.7 and changing your code with (removed extra whitespace): if __name__ == '__main__': print('hello') main() For these kind of problems don't hesitate to use a debugger. PyCharm for example https://www.jetbrains.com/pycharm/ After that : hello hello hello ('Marginal for node', 0, 'is ', array([0.59098405, 0.40901595])) hello hello ('Marginal for node', 1, 'is ', array([0.10161794, 0.89838206])) hello hello ('Marginal for node', 2, 'is ', array([0.59622558, 0.40377442])) hello hello ('Marginal for node', 3, 'is ', array([0.06575926, 0.93424074])) hello hello ('Marginal for node', 4, 'is ', array([0.56742955, 0.43257045])) hello hello ('Marginal for node', 5, 'is ', array([0.12965594, 0.87034406]))
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52743774
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52743774

http://stackoverflow.com/q/52669978
tagged with: python
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/92269856
type: Question
has title: How to clear the exception state in Python
has answer: http://stackoverflow.com/a/52670188
has comment: http://stackoverflow.com/comment/92269807
has body: I have a try/except block around a call to an API. It appears to me that once I get an exception, all valid try cases after that exception will see the same exception. The only way I have been able to get it to work is to re-start my Python script. I googled around and found PyErr_clear() but that is for the C-API. Is there something I can call from plain-old Python that will clear the exception state? Here is the basic idea of what I am doing: def get_and_print_data(key): try: data = get_data_from_some_3rd_party_api(key) except Exception as ex: print("Failed to get data for",key,": ",str(ex)) return print("data=",data) Then in main I have get_and_print_data("Valid Key") ## This works get_and_print_data("INvalid Key") ## This gets exception, as expected get_and_print_data("Valid Key") ## This and all subsequent calls to get_and_print_data() fail with the same exception.
tagged with: try-except
score: 3
has comment: http://stackoverflow.com/comment/92270176
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92270066
has comment: http://stackoverflow.com/comment/92269980
accepted answer: http://stackoverflow.com/a/52670188

http://stackoverflow.com/comment/92333121
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52700226
has text: The error message seems pretty clear - there is a conflict between the anaconda package and the prettytable package. You need to create a new environment that does not include the anaconda package to be able to install the prettytable package.

http://stackoverflow.com/a/52704676
score: 0
answers question: http://stackoverflow.com/q/52704126
type: Answer
has body: First Convert the date strings to pandas.Timestamps: &gt;&gt;&gt; df['startdate'] = pd.to_datetime(df['startdate']) &gt;&gt;&gt; df['enddate'] = pd.to_datetime(df['enddate']) &gt;&gt;&gt; df["Time_Conversation"] = df['enddate']-df['startdate'] &gt;&gt;&gt; df cpf day startdate enddate Time_Conversation 0 1234 1 2018-08-01 12:50:00 2018-08-01 15:50:00 0 days 03:00:00 1 1234 1 2018-08-01 14:30:00 2018-08-01 15:50:00 0 days 01:20:00 2 1234 1 2018-08-01 14:50:00 2018-08-01 15:50:00 0 days 01:00:00 3 1234 2 2018-08-01 20:20:00 2018-08-02 23:50:00 1 days 03:30:00 4 1234 2 2018-08-01 22:50:00 2018-08-02 23:50:00 1 days 01:00:00 5 1235 1 2018-08-01 11:50:00 2018-08-01 15:20:00 0 days 03:30:00 6 5212 1 2018-08-01 14:50:00 2018-08-01 15:20:00 0 days 00:30:00 Note: Passing infer_datetime_format=True can often-times speedup a parsing if its not an ISO8601 format exactly, but in a regular format, In some cases this can increase the parsing speed by ~5-10x. Hence, we can use that as well .. df['startdate'] = pd.to_datetime(df['startdate'], infer_datetime_format=True) df['enddate'] = pd.to_datetime(df['enddate'], infer_datetime_format=True)

http://stackoverflow.com/comment/137079154
has text: @imcz I have seen this as a note in Celery AbortableTask docs. Does it mean if I use Redis as broker and backend I can't use abortable tasks?
comment on: http://stackoverflow.com/a/54880615
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52729345
has body: You were close. Just modifying your code, the correct implementation of checking an entry m against multiple options, it would look like the following. To check for multiple options, you use in, for ex. if m in [4, 6, 9, 11] instead of ==. if d &gt; 30 and m in [4, 6, 9, 11]: print("This date is invalid") elif d &gt; 31: print ("This date is invalid") elif m not in [1,2,3,4,5,6,7,8,9,10,11,12]: print ("This date is invalid") else: print("This date is valid")
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52729318
downvote count: 0
type: Answer

http://stackoverflow.com/q/52613621
score: 1
type: Question
has title: Clean pythonic composition with default parameters
has body: Suppose I want to compose two objects and I'd like to be able to be able to define multiple constructors that respect the default arguments. class A: def __init__(x,y=0): self.x = x self.y = y class B: def __init__(w,objA, z=1): self.w = w self.objA = objA self.z = z I'd like to have multiple constructors for B which allow me to either pass an object A or pass parameters and then construct A. Looking at What is a clean, pythonic way to have multiple constructors in Python? I can do: class B: def __init__(w, objA, z=1): self.w = w self.objA = objA self.z=z @classmethod def from_values(cls,w,z,x,y): objA = A(x,y) return cls(w,objA,z) The problem is that the default values are being overwritten and I'd like to keep them. The following of course does not work. @classmethod def from_values(cls,w,x,**kwargs): objA = A(x,**kwargs) return cls(w,objA,**kwargs) So it seems I'm stuck with remembering the default values and calling them like this @classmethod def from_values(cls,w,x,z=1,y=0): objA = A(x,y) return cls(w,objA,z) This is not what I want since I'd rather have the objects themselves handle the default values and not be forced remember the default values. I could do one better than the above and use: @classmethod def from_values(cls,w,x,z=1,**kwargs): objA = A(x,**kwargs) return cls(w,objA,z) But in this case I still need to "remember" the default value for z. Is there a Pythonic solution to this? Is this a design problem? Can someone point me to a good design pattern or best practices? This problem compounds when composing with several objects... class L: def __init__(objM,objN): self.objM = objM self.objN = objN @classmethod def from_values(cls, m1,m2,m3,n1,n2): objM = M(m1,m2,m3) objN = N(n1,n2) return cls(objM, objN)
tagged with: default-value
has answer: http://stackoverflow.com/a/52614220
accepted answer: http://stackoverflow.com/a/52614220
upvote count: 1
tagged with: composition
answer count: 1
linked to: http://stackoverflow.com/q/682504
favorite count: 0
tagged with: constructor
tagged with: python
tagged with: design-patterns
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/92313013
score: 0
type: Comment
has text: This actually produces too many combinations, when sizes are not unique. The real input can easily have sizes repeated (as items are `(value, size)` tuples, items with a different value can still have the same size). For example, for `combos([1, 1, 2], 2)` you produce *4* `[1, 1]` pairs, where you have `[first 1, first 1]`, `[first 1, second 1]`, `[second 1, first 1]` and `[second 1, second 1]`. The combinations `[first 1, second 1]` and `[second 1, first 1]` are the exact same solution in a knapsack solution (it doesn't matter what order you pick items).
comment on: http://stackoverflow.com/a/52667107
type: AnswerComment

http://stackoverflow.com/q/52738256
tagged with: scripting
tagged with: devops
tagged with: python
tagged with: list
answer count: 2
possible better answer: http://stackoverflow.com/a/52738614
upvote count: 1
has answer: http://stackoverflow.com/a/52738614
accepted answer: http://stackoverflow.com/a/52738353
tagged with: http://stackoverflow.com/tag/json
has body: I'm having issue to execute this scenario from my codes. I have to list inside .ini file. [FMI] vendorCodes=["a", "b", "c", "d", "e"] supplierName=["Test 1", "Test 2", "Test 3", "Test 4", "Test 5" ] I used json.loads to call the list from the .ini file. vendorCodes = json.loads(config.get('Section1','vendorCodes')) supplierName = json.loads(config.get('Section1','supplierName'))4 From the list, the random.choice will execute to pick the data. vendorCodes, supplierName = random.choice(vendorCodes), random.choice(supplierName) I also have a function that will write it in the .csv file. fmiwriter.writerow([poNumber] + [vendorCodes] + [supplierName]) Well the problem is the output is incorrect. It should match from the list, if the random choices from the vendorCodes is a then the supplierName should be Test 1. Here is the incorrect output below: 588636,a,Test 3 332790,c,Test 2 810055,d,Test 4 655819,a,Test 3 159163,e,Test 1 The expected output should be like this: 588636,a,Test 1 332790,c,Test 3 810055,d,Test 4 655819,a,Test 1 159163,e,Test 5
has title: Random choice from two match list [Python]
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52738353
type: Question

http://stackoverflow.com/q/52716164
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92408038
tagged with: python
has comment: http://stackoverflow.com/comment/92387783
downvote count: 0
answer count: 0
tagged with: pytorch
type: Question
has title: Extending the vocabulary on deployment
score: 1
tagged with: torchtext
upvote count: 1
has body: When doing training, I initialize my embedding matrix, using the pretrained embeddings picked for words in training set vocabulary. import torchtext as tt contexts = tt.data.Field(lower=True, sequential=True, tokenize=tokenizer, use_vocab=True) contexts.build_vocab(data, vectors="fasttext.en.300d", vectors_cache=config["vectors_cache"]) In my model I pass contexts.vocab as parameter and initialize embeddings: embedding_dim = vocab.vectors.shape[1] self.embeddings = nn.Embedding(len(vocab), embedding_dim) self.embeddings.weight.data.copy_(vocab.vectors) self.embeddings.weight.requires_grad=False I train my model and during training I save its 'best' state via torch.save(model, f). Then I want to test/create demo for model in separate file for evaluation. I load the model via torch.load. How do I extend the embedding matrix to contain test vocabulary? I tried to replace embedding matrix # data is TabularDataset with test data contexts.build_vocab(data, vectors="fasttext.en.300d", vectors_cache=config["vectors_cache"]) model.embeddings = torch.nn.Embedding(len(contexts.vocab), contexts.vocab.vectors.shape[1]) model.embeddings.weight.data.copy_(contexts.vocab.vectors) model.embeddings.weight.requires_grad = False But the results are terrible (almost 0 accuracy). Model was doing good during training. What is the 'correct way' of doing this?

http://stackoverflow.com/q/52646902
linked to: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/92225978
possible better answer: http://stackoverflow.com/a/52647044
linked to: http://stackoverflow.com/q/5445970
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92225885
has comment: http://stackoverflow.com/comment/92225679
has comment: http://stackoverflow.com/comment/92226200
score: -1
has comment: http://stackoverflow.com/comment/92225985
answer count: 2
accepted answer: http://stackoverflow.com/a/52647029
has comment: http://stackoverflow.com/comment/92225793
has title: Access variables through their name as string in Python
upvote count: 0
linked to: http://stackoverflow.com/q/19122345
linked to: http://stackoverflow.com/q/28376538
has body: I would like to run a function with a list parameter : param = ['a', 'b', 'c'] myFunction(param) But a, b and c must be dynamic so I would like to remove the quotes to get this : param = [a, b, c] myFunction(param) How can I do that ? PS : I tried the solutions of this question but it didn't work Removing quotation marks from list items
has answer: http://stackoverflow.com/a/52647044
duplicate of: http://stackoverflow.com/q/47496415
favorite count: 0
has answer: http://stackoverflow.com/a/52647029
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92225909

http://stackoverflow.com/a/52714038
has body: There are a new RegEx \(\d\)[^(]+ \(\d\) match any string like (1) (2) (3) ... [^(]+ match one or more char and stop matching when found ( test on : on Regex101 But i wonder if you have a special example like (4) The Governor-General may arrange\n with the Chief Minister of the Austr ... (2) (3). \nNorthern Territory \n. It is a sentence from (4) to (2). Because my regex can not match this type of sentence.
answers question: http://stackoverflow.com/q/52700246
score: 0
type: Answer

http://stackoverflow.com/comment/92389104
comment on: http://stackoverflow.com/a/52712071
type: AnswerComment
score: 0
type: Comment
has text: MCO is correct. I try to avoid being recognized as a bot by a website. It disables the password login when I launch the chrome browser using selenium.

http://stackoverflow.com/comment/101955892
type: AnswerComment
has text: @TPPZ It's the sample spacing (see the rfftfreq documentation at https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftfreq.html). Generally, the sample spacing is an input or control parameter when the data was generated (or retrieved). The alternative, where the data is event driven with non constant sample intervals, can be Fourier transformed as a sum. The fast Fourier transform (FFT) assumes a constant sampling interval.
type: Comment
comment on: http://stackoverflow.com/a/52691914
score: 0

http://stackoverflow.com/comment/92396868
has text: Comment on the input. Buys and Sells can be anywhere. We're only interested in the Buy-Sell-Buy-Sell-Buy-Sell-etc... sequences without skipping any viable combinations. This means a lot of Buys and Sells which don't match this sequence can be ignored. I'm confused about the `TypingError` you get, can't see where it could happen.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52732624

http://stackoverflow.com/comment/92314849
comment on: http://stackoverflow.com/a/52692092
type: Comment
has text: I just read somewhere that matrices with more columns than rows must have linearly dependent columns, is this true?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52607616
type: AcceptedAnswer
has body: Scale your "run" process type down to 0 with heroku ps:scale run=0. Thern, make sure you can run it in a one-off dyno, e.g. with heroku run python src/main.py. Then in Heroku Scheduler configure the exact same command that you used to run it in a one-off dyno, and configure your required frequency (i.e. "Hourly").
downvote count: 0
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52607081
answers question: http://stackoverflow.com/q/52607081

http://stackoverflow.com/q/52728609
score: 6
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/37105350
downvote count: 0
has title: Pyinstaller generated exe doesn't work properly
favorite count: 0
tagged with: python-3.x
has body: I'm trying to package a python program/script (pastebin link) I wrote which includes a GUI using the tkinter module. I decided to use Pyinstaller and according to them it supports Python 3.7. Currently, trying to run pyinstaller seems to generate no issues when actually packaging. It is after when I try to run the executable that it fails. One I generate a one file variant of the executable, it simply opens a command prompt and hangs. When I do the non one file command, it opens and closes immediately, but gives an error output which I can't see due to how quick it closes. I opened up the executable directly in the cmd to get around that, and it gives me this error: C:\Users\mqian\Desktop\CGIProject\autoprimercode\windowsversion\build\windowsaut oprimer>windowsautoprimer.exe Error loading Python DLL 'C:\Users\mqian\Desktop\CGIProject\autoprimercode\windo wsversion\build\windowsautoprimer\python37.dll'. LoadLibrary: The specified module could not be found. I don't know if it's supposed to be looking for the python37.dll in this folder, but nevertheless, I had the bright idea to copy the dll from the python directory into the specified one by the trace (obviously it shouldn't have to be like that). And now the error I get is this: C:\Users\mqian\Desktop\CGIProject\autoprimercode\windowsversion\build\windowsaut oprimer>windowsautoprimer.exe Traceback (most recent call last): File "site-packages\PyInstaller\loader\rthooks\pyi_rth__tkinter.py", line 28, in <module> FileNotFoundError: Tcl data directory "C:\Users\mqian\Desktop\CGIProject\autopri mercode\windowsversion\build\windowsautoprimer\tcl" not found. [6600] Failed to execute script pyi_rth__tkinter An endless amount of googling hasn't yielded anything concrete. Here are some relevant links that I thought might help. https://github.com/pyinstaller/pyinstaller/issues/2149 https://www.xoolive.org/2015/09/09/issues-on-loading-dlls-with-pyinstaller.html PyInstaller: "No module named Tkinter" https://github.com/pyinstall…
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
upvote count: 6
linked to: http://stackoverflow.com/q/25194463
has answer: http://stackoverflow.com/a/54119819
has answer: http://stackoverflow.com/a/63721068
tagged with: tkinter

http://stackoverflow.com/comment/92147546
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52606420
has text: I changed the variables, could you take a look at it, as it is now, because this is how I coded it until now
type: Comment

http://stackoverflow.com/comment/92306904
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52689954
score: 0
has text: I have not heard about them, i should point out that I am a novice programmer.

http://stackoverflow.com/comment/92292784
type: Comment
score: 1
has text: @Ferreroire, you can accept the answer along with upvote if you feel that solves your requirement that way it will be removed from un-answered queue.
comment on: http://stackoverflow.com/q/52681747
type: QuestionComment

http://stackoverflow.com/comment/92375078
type: Comment
type: QuestionComment
has text: @J.Doe yes they are: "A lookbehind can match a variable-length string." https://pypi.org/project/regex/
score: 1
comment on: http://stackoverflow.com/q/52724641

http://stackoverflow.com/comment/92287770
type: QuestionComment
type: Comment
has text: Are the names of children unique? That is, a single parent can only have 1 child of each `(name, surname)`? I'm just trying to see how can we solve this without matching the whole sequence of children and incurring `O(n^2)` cost.
comment on: http://stackoverflow.com/q/52679355
score: 0

http://stackoverflow.com/a/52667504
upvote count: 3
answers question: http://stackoverflow.com/q/52667206
score: 3
downvote count: 0
has body: ORDER BY clause goes after the WHERE clause, so your SQL query would look something like this: SELECT seq_no, step_name, date FROM TR INNER JOIN TS ON TR.tr_OID = TS.tr_OI INNER JOIN ST ON TS.st_OID = STP.st_OID WHERE faci_OID = '0x16C0A' AND TR.tr_id = (???) ORDER BY seq_no ASC; You can find more info here: https://www.techonthenet.com/oracle/order_by.php Including it in Python is a different question. I hope I helped!
type: Answer

http://stackoverflow.com/comment/92304990
comment on: http://stackoverflow.com/a/52688976
score: 0
type: AnswerComment
has text: first column is of string type other columns are either 0 or 1.in this scenario its failing
type: Comment

http://stackoverflow.com/a/52620324
answers question: http://stackoverflow.com/q/52620140
type: Answer
score: 0
has body: I took the approach of trying to gobble up the numbers, including any comma or period by treating them as just another pseudo-digit: &gt;&gt;&gt; input="$3,100 per box, $3,000.00 per full box" &gt;&gt;&gt; box = r"\$([\d,\.]+)+\s+per\s?(?:full)?\s?box" &gt;&gt;&gt; boxs = re.findall(box, input, re.I) &gt;&gt;&gt; boxs ['3,100', '3,000.00']

http://stackoverflow.com/a/52670447
type: Answer
has body: Something like this maybe, concatenating 2 lists: from random import randint my_list = [randint(0,50) for i in range(5)] + [randint(0,12) for i in range(2)]
answers question: http://stackoverflow.com/q/52670383
has comment: http://stackoverflow.com/comment/92270664
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/q/52736033
tagged with: python
tagged with: cad
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52897940
linked to: http://stackoverflow.com/q/17399029
has title: Troubles Installing gdsCAD
has answer: http://stackoverflow.com/a/67832402
has body: I tried to install gdsCAD using the anaconda prompt : https://pypi.org/project/gdsCAD/ But I got the error: Collecting gdsCAD Using cached https://files.pythonhosted.org/packages/d0/54/60b48ee74d5ba364c4aaaf6a73e0d47274a501aafd3d64b04ce7b03b40f9/gdsCAD-0.4.5.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\EPFL\AppData\Local\Temp\pip-install-59twocd7\gdsCAD\setup.py", line 4, in &lt;module&gt; from git_version import sdist, get_version File "C:\Users\EPFL\AppData\Local\Temp\pip-install-59twocd7\gdsCAD\git_version.py", line 107 print get_version() ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\EPFL\AppData\Local\Temp\pip-install-59twocd7\gdsCAD\
type: UnansweredQuestion

http://stackoverflow.com/comment/92405017
type: QuestionComment
has text: Use *edit* option to update code in your question and share additional code trials - no need to add comments for that
score: 0
comment on: http://stackoverflow.com/q/52738492
type: Comment

http://stackoverflow.com/a/52685835
accepted answer of: http://stackoverflow.com/q/52685016
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92315770
has comment: http://stackoverflow.com/comment/92313222
has comment: http://stackoverflow.com/comment/92315080
answers question: http://stackoverflow.com/q/52685016
has body: Create a Named System DSN Go to ODBC Admin (make sure its the 64-bit one) Click on System DSN Create named DSN that points to 'C:\Users\jgp22\Documents\Database11.accdb' in this example lets use myDsn Use the connection string DSN=myDsn where myDsn is the name you gave in step 3. Don't worry about the driver info or path. All of that is stored with the DSN record on the system. ODBC Data Source Administrator Paths To setup DSN for 32-bit application you must use: %WINDIR%\SysWOW64\odbcad32.exe and for 64-bit application you must use: %WINDIR%\System32\odbcad32.exe From https://robertoschiabel.wordpress.com/2008/02/28/windows-x64-32bit-odbc-vs-64bit-odbc/amp/ Install the 64-bit Access DB Driver The driver for accessing accdb files might not be available on your system. In that case, you are going to need to install the driver from Microsft. The accdb driver is available for download from Microsoft here: https://microsoft.com/en-US/download/details.aspx?id=13255 Use 32-bit Python (if Access DB driver isn't available in 64-bit) Another alternative if you have the 32-bit accdb ODBC driver already installed on your system is to use the 32-bit version of Python. An example of this type of environment might be if you had a 32-bit version of Office installed already. Install the 32-bit version of Windows Python 3.7.0 from: https://www.python.org/ftp/python/3.7.0/python-3.7.0.exe When using the 32-bit version of python, you should access the DSNs under the 32-bit ODBC Data Source Administrator. Connect to the Named DSN import pyodbc conn = pyodbc.connect(r'DSN=myDsn')
has comment: http://stackoverflow.com/comment/92314915
type: Answer
has comment: http://stackoverflow.com/comment/92315141
has comment: http://stackoverflow.com/comment/92315847
has comment: http://stackoverflow.com/comment/92315453
has comment: http://stackoverflow.com/comment/92309864
has comment: http://stackoverflow.com/comment/92315059
has comment: http://stackoverflow.com/comment/92316209
has comment: http://stackoverflow.com/comment/92316122
has comment: http://stackoverflow.com/comment/92315806
has comment: http://stackoverflow.com/comment/92315755
has comment: http://stackoverflow.com/comment/92316152
score: 0

http://stackoverflow.com/a/52636318
score: 0
has comment: http://stackoverflow.com/comment/92205765
type: Answer
has comment: http://stackoverflow.com/comment/92205782
answers question: http://stackoverflow.com/q/52636215
has body: def code_one(d, f): while True: answer = input('Enter a number between %d and %d: ' % (d, f)) try: answer = int(answer) except ValueError: print('%s is not a number. Please try again.' % answer) continue if d &lt;= answer &lt;= f: return answer else: print('%d is out of range. Please try again.' % answer)
has comment: http://stackoverflow.com/comment/92205814

http://stackoverflow.com/q/52613220
type: UnansweredQuestion
tagged with: django
has body: We are dealing with an extremely (over several minutes) long-running Django orm keyword text query that is causing timeouts. For reasons we've yet to diagnose, when a keyword search is made on our postgres db containing over 1 million text records, the timeout occurs despite having implemented what we believe is the recommended approach to improving performance in such as scenario (e.g GIN indexes and to_tsvectors). There are probably many stones yet unturned, but as a temporary fix, initial Googling points to a solution to manage/stop the hanging query using the multiprocessing module. For example: import multiprocessing import time def run_problem_db_query(textFileSearchParameter, returned_statements): # this is the db query that hangs..... retrieved_text_files = statements.extra(where=["textfiles_tsv @@ plainto_tsquery(%s)"], params=[textFileSearchParameter]) return retrieved_text_files retrieved_text_files = None p = multiprocessing.Process(target=run_problem_db_query, name="run_problem_db_query", args=(textSearch, retrieved_text_files)) p.start() time.sleep(10) p.terminate() p.join() Even though a few blogs and SO posts have recommended a version of this approach, what are the potential problems (if any)? Ultimately, we want to fix the query of course and any potential issues with the db itself, but aside from consuming a potentially-large memory footprint (as mentioned here), what else are the potential pitfalls of such an approach?
linked to: http://stackoverflow.com/q/20055498
linked to: http://stackoverflow.com/q/3044580
has answer: http://stackoverflow.com/a/52613461
tagged with: django-models
tagged with: python-multiprocessing
type: Question
answer count: 2
has title: Understanding implications of using multiprocessing to manage long-running db queries
has answer: http://stackoverflow.com/a/52616665
tagged with: postgresql
score: 0
tagged with: python

http://stackoverflow.com/q/52686009
score: 1
favorite count: 0
type: Question
has body: The code below changes the color of the interface if it is Qwidget type. Can I change the interface color if it is Qmainwidow? Thanks for the help import sys from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout) # class Wind(QMainWindow): # this what i need class Wind(QWidget): def __init__(self): #__init__ method super(Wind, self).__init__() self.scaleFactor = 0.0 self.widget = QWidget(self) layout = QVBoxLayout(self) layout.addWidget(self.widget) self.widget.setStyleSheet(""" .QWidget { background-color: rgb(0, 200, 0); } """) self.setWindowTitle("first-window") self.resize(500, 400) if __name__ == '__main__': app = QApplication(sys.argv) imageViewer = Wind() imageViewer.show() sys.exit(app.exec_())
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/52686087
tagged with: pyqt5
upvote count: 1
has title: Change the color of the main interface with the python library PyQt5
tagged with: qtstylesheets
has answer: http://stackoverflow.com/a/52686087
tagged with: pyqt
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/92328290
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52699598
has text: Does your initial model have one output layer?
score: 0

http://stackoverflow.com/q/52693311
tagged with: python
tagged with: dictionary
answer count: 4
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52693367
linked to: http://stackoverflow.com/q/5946236
tagged with: performance
upvote count: 3
has answer: http://stackoverflow.com/a/52693394
duplicate of: http://stackoverflow.com/q/5946236
type: Question
has body: I have the following list of dictionaries in Python3.x: list_of_dictionaries = [{0:3523, 1:3524, 2:3540, 4:3541, 5:3542}, {0:7245, 1:7246, 2:7247, 3:7248, 5:7249, 6:7250}, {1:20898, 2:20899, 3:20900, 4:20901, 5:20902}] In this case, it's a single list with three dictionaries. I would like to efficiently merge this into a single dictionary with lists as values; here is the correct answer: correct = {0:[3523, 7245], 1:[3524, 7246, 20898], 2:[3540, 7247, 20899], 3:[7248, 20900], 4:[3541, 20901], 5:[3542, 7249, 20902], 6:[7250]} My first thought was a list comprehension like this: dict(pair for dictionary in list_of_dictionaries for pair in dictionary.items()) But this is wrong, as it doesn't include lists of values: {0: 7245, 1: 20898, 2: 20899, 4: 20901, 5: 20902, 3: 20900, 6: 7250} I'm also worried about how to efficiently as possible create value lists. It may not scale to large lists/large dictionaries either. How could I accomplish this?
tagged with: dictionary-comprehension
downvote count: 0
accepted answer: http://stackoverflow.com/a/52693367
has answer: http://stackoverflow.com/a/52693411
favorite count: 0
has answer: http://stackoverflow.com/a/52693785
tagged with: python-3.x
has title: How to merge a list of multiple dictionaries into a dictionary of lists?
possible better answer: http://stackoverflow.com/a/52693411

http://stackoverflow.com/a/52681308
type: Answer
has comment: http://stackoverflow.com/comment/92291177
accepted answer of: http://stackoverflow.com/q/52681186
has comment: http://stackoverflow.com/comment/92291235
answers question: http://stackoverflow.com/q/52681186
upvote count: 1
has comment: http://stackoverflow.com/comment/92291226
has body: First, convert the string to datetime datatype using to_datetime and parameter yearfirst=True then use strftime("%Y-%m-%d") as: pd.to_datetime('18-09-14',yearfirst=True).strftime("%Y-%m-%d") '2018-09-14' Or if it is a dataframe then: pd.to_datetime(df[0],yearfirst=True).dt.strftime("%Y-%m-%d") 0 2018-09-14 1 2018-09-17 2 2018-09-18 Name: 0, dtype: object
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92291066

http://stackoverflow.com/comment/92378216
comment on: http://stackoverflow.com/a/52720802
type: AnswerComment
has text: @Jamin my code works fine on windows when it comes to keeping the overrideredirect working. I will see what I can do about the Icon and linux option.
score: 0
type: Comment

http://stackoverflow.com/q/52712821
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/92351566
has answer: http://stackoverflow.com/a/52723195
score: 1
upvote count: 1
has title: Printing Curve Fit Function
has body: I have been struggling to find a way to get the determined parameters for the curve fit function below to print. The graph properly matches my data, but I can't figure out how to get the equation it produced. Any help would be appreciated! import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit x_data = [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] y_data = [.99, 1, .98, .93, .85, .77, .67, .56, .46, .36, .27, .19, .12, .07, .03, .01, 0, .01, .05, .09, .16, .24, .33, .44, .55, .65, .76, .85, .93, .98, 1] x_val = np.array(x_data) y_val = np.array(y_data) def fitFunc(x, a, b, c, d): return a * np.sin((2* np.pi / b) * x - c) + d print(a, b, c, d) plt.plot(x_val, y_val, marker='.', markersize=0, linewidth='0.5', color='green') popt, pcov = curve_fit(fitFunc, x_val, y_val) plt.plot(x_val, fitFunc(x_val, *popt), color='orange', linestyle='--')
type: Question
tagged with: numpy
tagged with: printing
tagged with: trigonometry
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92369736
type: UnansweredQuestion

http://stackoverflow.com/q/52745442
tagged with: python
has answer: http://stackoverflow.com/a/52745894
accepted answer: http://stackoverflow.com/a/52745894
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92416267
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/92415926
score: 0
tagged with: pyqt
has body: I am trying to create a PyQt5.QtWidgets.QWidget derived widget, whilst at the same time inherit from another base class, Base. Inheriting from Base causes an error when calling the QWidget constructor, saying I never provided the arguments which Base requires. This is how I attempt to call the QWidget and Base constructors: class Deriv(QtWidgets.QWidget, Base): def __init__(self): QtWidgets.QWidget.__init__(self) Base.__init__(self, "hello world") The error I'm getting says: QtWidgets.QWidget.__init__(self) TypeError: __init__() missing 1 required positional argument: 'id' Is it possible to inherit from both QWidget and Base, and if so, how do I call their respective constructors correctly? Here is an exemplar app which reproduces the error I am experiencing: #!/usr/bin/env python3 import sys from PyQt5 import QtWidgets class Base(object): def __init__(self, id): self.id = id class Deriv(QtWidgets.QWidget, Base): def __init__(self): QtWidgets.QWidget.__init__(self) Base.__init__(self, "hello world") self.show() def main(): app = QtWidgets.QApplication(sys.argv) d = Deriv() sys.exit(app.exec_()) if __name__ == '__main__': main() Here is the traceback: Traceback (most recent call last): File "./test.py", line 22, in &lt;module&gt; main() File "./test.py", line 18, in main d = Deriv() File "./test.py", line 11, in __init__ QtWidgets.QWidget.__init__(self) TypeError: __init__() missing 1 required positional argument: 'id' Note that if I only inherit from QWidget (so just remove everything referring to Base), then the code works class Deriv(QtWidgets.QWidget): def __init__(self): QtWidgets.QWidget.__init__(self) self.show()
answer count: 1
tagged with: multiple-inheritance
has comment: http://stackoverflow.com/comment/92416450
has title: Multiply inherit from QWidget and another base class?
has comment: http://stackoverflow.com/comment/92416501
has comment: http://stackoverflow.com/comment/92415775
has comment: http://stackoverflow.com/comment/92415859

http://stackoverflow.com/comment/92256673
type: Comment
score: 0
has text: Thanks for sharing :)
type: AnswerComment
comment on: http://stackoverflow.com/a/52642352

http://stackoverflow.com/comment/92346980
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52710315
has text: @G_M, sorry, I corrected the question, it's for Python 3.
type: Comment

http://stackoverflow.com/a/52642456
has comment: http://stackoverflow.com/comment/92217366
score: 0
has comment: http://stackoverflow.com/comment/92217483
has body: Yes, classes are objects too, so you can set attributes, like you do in regular objects. However, it's Child.name, not Child().name. Child() creates an instance, and assigns name to that, instead of the class.
answers question: http://stackoverflow.com/q/52642360
type: Answer

http://stackoverflow.com/comment/92351936
has text: What is the error? Have you tried testing with echo=True on your `engine` to see if there is a syntax error in the sql?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52712726
score: 0

http://stackoverflow.com/comment/92173130
score: 0
type: AnswerComment
type: Comment
has text: @pygo I have added the code I use to generate the sample list
comment on: http://stackoverflow.com/a/52619416

http://stackoverflow.com/a/52599687
answers question: http://stackoverflow.com/q/52598998
score: 0
has comment: http://stackoverflow.com/comment/92134033
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92133956
has body: You can accomplish that effect by using a series of lines with differing widths: from random import random from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Color, Line MAX_WIDTH = 6.0 MAX_SEGMENTS = 10 class BladeEfx(Widget): def __init__(self, **kwargs): super(BladeEfx, self).__init__(**kwargs) self.lines = [] self.width_delta = (MAX_WIDTH - 1.0)/ (MAX_SEGMENTS - 2) self.color = None def on_touch_down(self, touch): self.color = (random(), 1, 1) line = Line(points=(touch.x, touch.y), cap='round', joint='round', cap_precision=5) self.lines.append(line) def on_touch_up(self, touch): self.canvas.clear() self.lines = [] def on_touch_move(self, touch): line = Line(points=(touch.x, touch.y), cap='round', joint='round', cap_precision=5) self.lines[-1].points += [touch.x, touch.y] # add second point to the previous line self.lines.append(line) # add a new line (for now, it has just one point) self.lines = self.lines[-MAX_SEGMENTS:] # limit number of lines to MAX_SEGMENTS self.canvas.clear() self.canvas.add(Color(*self.color, mode='hsv')) width = 1.0 for line in self.lines: line.width = width width += self.width_delta self.canvas.add(line) # add a line to the Canvas with the specified width class BladeApp(App): def build(self): parent = Widget() self.bldEfx = BladeEfx() parent.add_widget(self.bldEfx) return parent if __name__ == '__main__': BladeApp().run()
type: Answer
accepted answer of: http://stackoverflow.com/q/52598998

http://stackoverflow.com/comment/92333707
comment on: http://stackoverflow.com/q/52701739
score: 0
has text: @acgtyrant I can assure you that no other solution will be as fast as hitting ‹Ctrl›-‹D›, followed by ‹up-arrow› and ‹return›. Because that’s all it takes to restart Python. — Furthermore, if you need to clear your REPL very often this suggests that you’re doing something you’re not supposed to do: write reproducible scripts with functions etc. instead.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52733304
has answer: http://stackoverflow.com/a/52733356
accepted answer: http://stackoverflow.com/a/52733356
favorite count: 0
has title: change the type of the query result from DB2 via python
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
tagged with: db2
has body: I'm not able to use all the lines from my query output. If I run the 1st code: #1st code l1 = [(1, 2, 3, 4, 'John'),(10, 20, 30, 40, 'Doe')] labels = ['A', 'B', 'C', 'D', 'E'] df = pd.DataFrame.from_records(l1, columns=labels) print(df) The output is: A B C D E 0 1 2 3 4 John 1 10 20 30 40 Doe If I run the 2nd code: #2nd code def c2nd(): conn = ibm_db.pconnect("db login details;", "", "") sql = "SELECT * FROM METADATA.TBD_201811_TMP_AT" stmt = ibm_db.exec_immediate(conn, sql) tuple = ibm_db.fetch_tuple(stmt) while tuple != False: l = list(tuple) return l tuple = ibm_db.fetch_tuple(stmt) print(c2nd()) the output is ONLY one line instead of two: [10,20,30,40,'Doe'] The problem is, if I try to write the result into the .csv file, I always receive only the last line of the result. How can I list out and use all (in my case both) lines of my output? ps: just FYI, the result can contain 1000 or 100 000 lines too
upvote count: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/a/52692813
accepted answer of: http://stackoverflow.com/q/52692643
has body: Here are the problems: You need to pass in arguments in a function. You need to check every letter in the word instead of checking and changing the entire word. What I did was make a new variable and made changes to that variable and then returned this variable. alphabet = "abcdefghijklmnopqrstuvwxyzæø˚a ?" my_list = list(alphabet) n = input() def textis(n, my_list): new = '' for letter in n: if letter in my_list: new += letter else: new += "?" return new print(textis(n, my_list))
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52692643

http://stackoverflow.com/q/52657223
has answer: http://stackoverflow.com/a/74054984
has title: TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced
accepted answer: http://stackoverflow.com/a/52657344
has answer: http://stackoverflow.com/a/74438390
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/71226861
linked to: http://stackoverflow.com/q/36000993
possible better answer: http://stackoverflow.com/a/71226861
type: Question
tagged with: numpy
score: 105
linked to: http://stackoverflow.com/q/50588601
tagged with: missing-data
downvote count: 0
upvote count: 105
tagged with: numpy-ufunc
has answer: http://stackoverflow.com/a/52657344
has comment: http://stackoverflow.com/comment/126418282
has answer: http://stackoverflow.com/a/63850268
answer count: 7
tagged with: python
has comment: http://stackoverflow.com/comment/92245299
has body: I am trying to convert a CSV into numpy array. In the numpy array, I am replacing few elements with NaN. Then, I wanted to find the indices of the NaN elements in the numpy array. The code is: import pandas as pd import matplotlib.pyplot as plyt import numpy as np filename = 'wether.csv' df = pd.read_csv(filename,header = None ) list = df.values.tolist() labels = list[0] wether_list = list[1:] year = [] month = [] day = [] max_temp = [] for i in wether_list: year.append(i[1]) month.append(i[2]) day.append(i[3]) max_temp.append(i[5]) mid = len(max_temp) // 2 temps = np.array(max_temp[mid:]) temps[np.where(np.array(temps) == -99.9)] = np.nan plyt.plot(temps,marker = '.',color = 'black',linestyle = 'none') # plyt.show() print(np.where(np.isnan(temps))[0]) # print(len(pd.isnull(np.array(temps)))) When I execute this, I am getting a warning and an error. The warning is: wether.py:26: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison temps[np.where(np.array(temps) == -99.9)] = np.nan The error is: Traceback (most recent call last): File "wether.py", line 30, in <module> print(np.where(np.isnan(temps))[0]) TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' This is a part of the dataset which I am using: 83168,2014,9,7,0.00000,89.00000,78.00000, 83.50000 83168,2014,9,22,1.62000,90.00000,72.00000, 81.00000 83168,2014,9,23,0.50000,87.00000,74.00000, 80.50000 83168,2014,9,24,0.35000,82.00000,73.00000, 77.50000 83168,2014,9,25,0.60000,85.00000,75.00000, 80.00000 83168,2014,9,26,0.76000,89.00000,77.00000, 83.00000 83168,2014,9,27,0.00000,89.00000,79.00000, 84.00000 83168,2014,9,28,0.00000,90.00000,81.00000, 85.50000 83168,2014,9,29,0.00000,90.00000,79.00000, 84.50000 83168,2014,9,30,0.50000,89.00000,75.00000, 82.00000 83168,2014,10,1,0.02000,91.00000,75.00000, 83.00000 83168,2014,10,2,0.03000…
tagged with: nan
favorite count: 0
has comment: http://stackoverflow.com/comment/92245761
has comment: http://stackoverflow.com/comment/92245248
has answer: http://stackoverflow.com/a/67629235
has answer: http://stackoverflow.com/a/71489743

http://stackoverflow.com/q/52645495
tagged with: python
has title: add trailing 0's to a string in a df.Column dependent on length
has body: Looking for a sort of chain method to apply to a df. consider the following DF. Store 1 33 455 what I'm trying to do is ascertain the length and append a 0 based on the length. I've tried a simple for loop which i thought may work for s in df.Store: if s.str.len() == 3: "0" + s however this doesn't work. I've also tried slicing the DF and each variable one by one if df.Store == df[df['Store'].str.len() == 1]: "0" + df.Store but neither work and just return a blank output. I'm working with an object dtype. desired output: Store 0001 0033 0455
has answer: http://stackoverflow.com/a/52645511
downvote count: 0
accepted answer: http://stackoverflow.com/a/52645511
tagged with: pandas
score: 2
type: AnsweredQuestion
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/52645525
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/52645525

http://stackoverflow.com/comment/92347950
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52710636
has text: Thank you! And Welcome!

http://stackoverflow.com/a/52661108
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92252537
has body: It's actually surpising that this code works. sns.catplot() is designed to plot onto a FacetGrid and is not meant to be used the way you are using it. I think you should use sns.boxplot() directly: fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) sns.boxplot(x='not.fully.paid', y='int.rate', kind='box', data=loans, ax=ax1) sns.boxplot(x='not.fully.paid', y='fico', kind='box', data=loans, ax=ax2) If you really wanted to use catplot you would have to transform your dataframe so that all y-values would be in a single column, with an additional category column indicating the type of value (int.rate/fico) and then call: sns.catplot(x='not.fully.paid', y='&lt;values column&gt;', col='&lt;category column&gt;', kind='box', data=loans) and seaborn would automatically the correct subplots to accommodate the number of unique categories in your category column.
has comment: http://stackoverflow.com/comment/92252624
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52659771
downvote count: 0
answers question: http://stackoverflow.com/q/52659771
has comment: http://stackoverflow.com/comment/92252654
score: 4

http://stackoverflow.com/q/52634970
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/92203709
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/92203956
has answer: http://stackoverflow.com/a/52635417
accepted answer: http://stackoverflow.com/a/52635417
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52636542
answer count: 2
has body: Is there a shorter way in python 3 to write: if a in ('n', 'm') or b in ('n', 'm'): print(a) I have been searching but did't find a shorter way. I am try to type this line shorter: if color1 in ('blue', 'red') or color2 in ('blue', 'red'):
has comment: http://stackoverflow.com/comment/92203598
favorite count: 0
has title: Is there a shorter way to ask if 2 variables are a value?
possible better answer: http://stackoverflow.com/a/52636542
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92206244

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

http://stackoverflow.com/q/52632791
has comment: http://stackoverflow.com/comment/92199734
has comment: http://stackoverflow.com/comment/92198945
favorite count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/92199084
tagged with: python
accepted answer: http://stackoverflow.com/a/52633000
has title: Multiprocessing not parallelizing
type: AnsweredQuestion
has body: I have a function that can be run in parallel, however, as I try running it, it appears that the function is being called serially. import multiprocessing as mp def function_to_be_parallelized(x,y,z): #compute_array takes 1-5 minutes computation to depending on x,y,z computed_array=compute_array(x,y,z) print ("running with parameters"+str(x*y*z)) return computed_array def run(xs,ys,zs): pool = mp.Pool(processes=4) all_outputs = [pool.apply(function_to_be_parallelized, args=(x,y,z)) for x in xs for y in ys for z in zs] What I find is that the print statements are printed one at a time, and each is only printed once the previous process is finished, I'm running this on a machine with 4 cores. Is this because the processes in the inner function each occupy more than 2 cores (so that it cannot be parallelized)? Or is there another reason?
has comment: http://stackoverflow.com/comment/92198993
has comment: http://stackoverflow.com/comment/92199543
tagged with: multiprocessing
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/92199836
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/92199596
has answer: http://stackoverflow.com/a/52633000
possible better answer: http://stackoverflow.com/a/52632838
has answer: http://stackoverflow.com/a/52632838

http://stackoverflow.com/comment/92217431
score: 1
type: AnswerComment
type: Comment
has text: *new list = the original* will only copy the reference, not the list.
comment on: http://stackoverflow.com/a/52642302

beautifulsoup
tags question: http://stackoverflow.com/q/52695214
tags question: http://stackoverflow.com/q/52681511
tags question: http://stackoverflow.com/q/52608956
tags question: http://stackoverflow.com/q/52636648
tags question: http://stackoverflow.com/q/52593716
tags question: http://stackoverflow.com/q/52635163
tags question: http://stackoverflow.com/q/52667008
tags question: http://stackoverflow.com/q/52591299
tags question: http://stackoverflow.com/q/52721083
tags question: http://stackoverflow.com/q/52690615
tags question: http://stackoverflow.com/q/52706259
tags question: http://stackoverflow.com/q/52686268
tags question: http://stackoverflow.com/q/52685458
tags question: http://stackoverflow.com/q/52723591
tags question: http://stackoverflow.com/q/52624286
tags question: http://stackoverflow.com/q/52670685
tags question: http://stackoverflow.com/q/52684555
tags question: http://stackoverflow.com/q/52717750
tags question: http://stackoverflow.com/q/52678336
tags question: http://stackoverflow.com/q/52690022
tags question: http://stackoverflow.com/q/52605370
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/52659782
tags question: http://stackoverflow.com/q/52622909
tags question: http://stackoverflow.com/q/52619754
tags question: http://stackoverflow.com/q/52659390
tags question: http://stackoverflow.com/q/52597445
tags question: http://stackoverflow.com/q/52687372
tags question: http://stackoverflow.com/q/52703476
tags question: http://stackoverflow.com/q/52685078
tags question: http://stackoverflow.com/q/52726555
tags question: http://stackoverflow.com/q/52591846
tags question: http://stackoverflow.com/q/52659057
tags question: http://stackoverflow.com/q/52693854
tags question: http://stackoverflow.com/q/52594179
tags question: http://stackoverflow.com/q/52664414
tags question: http://stackoverflow.com/q/52588827
tags question: http://stackoverflow.com/q/52635717
tags question: http://stackoverflow.com/q/52656353
tags question: http://stackoverflow.com/q/52629595
tags question: http://stackoverflow.com/q/52657610
tags question: http://stackoverflow.com/q/52588733
type: Tag
tags question: http://stackoverflow.com/q/52637365
tags question: http://stackoverflow.com/q/52603029
tags question: http://stackoverflow.com/q/52667677
tags question: http://stackoverflow.com/q/52715847
tags question: http://stackoverflow.com/q/52703694
tags question: http://stackoverflow.com/q/52626158
tags question: http://stackoverflow.com/q/52687155
tags question: http://stackoverflow.com/q/52670792
tags question: http://stackoverflow.com/q/52684541
tags question: http://stackoverflow.com/q/52683320
tags question: http://stackoverflow.com/q/52658754
tags question: http://stackoverflow.com/q/52594370
tags question: http://stackoverflow.com/q/52626682
tags question: http://stackoverflow.com/q/52717440
tags question: http://stackoverflow.com/q/52596492
tags question: http://stackoverflow.com/q/52737636
tags question: http://stackoverflow.com/q/52592744
tags question: http://stackoverflow.com/q/52731947
tags question: http://stackoverflow.com/q/52629888
tags question: http://stackoverflow.com/q/52641121
tags question: http://stackoverflow.com/q/52681765
tags question: http://stackoverflow.com/q/52726614
tags question: http://stackoverflow.com/q/52719131
tags question: http://stackoverflow.com/q/52728333
tags question: http://stackoverflow.com/q/52726818
tags question: http://stackoverflow.com/q/52745495
tags question: http://stackoverflow.com/q/52689171
tags question: http://stackoverflow.com/q/52730256
tags question: http://stackoverflow.com/q/52679150
tags question: http://stackoverflow.com/q/52712472
tags question: http://stackoverflow.com/q/52619669
tags question: http://stackoverflow.com/q/52707117
tags question: http://stackoverflow.com/q/52611748
tags question: http://stackoverflow.com/q/52687990
tags question: http://stackoverflow.com/q/52655532
tags question: http://stackoverflow.com/q/52642938
tags question: http://stackoverflow.com/q/52678883

http://stackoverflow.com/comment/92132870
comment on: http://stackoverflow.com/q/52599040
score: 0
has text: `data['session'] = np.where(data['day'].shift(1) > data['day'], 1, 0)` starts you off, the increment in `session` is causing me a little issue :)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/94131863
has text: Fair enough, thanks anyway!
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52729686

http://stackoverflow.com/q/52672166
tagged with: multithreading
type: Question
has comment: http://stackoverflow.com/comment/92275236
linked to: http://stackoverflow.com/q/38393269
tagged with: concurrency
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has body: I am trying to make a dictionary with dataframe as values using multiprocess module. I am using the instruction that was provided here. However,it outputs an empty dictionary. Any help is highly appreciated. def parallel_main(summary_res_all_type,st,df_x,df_y,max_number): res_all =modified_mlr.do_mlr(df_x,df_y,soil_type=st,max_namber=max_number) summary_res_all_type[st]=pd.DataFrame(index=pars_keys_all,columns=[st] ) summary_res_all_type[st]=res_all['dict_cor_par'].values() if __name__ == '__main__': manager = Manager() summary_res_all_type = manager.dict() job = [Process(target=parallel_main, args=(summary_res_all_type, i,df_x,df_y,max_number)) for i in set(df_x["soil_type"])] _ = [p.start() for p in job] _ = [p.join() for p in job] print(summary_res_all_type)
has title: Creating a dictionary with multiprocess
tagged with: parallel-processing
has answer: http://stackoverflow.com/a/52678102

http://stackoverflow.com/comment/92148860
type: QuestionComment
has text: my code is not working ..
comment on: http://stackoverflow.com/q/52607299
score: 0
type: Comment

http://stackoverflow.com/comment/92270034
has text: Disregard my comment.
type: Comment
comment on: http://stackoverflow.com/q/52669951
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92330755
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52702017
has text: `[*map(list, enumerate(word, 1))]` ?
score: 0

http://stackoverflow.com/comment/92405330
comment on: http://stackoverflow.com/q/52740339
has text: It didn't raise any error for me
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52639733
has comment: http://stackoverflow.com/comment/92221801
score: 2
has body: I'm doing my python assignments using PyCharm. I have created folders like "Assignment 01", "Assignment 02" and so on. In each of the assignment folders, I have 2 python files. "Helper.py" and "Demo.py". In "Demo.py", I have to import the Helper file. I do that using import Helper But PyCharm doesn't recognize this unless I mark the directory containing the Helper files as Sources Root. So, I marked my directory "Assignment 01" as Sources Root. All is fine. Now, I started with "Assignment 02". In "Demo.py" of "Assignment 02", I imported Helper. This imports Helper from "Assignment 01" and not "Assignment 02". Even if I mark "Assignment 02" as Sources Root, PyCharm still refers to "Helper.py" from "Assignment 01". How to make PyCharm refer to "Helper.py" in the same folder? Note: I don't want to open different Assignments as different projects. I would like to have everything as a single project. Any other suggestions, conventions, best practices are also welcome. Thanks!
has comment: http://stackoverflow.com/comment/92222345
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92221661
has answer: http://stackoverflow.com/a/52640832
has comment: http://stackoverflow.com/comment/92222583
has title: PyCharm Import files with same name in different folders
tagged with: python
type: AnsweredQuestion
tagged with: pycharm
upvote count: 2
accepted answer: http://stackoverflow.com/a/52640832
type: Question
has comment: http://stackoverflow.com/comment/92221966
has comment: http://stackoverflow.com/comment/92222223
has comment: http://stackoverflow.com/comment/92214073

javascript
tags question: http://stackoverflow.com/q/52735509
tags question: http://stackoverflow.com/q/52712850
tags question: http://stackoverflow.com/q/52634731
tags question: http://stackoverflow.com/q/52697848
tags question: http://stackoverflow.com/q/52683168
tags question: http://stackoverflow.com/q/52714632
tags question: http://stackoverflow.com/q/52681511
tags question: http://stackoverflow.com/q/52593109
tag name: javascript
tags question: http://stackoverflow.com/q/52595247
tags question: http://stackoverflow.com/q/52705784
tags question: http://stackoverflow.com/q/52657775
tags question: http://stackoverflow.com/q/52632832
tags question: http://stackoverflow.com/q/52683723
tags question: http://stackoverflow.com/q/52736004
tags question: http://stackoverflow.com/q/52698552
tags question: http://stackoverflow.com/q/52665479
tags question: http://stackoverflow.com/q/52713234
tags question: http://stackoverflow.com/q/52682600
tags question: http://stackoverflow.com/q/52677365
type: Tag
tags question: http://stackoverflow.com/q/52718057
tags question: http://stackoverflow.com/q/52725952
tags question: http://stackoverflow.com/q/52728144
tags question: http://stackoverflow.com/q/52743188
tags question: http://stackoverflow.com/q/52746470
tags question: http://stackoverflow.com/q/52592578
tags question: http://stackoverflow.com/q/52734213
tags question: http://stackoverflow.com/q/52683873
tags question: http://stackoverflow.com/q/52612667
tags question: http://stackoverflow.com/q/52693786
tags question: http://stackoverflow.com/q/52624102
tags question: http://stackoverflow.com/q/52744071

http://stackoverflow.com/a/52661260
upvote count: 0
accepted answer of: http://stackoverflow.com/q/52661069
has comment: http://stackoverflow.com/comment/92253253
answers question: http://stackoverflow.com/q/52661069
has comment: http://stackoverflow.com/comment/92253394
score: -1
has body: You can do it step by step: Replace all the vowels in the string with '' for i in s: for j in vowels: s=s.replace(j,'') Convert the string into lowercase: s=s.lower() Adding '.' in between each letters: s='.' + '.'.join(s)
type: AcceptedAnswer
downvote count: 1
type: Answer

http://stackoverflow.com/comment/92359046
score: 0
has text: What exactly are you trying to do? Find the index of a certain item in a list?
type: Comment
comment on: http://stackoverflow.com/q/52716448
type: QuestionComment

http://stackoverflow.com/a/52672007
score: 0
answers question: http://stackoverflow.com/q/52671308
has comment: http://stackoverflow.com/comment/92311485
type: Answer
has body: You can apply diff() on your Series, and then just count the number of consecutive entries where the difference is 1 and the actual value is above your cutoff. The largest count is the maximum number of consecutive values. First compute diff(): df = pd.DataFrame({"a":[1, 2, 6, 7, 8, 3, 2, 3, 6, 10, 2, 1, 0, 2]}) df['b'] = df.a.diff() df a b 0 1 NaN 1 2 1.0 2 6 4.0 3 7 1.0 4 8 1.0 5 3 -5.0 6 2 -1.0 7 3 1.0 8 6 3.0 9 10 4.0 10 2 -8.0 11 1 -1.0 12 0 -1.0 13 2 2.0 Now count consecutive sequences: above = 5 n_consec = 1 max_n_consec = 1 for a, b in df.values[1:]: if (a &gt; above) &amp; (b == 1): n_consec += 1 else: # check for new max, then start again from 1 max_n_consec = max(n_consec, max_n_consec) n_consec = 1 max_n_consec 3

http://stackoverflow.com/a/52736640
upvote count: 2
answers question: http://stackoverflow.com/q/52736571
downvote count: 0
has body: change description = models.CharField(widget = forms.Textarea, max_length = 250, required=False) to description = models.CharField(max_length = 250) widget = forms.Textarea, required=False is used in Form like: from django import forms class Desc(forms.ModelForm): description = forms.CharField(widget = forms.Textarea, max_length = 250, required=False)
type: Answer
score: 2

http://stackoverflow.com/comment/92113211
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52588733
has text: @vasdevchandrakar , the data comes from JSON, but you're requesting HTML source... What is the point? If you need data - make a request to URL with JSON, not to URL with HTML
score: 0

http://stackoverflow.com/comment/92423927
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52746410
has text: Good question. Yes, it requires objects (dataframes, etc) created in the previous code, but they're saved in the global namespace, so that does not cause problems for me. To solve my problem, I followed my own suggestion and copied the line I wanted to debug to the top of the code (i.e. line 1), and started the debug from there. Pretty easy to do as a workaround.
score: 0

http://stackoverflow.com/a/62849678
upvote count: 3
has body: This worked for me in Ubuntu 18.04 LTS, to render gym locally. But, I believe it will work even in remote Jupyter Notebook servers. First, run the following installations in Terminal: pip install gym python -m pip install pyvirtualdisplay pip3 install box2d sudo apt-get install xvfb That's just it. Use the following snippet to configure how your matplotlib should render : import matplotlib.pyplot as plt from pyvirtualdisplay import Display display = Display(visible=0, size=(1400, 900)) display.start() is_ipython = 'inline' in plt.get_backend() if is_ipython: from IPython import display plt.ion() # Load the gym environment import gym import matplotlib.pyplot as plt %matplotlib inline env = gym.make('LunarLander-v2') env.seed(23) # Let's watch how an untrained agent moves around state = env.reset() img = plt.imshow(env.render(mode='rgb_array')) for j in range(200): # action = agent.act(state) action = random.choice(range(4)) img.set_data(env.render(mode='rgb_array')) plt.axis('off') display.display(plt.gcf()) display.clear_output(wait=True) state, reward, done, _ = env.step(action) if done: break env.close()
downvote count: 0
has comment: http://stackoverflow.com/comment/127443301
answers question: http://stackoverflow.com/q/52726475
type: Answer
score: 3

http://stackoverflow.com/q/52612292
tagged with: python
tagged with: matlab
upvote count: 1
has title: Eigen Value in Python
answer count: 1
type: UnansweredQuestion
tagged with: eigenvector
downvote count: 0
score: 1
has body: I wanted to find the Eigen value of a matrix size (280*280). I done it in MATLAB by using [V D] = eig(matrix); but I wanted to convert my code in python by using d, v = np.eigh(matrix) It will provide almost same output but in python the first and the last column are of opposite sign (i.e if positive in MATLAB then negative in python) and I know that MATLAB output is correct
has answer: http://stackoverflow.com/a/52627476
favorite count: 0
type: Question

http://stackoverflow.com/a/52717840
answers question: http://stackoverflow.com/q/52717440
has body: This is because of default column width in pandas, which is 50. You can simply set it to the maximum length you expect or set it to -1 to disable column maximum width. Add the following line before writing: pd.set_option('display.max_colwidth', -1) See the link for details: https://pandas.pydata.org/pandas-docs/stable/options.html
has comment: http://stackoverflow.com/comment/92397478
score: 0
has comment: http://stackoverflow.com/comment/92391968
has comment: http://stackoverflow.com/comment/92439349
type: Answer
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92438222

http://stackoverflow.com/comment/92232438
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52650204
has text: "but it looks like there's something wrong at the calculating average part" - please make your problem statement clear. Give sample input and expected and actual result or error message you are getting. "something wrong" is not very clear
type: QuestionComment

http://stackoverflow.com/comment/92156455
has text: Do you still use `wait`? I don't get anything back when I use that
comment on: http://stackoverflow.com/a/52609404
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52743872
favorite count: 0
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/52754357
accepted answer: http://stackoverflow.com/a/52754357
has body: I have been creating a game where an image moves according to player input with Keydown and Keyup methods. I want to add boundaries so that the user cannot move the image/character out of the display (I dont want a game over kind of thing if boundary is hit, just that the image/character wont be able to move past that boundary) import pygame pygame.init()#initiate pygame black = (0,0,0) white = (255,255,255) red = (255,0,0) display_width = 1200 display_height = 800 display = pygame.display.set_mode((display_width,display_height)) characterimg_left = pygame.image.load(r'/Users/ye57324/Desktop/Make/coding/python/characterimg_left.png') characterimg_right = pygame.image.load(r'/Users/ye57324/Desktop/Make/coding/python/characterimg_right.png') characterimg = characterimg_left def soldier(x,y): display.blit(characterimg, (x,y)) x = (display_width * 0.30) y = (display_height * 0.2) pygame.display.set_caption('No U') clock = pygame.time.Clock()#game clock flip_right = False x_change = 0 y_change = 0 bg_x = 0 start = True bg = pygame.image.load(r'/Users/ye57324/Desktop/Make/coding/python/bg.png').convert() class player: def __init__(self, x, y): self.jumping = False p = player(x, y) while start: for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): start = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change += -4 if flip_right == True: characterimg = characterimg_left flip_right = False x += -150 elif event.key == pygame.K_RIGHT: x_change += 4 if flip_right == False: characterimg = characterimg_right flip_right = True x += 150 elif event.key == pygame.K_UP: y_change += -4 elif event.key == pygame.K_DOWN: y_change += 4 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: x_change += 4 elif event.key == pygame.K_RIGHT: x_change += -4 elif event.key == pygame.K_UP: y_change += 4 elif event.key == pygame.K_DOWN: y_change += -4 x += x_change y += y_change display.fill(…
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: boundary
type: Question
possible better answer: http://stackoverflow.com/a/52754694
answer count: 2
has title: Adding boundaries in Pygame with movable characters/images
has answer: http://stackoverflow.com/a/52754694
upvote count: 1

http://stackoverflow.com/comment/134320077
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52622392
has text: Using ufunc's `where` parameter directly is much more concise and usually faster. See answer by @hpaulj.
score: 0

http://stackoverflow.com/a/52708161
has comment: http://stackoverflow.com/comment/92343872
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52708019
has body: Do something like the following: import seaborn as sns import pandas as pd valor_ano = pd.DataFrame({'level_1':[1900, 2014, 2015, 2016, 2017, 2018], 'total':[0.0, 154.4, 490.9, 628.4,715.2,601.5]}) valor_ano.drop(0, axis=0, inplace=True) valor_plot = sns.barplot( data= valor_ano, x= 'level_1', y= 'total') This produces the following plot: EDIT: If you want to do it without the dataframe and just pass in the raw data you can do it with the following code. You can also just use a variable containing a list instead of hard-coding the list: valor_graph = sns.barplot( x= [2014, 2015, 2016, 2017, 2018], y= [154.4, 490.9, 628.4,715.2,601.5])
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/92344649
has comment: http://stackoverflow.com/comment/92343625
has comment: http://stackoverflow.com/comment/92343284
downvote count: 0
has comment: http://stackoverflow.com/comment/92343378
accepted answer of: http://stackoverflow.com/q/52708019

http://stackoverflow.com/q/52616341
has comment: http://stackoverflow.com/comment/93464220
favorite count: 0
has comment: http://stackoverflow.com/comment/93402658
type: UnansweredQuestion
tagged with: python
upvote count: 6
has title: Error opening TIFF in python unknown pseudo-tag
score: 6
type: Question
tagged with: tiff
has comment: http://stackoverflow.com/comment/93470565
has answer: http://stackoverflow.com/a/53570965
has body: I am trying to open a .TIFF image in python. My code is import numpy as np import matplotlib.pyplot as plt from PIL import Image photos = Image.open("haz(1,8grados).tif") photos.show() and I am getting the error TIFFSetField: tempfile.tif: Unknown pseudo-tag 65538. Can anyone help with this? I am running python 3 in Mac OS High Sierra.
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52591629
answer count: 1
downvote count: 0
score: 1
has title: Pyephem and pypredict/gpredict differences
tagged with: pyephem
favorite count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52593644
type: AnsweredQuestion
type: Question
has body: I am trying to use pyephem to predict satellite passes for a ground station. However, the results I get are quite different from the ones I get with pypredict and gpredict. Here is the code I wrote. import ephem import predict import datetime as dt def passes(station, satellite, start=None, duration=7): result = [] if start is not None: station.date = ephem.date(start) end = ephem.date(station.date + duration) while station.date &lt; end: t_aos, azr, t_max, elt, t_los, azs = station.next_pass(satellite) result.append({'aos': t_aos.datetime(), 'los': t_los.datetime()}) station.date = t_los + ephem.second return result tle = """ISS (ZARYA) 1 25544U 98067A 18274.33960752 .00001880 00000-0 36095-4 0 9991 2 25544 51.6416 209.7138 0003794 227.2741 275.6194 15.53757611135029""" station = ephem.Observer() station.lat = 20 station.long = 0 station.elev = 0 epoch = dt.datetime.utcnow() for i in passes(station, ephem.readtle(*tle.split("\n")), epoch, 1): print(i['aos'], i['los']) print("===============") p = predict.transits(tle, (station.lat, -station.long, station.elev), (epoch - dt.datetime(1970,1,1)).total_seconds()) for i in range(1, 8): transit = p.next() print(dt.datetime.utcfromtimestamp(transit.start), dt.datetime.utcfromtimestamp(transit.end)) And the results (datetime.datetime(2018, 10, 1, 17, 4, 43, 552230), datetime.datetime(2018, 10, 1, 17, 11, 12, 744164)) (datetime.datetime(2018, 10, 1, 18, 39, 4, 59194), datetime.datetime(2018, 10, 1, 18, 47, 5, 185600)) (datetime.datetime(2018, 10, 1, 20, 14, 28, 126953), datetime.datetime(2018, 10, 1, 20, 22, 3, 101339)) (datetime.datetime(2018, 10, 1, 21, 51, 6, 130556), datetime.datetime(2018, 10, 1, 21, 55, 21, 829297)) (datetime.datetime(2018, 10, 2, 16, 13, 51, 767026), datetime.datetime(2018, 10, 2, 16, 19, 13, 556850)) =============== (datetime.datetime(2018, 10, 1, 13, 43, 6, 584816), datetime.datetime(2018, 10, 1, 13, 53, 21, 721679)) (datetime.datetime(2018, 10, 1, 15, 20, 13, 473098), datetime.datetime(2018, 10, 1…
has answer: http://stackoverflow.com/a/52593644

http://stackoverflow.com/a/52654457
score: 2
upvote count: 2
has body: You can use a context manager to open and write to a new json file for each row: fieldnames = ("first_name","last_name","color") reader = csv.DictReader(csvfile, fieldnames) for row in reader: with open('%s_%s.json' % (row['first_name'], row['last_name']), 'w') as jsonfile: jsonfile.write('"first_name": "' + row['first_name'] + '",\n') jsonfile.write('"last_name": "' + row['last_name'] + '",\n') jsonfile.write('"color": "' + row['color'] + '",\n')
downvote count: 0
answers question: http://stackoverflow.com/q/52654327
type: Answer

http://stackoverflow.com/comment/92337590
score: 0
type: AnswerComment
has text: What are my alternatives?
type: Comment
comment on: http://stackoverflow.com/a/52705567

http://stackoverflow.com/comment/92310384
has text: Not work too. python3 implementing-scalar-mib-objects1.py Unhandled Error Traceback (most recent call last): --- <exception caught here> --- File "/usr/local/lib/python3.6/dist-packages/twisted/internet/base.py", line 878, in runUntilCurrent ... builtins.TypeError: getValue() got an unexpected keyword argument 'snmpEngine'
comment on: http://stackoverflow.com/a/52681737
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/61371170
score: 47
has comment: http://stackoverflow.com/comment/113246748
has comment: http://stackoverflow.com/comment/111547144
upvote count: 47
has comment: http://stackoverflow.com/comment/109257159
downvote count: 0
has comment: http://stackoverflow.com/comment/129856062
has comment: http://stackoverflow.com/comment/138046953
has comment: http://stackoverflow.com/comment/112019005
type: Answer
has comment: http://stackoverflow.com/comment/109990839
has comment: http://stackoverflow.com/comment/112028997
has comment: http://stackoverflow.com/comment/112029594
has comment: http://stackoverflow.com/comment/113246621
has comment: http://stackoverflow.com/comment/132934522
has body: Given your task your comparing 70k strings with each other using fuzz.WRatio, so your having a total of 4,900,000,000 comparisions, with each of these comparisions using the levenshtein distance inside fuzzywuzzy which is a O(N*M) operation. fuzz.WRatio is a combination of multiple different string matching ratios that have different weights. It then selects the best ratio among them. Therefore it even has to calculate the Levenshtein distance multiple times. So one goal should be to reduce the search space by excluding some possibilities using a way faster matching algorithm. Another issue is that the strings are preprocessed to remove punctuation and to lowercase the strings. While this is required for the matching (so e.g. a uppercased word becomes equal to a lowercased one) we can do this ahead of time. So we only have to preprocess the 70k strings once. I will use RapidFuzz instead of FuzzyWuzzy here, since it is quite a bit faster (I am the author). The following version performs more than 10 times as fast as your previous solution in my experiments and applies the following improvements: it preprocesses the strings ahead of time it passes a score_cutoff to extractOne so it can skip calculations where it already knows they can not reach this ratio import pandas as pd, numpy as np from rapidfuzz import process, utils org_list = df['org_name'] processed_orgs = [utils.default_process(org) for org in org_list] for (i, processed_query) in enumerate(processed_orgs): # None is skipped by extractOne, so we set the current element to None an # revert this change after the comparision processed_orgs[i] = None match = process.extractOne(processed_query, processed_orgs, processor=None, score_cutoff=93) processed_orgs[i] = processed_query if match: df.loc[i, 'fuzzy_match'] = org_list[match[2]] df.loc[i, 'fuzzy_match_score'] = match[1] Here is a list of the most relevant improvements of RapidFuzz to make it faster than FuzzyWuzzy in this example: It is implemented fully in …
answers question: http://stackoverflow.com/q/52631291
has comment: http://stackoverflow.com/comment/129856339
has comment: http://stackoverflow.com/comment/112031723
has comment: http://stackoverflow.com/comment/138035867
has comment: http://stackoverflow.com/comment/113244166
has comment: http://stackoverflow.com/comment/112019282

http://stackoverflow.com/comment/92290310
comment on: http://stackoverflow.com/q/52676110
has text: The issue is the SSL (or lack of) failing.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52595776
has comment: http://stackoverflow.com/comment/92221658
has comment: http://stackoverflow.com/comment/92181605
has comment: http://stackoverflow.com/comment/92242174
has comment: http://stackoverflow.com/comment/92158555
score: 0
has comment: http://stackoverflow.com/comment/92126741
has comment: http://stackoverflow.com/comment/92181573
has comment: http://stackoverflow.com/comment/92224043
has body: Script to run python from Java could look like following: String script = "C:\\Users\\Caterina\\Downloads\\PyBoof-master\\PyBoof-master\\examples\\blur_image.py"; String python_app = "python27" Process pr = rt.exec(new String[]{python_app, script}) After process run, you need to wait when it finish by doing following: pr.waitFor() If script is expected will write some output or read some input, you should read output and write something for it's input. Following example writes something to the input stream of subprocess: BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(p.getOutputStream())); writer.write("something"); writer.newLine(); writer.close(); Nevertheless, PyBoof is a Python wrapper for the computer vision library BoofCV (opposite direction, from Python to call Java) as it written on it's GitHub page and you can use BoofCV library directly from Java.
type: Answer
answers question: http://stackoverflow.com/q/52594738
has comment: http://stackoverflow.com/comment/92220596
has comment: http://stackoverflow.com/comment/92196371

http://stackoverflow.com/a/52705676
score: 1
answers question: http://stackoverflow.com/q/52705656
downvote count: 0
has comment: http://stackoverflow.com/comment/92338504
type: Answer
has body: Here are two options among many. isin df[df.Climate.isin(climate_of_interest)] Date Temperature Climate 0 4/1 50 Sunny 2 4/3 48 Rainy 4 4/5 33 Snowy query df.query('Climate in @climate_of_interest') Date Temperature Climate 0 4/1 50 Sunny 2 4/3 48 Rainy 4 4/5 33 Snowy
upvote count: 1

http://stackoverflow.com/comment/92207188
comment on: http://stackoverflow.com/q/52636797
has text: Theres no method on the serial module for reading hex. Even readStringAsBytes will still return a byte string, which you would have to cast over to hex.
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/92386287
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52728432
has text: @shadowtalker I am relatively new to R and did not think to use data.table. It worked very nicely, thank you so much!
type: Comment

http://stackoverflow.com/a/52617152
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52609980
has body: As of Bokeh 0.13 this is known layout bug. There is currently a large PR in progress to address many layout issues at once, including this one, but it will not be ready until Bokeh 1.1 is released. In the mean time, I can only suggest: avoiding the combination of tabs and responsive sizing modes using components to template plots into non-Bokeh layouts.
type: Answer
accepted answer of: http://stackoverflow.com/q/52609980
has comment: http://stackoverflow.com/comment/92214409

http://stackoverflow.com/a/52724111
type: Answer
accepted answer of: http://stackoverflow.com/q/52686520
score: 1
answers question: http://stackoverflow.com/q/52686520
upvote count: 1
has body: OK, so I wasn't able to find a way to do this using Python. I"m sure it's possible but I couldn't figure it out! Anyway, the computer is running Windows so I decided to do it with AutoHotkey. That was trivial to do and worked like a charm. Edit: Here is the example AHK script. I know this answer doesn't really belong in the Python section, but hopefully it will help anybody who finds this through Google :) I decided to go with a toggle key that will capture all keyboard input when it is pressed. When the toggle key is pressed again the script is suspended and all commands go to whichever window is active. #NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases. ; #Warn ; Enable warnings to assist with detecting common errors. SendMode Input ; Recommended for new scripts due to its superior speed and reliability. SetWorkingDir C:\ahkscripts ; Use capslock as a toggle key capslock:: Suspend return ; write "1" to a file. FileAppend will create the file if it doesn't exist 1:: FileAppend, `n1, *myoutputfile.txt, return ; write alt+1 to a file !1:: FileAppend, `naltleft 1, *myoutputfile.txt, return ; write shift+1 to a file +1:: FileAppend, `nshiftleft 1, *myoutputfile.txt, return
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92336594
type: QuestionComment
has text: @mr_mo I am getting asserion error `1 columns passed, passed data had 19 columns`
score: 0
comment on: http://stackoverflow.com/q/52704887
type: Comment

http://stackoverflow.com/comment/92164943
score: 1
has text: You can make this slightly more precise by using randint with a large enough upper bound and then doing the division. This way, the sum itself is exact.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52615139

http://stackoverflow.com/a/52662023
has body: Question: I would like to extract the text in a way that "a": {"aaaa1", "aaaa2", "aaaa3"}, "b": {"bbbb"}, "c": {"cccc"}. Note: If there are more than one tag or <c> within xml, you have to handle this using a condition! import lxml.etree as etree xml = 'aaaa1bbbbaaaa2<c>cccc</c>aaaa3' # Parse xml to tree tree = etree.fromstring(xml) #root = tree.getroot() # In this example, the first tag is the root Element root = tree.tag # Init result dict with this first Element tag:[text] result = {tree.tag:[tree.text]} # Loop every Element in the tree for element in tree: # Add this element to result tag:text result.setdefault(element.tag, element.text) # If this element has a .tail, append it to the root:[] if element.tail: result[root].append(element.tail) print("result:{}".format(result)) >>>result:{'c': 'cccc', 'b': 'bbbb', 'a': ['aaaa1', 'aaaa2', 'aaaa3']} Tested with Python: 3.5
score: 0
answers question: http://stackoverflow.com/q/52660860
type: Answer

http://stackoverflow.com/comment/92274199
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52672130
has text: Your dictionary values are string. If you want an int it would be `'A' : 10,`

http://stackoverflow.com/q/52615206
tagged with: plot
has body: I'm trying to plot rather simple set of data stored in dictionary. Key is the date, when value is.. value. However x axis acts as normal set of values, instead of dates. They are plotted in the order, they are saved in the dictionary (not chronologically).There is as well no real scale on the x axis, so it's not plotting empty space on dates there is no data for. On attached code there is only small part of the real dictionary, but it's enough to show the problem: from matplotlib import pyplot as plt dictionary = {'2015-11-15': 318, '2015-11-16': 3, '2015-11-18': 147, '2015-11-20': 38, '2015-11-22': 128,'2015-11-23': 37, '2015-11-24': 5, '2015-11-25': 3, '2015-11-26': 323, '2015-11-27': 478,'2015-11-28': 49, '2015-11-29': 9,'2015-12-11': 172, '2015-12-13': 219, '2015-12-16': 1,'2015-12-17': 10, '2015-12-18': 25, '2015-12-19': 3, '2015-12-2': 147, '2015-12-21': 133} x = list(dictionary.keys()) y = list(dictionary.values()) plt.plot_date(x,y, xdate=True) plt.xticks(x, rotation='vertical') plt.show() Any idea how to edit the code to show the plot in the proper way? Do I have to sort the dictionary to plot dates chronologically, or will it place them in the right spot automatically? Link 1 - Date tick labels Link 2 - matplotlib.pyplot.plot_date Link 3 - Date Demo Rrule Link 4 - Dates API Possible solution? Plotting dates and associated values from a dictionary with Matplotlib
type: Question
has answer: http://stackoverflow.com/a/52615727
has title: Plotting data from dictionary with dates using Matplotlib
tagged with: matplotlib
score: 0
answer count: 1
tagged with: python-3.x
linked to: http://stackoverflow.com/q/39520366
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/96589784
type: Comment
comment on: http://stackoverflow.com/a/52936728
has text: @jcupitt Sorry to bother again, just a quick question: there aren't any issues with pyvips/libvips on Windows 7, are there? Asking because I'm trying to now implement this fix on an older device, and it isn't performing as expected.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52699654
tagged with: tensorflow
has answer: http://stackoverflow.com/a/56989914
downvote count: 0
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/99283234
has title: Object detection api training issue
type: Question
score: 1
tagged with: python-3.x
tagged with: object-detection-api
upvote count: 1
tagged with: python
answer count: 1
has body: System information OS WIN 10 Processor : i5-4440 3.10GHz RAM 8 TensorFlow installed from (source or binary): pip install TensorFlow version (use command below): b'v1.10.0-rc1-19-g656e7a2b34' 1.10.0 Python version: 3.6.6 Describe the problem I am trying to train object detection api using faster_rcnn_inception_v2_coco_2018_01_28. I am facing with issue with object detection training. After ~400 steps the training stops because of a path problem while the script create the path: path - C:\Users\z\Anaconda3\envs\tensorflow\Lib\site-packages\tensorflow\models\research\object_detection\training_dataturk\models\model\export\Servo\temp-b'1538897129' ----the error screen shot that happened twice before stopping screen shot

http://stackoverflow.com/a/52710426
answers question: http://stackoverflow.com/q/52710396
has body: Yes, it sure does. b &gt; 0. b = 10 while b: print(b) b -= 1 A simple print() statement should let you know when the loop terminates. Furthermore, this does not mean that the loop will not run for negative b &lt; 0. This means that the loop will terminate then b = 0. b = -1 while b: print(b) b -= 1 Goes into an infinite loop.
has comment: http://stackoverflow.com/comment/92347109
has comment: http://stackoverflow.com/comment/92347055
score: 0
type: Answer

http://stackoverflow.com/comment/92141090
type: AnswerComment
comment on: http://stackoverflow.com/a/52603313
type: Comment
has text: Thanks, but I do not want to based on length of sublist. The logic I revised in my question. thanks again.
score: 0

http://stackoverflow.com/a/52691180
answers question: http://stackoverflow.com/q/52689567
score: 0
has body: It's uncommon to create a list of gurobi variables. In general, better use Model.addVars() to get a gurobi tupledict of your variables. And as far as I remember correctly, you can use max_() only inside the Model.addConstr() and Model.addConstrs() methods. To sum it up, here's a way to do it: alpha = global_model.addVar(name="alpha") beta = global_model.addVar(name="beta") maxtime = global_model.addVar(name="maxtime") global_model.update() global_model.addConstr(maxtime == max_(alpha, beta)) global_model.setObjective(maxtime, sense=GRB.MINIMIZE)
type: Answer

http://stackoverflow.com/q/52731754
has body: For this problem, I need to "separate" or identify individual sets of 3 different user inputs: a name, an address, and a salary. Then the program needs to find the highest salary and print the name and the address of the person that it belongs to. I'm not sure how I can do this in Python. I know I can use max(salary) but how can I print the associated name and address? I'm trying to do this using a while loop. Edit: Ok, so I'm a beginner so I apologize if this is too basic. This is what I came up with so far. name = str(raw_input("Input name: ")) address = str(raw_input("Input address: ")) salary = int(raw_input("Input salary or a number &lt; 0 to end program: ")) x = [] while salary &gt; 0: name = str(raw_input("Input name: ")) address = str(raw_input("Input address: ")) salary = int(raw_input("Input salary or a number &lt; 0 to end program: ")) x.append(salary) #this returns error: 'int' object is not iterable m = max(salary) print #should print name, address associated with max(salary) Thank you
has comment: http://stackoverflow.com/comment/92388577
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52739492
score: -4
type: Question
has answer: http://stackoverflow.com/a/52731922
has comment: http://stackoverflow.com/comment/92388565
has comment: http://stackoverflow.com/comment/92388566
has comment: http://stackoverflow.com/comment/92388659
answer count: 2
downvote count: 4
upvote count: 0
has title: How to combine str and int variables?
favorite count: 0

http://stackoverflow.com/comment/92385887
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52730339
has text: Yes it would be faster than try, except.

http://stackoverflow.com/q/52596891
type: Question
has body: All, I built a customized model for binary image classification. I managed to successfully save model using tf estimator to .pb format. My jpg image files have images in various sizes, so I have a image transformation step to transform the images to 224x224. Here is how I define serving_input_fn(): def parse_function_test(filename): image_string=tf.read_file(filename) image=tf.image.decode_jpeg(image_string, channels=3) shape = tf.shape(image) init_width = shape[0] init_height = shape[1] max_size = 224 resized_image = resize_image_keep_aspect(image,init_width,init_height,max_size) image_padded = tf.image.resize_image_with_crop_or_pad(resized_image,max_size,max_size) final_image_padded=tf.image.convert_image_dtype(image_padded,dtype=tf.float32) return final_image_padded def serving_input_fn(): serialized_tf_example=tf.placeholder(dtype=tf.string,shape=1,name='input_tensor') receiver_tensors={'inputs':serialized_tf_example} feature_spec ={'image/encoded':tf.FixedLenFeature([],dtype=tf.string)} features=tf.parse_example(serialized_tf_example,feature_spec) jpegs=features['image/encoded'] images=tf.map_fn(parse_function_test,jpegs,dtype=tf.float32) return tf.estimator.export.ServingInputReceiver(images,receiver_tensors) This is the scoring script. I tried to score on one image file. exported_path='./1538070515' testimg = './test.jpg' filename = tf.constant([testimg]) image= tf.map_fn(parse_function_test,filename,dtype=tf.float32) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def main(): with tf.Session() as sess: value=sess.run(image) tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], exported_path) model_input=tf.train.Example(features=tf.train.Features(feature={'image/encoded':_bytes_feature(value.tostring())})) predictor= tf.contrib.predictor.from_saved_model(exported_path) input_tensor=tf.get_default_graph().get_tensor_by_name("input_tensor:0") print(input_tensor) model_input = model_input.Seria…
has title: How to score model saved using Tensorflow estimator?
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/52610098
tagged with: tensorflow

http://stackoverflow.com/q/52737412
linked to: http://stackoverflow.com/q/48496479
tagged with: python
type: UnansweredQuestion
has title: Tensorboard loss plots go back in time (Keras)
tagged with: tensorflow
type: Question
has body: I have a similar problem to the one described here, only I am using Keras with Tensorflow backend rather then Tensorflow. I have trained 18 MLP models for time series forecasting with different meta parameters, all created with the same basic architecture. The 3 meta parameters I am scanning are the lookahead that the model uses for prediction, the depth of the model, and whether I am using L2 regularization. model = Sequential() # input_shape should be a 3D tensor with shape (batch_size, timesteps ,input_dim) model.add(Flatten()) # hidden layer sizes should drop gradually from 256 to 2*lookahead hidden_layer_sizes = [int(256 - i * (256 - 2 * lookahead) / depth) for i in range(depth)] for hidden_layer_size in hidden_layer_sizes: if regularization: model.add(Dense(hidden_layer_size, kernel_initializer="he_normal", kernel_regularizer = regularizers.l2(0.01), activation=activations)) else: model.add(Dense(hidden_layer_size, kernel_initializer="he_normal", activation=activations)) model.add(Dense(2 * lookahead)) loss = losses.mean_squared_error model.compile(loss=loss, optimizer=self.kwargs["optimizer"], metrics=['mae']) Each model's tensorboard data is saved in a seperate folder through the relevant Keras callback callback_tensorboard = TensorBoard(log_dir=log_dir, histogram_freq=5, write_graph=False, write_grads=True, write_images=False) but for some reason, 3 out of the 18 models have two tensorboard files saved instead of one, and the resulting graphs show this weird phenomena of progressing backwards through time Why does this happen? and other then deleting the second tensorboard file, what can I do to prevent this?
has answer: http://stackoverflow.com/a/54364853
upvote count: 4
downvote count: 0
answer count: 1
tagged with: keras
score: 4
favorite count: 0
tagged with: tensorboard

http://stackoverflow.com/q/52598832
score: 1
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/1466000
has comment: http://stackoverflow.com/comment/92132793
has body: I am learning Python and I have an exercise to work through: Write a program which will read in lines from a file and select the first three fields (separated by blank space). The program should write a file called error which contains lines which look like Line 362 did not have 3 fields, to identify those which did not have 3 fields. The program should then write, into a file called output, the first three fields in the form of a string of width 10, followed by two floats of width 10 each with 3 places after the decimal point. In case this is not possible, the fields should be written as strings of width 10. I have done half of it, but I can't get the list items into the error exceptions report. I don't get any error messages; I just get an empty file. My exceptions data is displayed in Python but the write output is missing. This is my code: file = open("question3.txt",'r') read = file.read() file.close() print(read) #This is the list of sentences that form the list 'read' #I need to analyse these list items. array = read.splitlines() print(array) for item in array: if(item.count(" "))&lt;3: exception = str(item) f = open('error.txt','w') f.write(exception) print(exception) f.close() How can I resolve this? I don't need a full answer to the question, just a suggestion as to how I can get the 'short list fields' I have identified into the text file. Thank you!
has comment: http://stackoverflow.com/comment/92132728
answer count: 3
has answer: http://stackoverflow.com/a/52599051
has title: Writing data from a list
downvote count: 0
has answer: http://stackoverflow.com/a/52599199
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92132436
has answer: http://stackoverflow.com/a/52598982

http://stackoverflow.com/comment/92291744
comment on: http://stackoverflow.com/q/52681747
score: 0
type: Comment
type: QuestionComment
has text: would help if you posted a snippet of the `txt` and any code you attempted

http://stackoverflow.com/comment/92201661
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52633668
has text: forget the parentheses - they dont matter it was just a way of grouping the text that I would like to capture

http://stackoverflow.com/comment/92224917
has text: @PM2Ring Even if there's only one line, `for line in file` is still a fine way to go.
comment on: http://stackoverflow.com/a/52646429
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52692435
score: 0
has body: You are displaying row, not rows, so you are displaying a character from the second element of each row.
type: Answer
answers question: http://stackoverflow.com/q/52692345
has comment: http://stackoverflow.com/comment/92312591

http://stackoverflow.com/comment/92167697
has text: You can set it at any time using the `SET` SQL statement.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52616665
type: Comment

http://stackoverflow.com/a/52726407
has comment: http://stackoverflow.com/comment/92378753
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92378879
upvote count: 1
downvote count: 1
has body: You can do it like this: import re text = """iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.4.2.13.36 = Hex-STRING: 84 16 F9 B0 05 1F 70 4F 57 4C A8 1F 60 E3 27 A1 E0 CD C4 E9 84 C3 68 53 C4 E9 84 C9 7A BB C4 E9 84 AC C3 68 53 27 CC 58 97 84 AC 74 F7 60 E3 27 CC 58 97 84 AC 74 F7 60 E3 27 CC 58 97 84 AC 74 F7 60 E3 27 CC 58 97 84 AC 74 F7 60 E3 27 C3 68 53 84 AC 74 F7 60 E3 27 CC 58 97""" result = re.search("Hex-STRING:\s(.+)$", text, re.DOTALL) print(result.group()) Output Hex-STRING: 84 16 F9 B0 05 1F 70 4F 57 4C A8 1F 60 E3 27 A1 E0 CD C4 E9 84 C3 68 53 C4 E9 84 C9 7A BB C4 E9 84 AC C3 68 53 27 CC 58 97 84 AC 74 F7 60 E3 27 CC 58 97 84 AC 74 F7 60 E3 27 CC 58 97 84 AC 74 F7 60 E3 27 CC 58 97 84 AC 74 F7 60 E3 27 C3 68 53 84 AC 74 F7 60 E3 27 CC 58 97 From the documentation: If the DOTALL flag has been specified, this matches any character including a newline.
answers question: http://stackoverflow.com/q/52726309

http://stackoverflow.com/a/52701281
accepted answer of: http://stackoverflow.com/q/52701085
score: 1
type: AcceptedAnswer
downvote count: 0
has body: It works for me python1.py import sys global var arg1 = sys.argv[1] arg2 = sys.argv[2] var = int(arg1) + int(arg2) print var and the next file is import os import subprocess import sys def test(): dirpath = os.getcwd() os.chdir('.') output = subprocess.check_output([sys.executable, "python1.py", '3', '3' ]) print "output: ",output test()
answers question: http://stackoverflow.com/q/52701085
type: Answer
upvote count: 1

http://stackoverflow.com/comment/92208159
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52636309
score: 0
has text: Possible duplicate of https://stackoverflow.com/questions/16174992/cant-get-argparse-to-read-quoted-string-with-dashes-in-it

http://stackoverflow.com/comment/92489814
comment on: http://stackoverflow.com/a/52730655
type: AnswerComment
score: 0
has text: Sure. An SMT solver can be used as a general-purpose constraint solver. Note that you'll not have the same performance as you would have in a dedicated algorithm, but since SMT solvers cover many different theories (arithmetic, datatypes, booleans, reals..) most such problems can be coded easily and solved rather efficiently.
type: Comment

http://stackoverflow.com/comment/92212667
comment on: http://stackoverflow.com/q/52640088
type: Comment
type: QuestionComment
has text: Provide your code snippet, for people to better understand the issue
score: 1

http://stackoverflow.com/comment/111594011
has text: The reason you need this is explained further down in the documentation: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls
comment on: http://stackoverflow.com/q/52669425
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52635717
tagged with: string-parsing
tagged with: html-parsing
type: Question
has body: I'm trying to parse an HTML source with Python. I'm using BeautifulSoup for the purpose. What I need to get is to get all td tags with ids in the form of nameX format, where X starts from 1. So they are name1, name2, ... as many as we have. How can I achieve this? My simple code using regex doesn't work. soup = BeautifulSoup(response.text,"lxml") resp=soup.find_all("td",{"id":'name*'}) Error: IndexError: list index out of range
score: 0
has title: Parse HTML to get specific tags in Python
answer count: 1
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52635776
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52635776

http://stackoverflow.com/q/52675162
favorite count: 0
tagged with: tkinter
downvote count: 0
type: UnansweredQuestion
has body: I'm trying to use pyinstaller to make builds of a program I've been developing but I'm running into problems with the binary afterward. Here has been my procedure. First I ran pyinstall test.py Then I ran the binary using ./dist/main/test but I get this error which I don't get when running the script normally (such as python3 test.py). Traceback (most recent call last): File "PIL/ImageTk.py", line 181, in paste _tkinter.TclError: invalid command name "PyImagingPhoto" During handling of the above exception, another exception occurred: Traceback (most recent call last): File "magic-collection-tracker/test.py", line 22, in &lt;module&gt; File "magic-collection-tracker/test.py", line 11, in main File "PIL/ImageTk.py", line 120, in __init__ File "PIL/ImageTk.py", line 185, in paste ModuleNotFoundError: No module named 'PIL._tkinter_finder' Here is a minimal example that reproduces the issue. from PIL import ImageTk import PIL.Image from tkinter import * window = Tk() pil_img = PIL.Image.open('./scr_images/blank_card.png') tkimage = ImageTk.PhotoImage(pil_img) canvas = Canvas(window) canvas.create_image(0,0,image=tkimage, anchor=NW) canvas.pack() window.mainloop() Am I using pyinstaller incorrectly or is there some other problem?
score: 3
tagged with: python-imaging-library
has title: Pyinstaller doesn't play well with ImageTk and Tkinter
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/53848300
has answer: http://stackoverflow.com/a/53468495
upvote count: 3
tagged with: pyinstaller
tagged with: python

http://stackoverflow.com/a/52633311
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52633252
answers question: http://stackoverflow.com/q/52633252
upvote count: 3
type: Answer
downvote count: 0
score: 3
has body: You can iterate more efficiently as in the following:" for kw in keywords: for sent in sentences: if kw in sent: lang = kw beginning,ending = sent.split(kw,1) ## Force to only split 1 time

http://stackoverflow.com/comment/92209459
comment on: http://stackoverflow.com/a/52635298
type: AnswerComment
score: 0
type: Comment
has text: The question says "when Grandchild is initiated, the foo() call in Parent.__init__() uses the Parent.foo() instead of Grandchild.foo()", which doesn't really make sense and needs a better code sample. You've addressed the lack of `self` in the constructor calls, but that seems to be an artifact of the questioner making up the code snippet. Your answer doesn't have anything in it related to which version of `foo` gets called, which seems to be the core of the question.

http://stackoverflow.com/q/52697638
tagged with: sqlite
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92321862
favorite count: 0
has answer: http://stackoverflow.com/a/52697652
tagged with: python
type: AnsweredQuestion
has title: sqlite nested for loop bug
score: 1
upvote count: 1
tagged with: cursor
accepted answer: http://stackoverflow.com/a/52697652
type: Question
tagged with: iterator
has body: I am trying to make a ChatBot but I've run into a small problem. I have a nested or loop in python and it's supposed to cycle through a sqlite table that had all the names of other table. The inner for loop cycles through the table inside the first one, iterating over cells. for i in c.execute("""SELECT * FROM triggers_sql"""): for l in c.execute("""SELECT * FROM "{}" """.format(i)): print(i, l) However, for some reason, the outer for loop only cycles through the first cell of the first table. I can't think of anything that I've done wrong here.

http://stackoverflow.com/a/52636680
has body: Good to know: You can apply the same "Predicates and Relationships" methods on MultiPolygons that you can apply on any other Geometric Object in shapely (see documentation). Check for overlapping: To check if two Multipolygons overlap you can use object.intersects(other). See this example (not the MultiPolygons from your picture though): from shapely.geometry import MultiPolygon a = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)] b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)] multi1 = MultiPolygon([[a, []], [b, []]]) c = [(0, 1.5), (1.5, 1.5), (1.5, 3), (0, 3), (1.5, 3)] d = [(1.5, 1.5), (1.5, 0), (3, 0), (3, 1.5), (1.5, 1.5)] multi2 = MultiPolygon([[c, []], [d, []]]) print(multi1.intersects(multi2)) print(multi2.intersects(multi1)) Returns &gt;&gt;&gt;True &gt;&gt;&gt;True Edit: Apparently, OP is not interested in overlapping, but is "trying to find out if the red [multi]polygon has the exact same coordinates as parts of the yellow one". In that case you can iterate over the individual Polygons and check if they are equal to one of the target Polygons: from shapely.geometry import MultiPolygon #target multipolygon a = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)] b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)] c = [(2, 1), (3, 1), (3, 0), (2, 0), (2, 1)] multi_target = MultiPolygon([[a, []], [b, []], [c, []]]) #test multipolygon with two polygons that match a target polygon a = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)] b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)] multi_test1 = MultiPolygon([[a, []], [b, []]]) #test multipolygon where one polygon does not exactly match a target polygon. a = [(0, 0.5), (0, 1), (1, 1), (1, 0.5), (0, 0.5)] b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)] multi_test2 = MultiPolygon([[a, []], [b, []]]) def check_multipolys(test, target): for test_poly in test: exists = False for target_poly in target: if test_poly.equals(target_poly): exists = True break if not exists: return False return True &gt;&gt;&gt;check_multipolys(multi_test1, multi_target) &gt;&gt;&g…
downvote count: 0
has comment: http://stackoverflow.com/comment/92218392
type: Answer
answers question: http://stackoverflow.com/q/52636047
has comment: http://stackoverflow.com/comment/92228158
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139109787

http://stackoverflow.com/q/52645542
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52645722
type: Question
has answer: http://stackoverflow.com/a/52645722
score: 0
upvote count: 1
answer count: 1
tagged with: user-interface
downvote count: 1
favorite count: 0
tagged with: tkinter
has body: If you can see where there's all the topping like bacon, cheese and what not. I'm trying to make that code print ("bacon selected") While it saves itself to a list. Can someone aid me in my efforts to make this program print ("bacon selected") while it saves to a list. list = [] from tkinter import * root = Tk() root.geometry("300x300") mb2= Menubutton(root, text = "Choose your toppings ") mb2.menu = Menu(mb2) mb2["menu"] = mb2.menu bacon = mb2.menu.add_command(label = "bacon", command = lambda:list.append("Bacon selected") #i want to add another command that prints bacon selected here? chesse = mb2.menu.add_command(label = "cheese", command = lambda:list.append("Cheese selected")) mb2.pack() root.mainloop()
has title: Can I run two commands with the a single Tkinter menu button?
tagged with: python

http://stackoverflow.com/q/52720673
has comment: http://stackoverflow.com/comment/92392208
tagged with: python
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/92391282
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/46604114
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/92381181
tagged with: openssl
upvote count: 1
has title: Not able to download Excel Spreadhsheet from a given url
favorite count: 0
tagged with: ssl
has body: I have already written a script that will take an .xlsm file and will update this file based on some other file and then will plot a graph according to the updated data. The Script is working fine. But now as this script is contributing to automation of a process,it needs to get the Excel(.xlsm) file from a url and then update the file and may be save it back to the same url. I have tried downloading the file into a local copy using below code- import requests url = 'https://sharepoint.amr.ith.intel.com/sites/SKX/patchboard/Shared%20Documents/Forms/AllItems.aspx?RootFolder=%2Fsites%2FSKX%2Fpatchboard%2FShared%20Documents%2FReleaseInfo&amp;FolderCTID=0x0120004C1C8CCA66D8D94FB4D7A0D2F56A8DB7&amp;View={859827EF-6A11-4AD6-BD42-23F385D43AD6}/Copy of Patch_Release_Utilization' r = requests.get(url) open('Excel.xlsm', 'wb').write(r.content) By doing this I am getting the error- Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),) What I understood till now is that the Server is not sending the complete Chain Certificates to the browser for authentication. I also tried- r=requests.get(url,verify=False) By doing this error is gone but The file created is empty.When I checked status code for the connection using code- r=requests.get(url,verify=False).status_code I got the code as "401" which means authorization error.I have tried providing authentication as- resp = requests.get(url,auth=HTTPBasicAuth('username', 'password'),verify=False) and resp = requests.get(url,auth=HTTPBasicAuth('username', 'password')) both the above lines I have tried but still status code remained same. Then I came along an article-Python requests SSL error - certificate verify failed ,where the author is asking to add missing certificates in a .pem file then use that pem file.How to know what are the missing certificates??So din't get any help from there also. Can somebody please help me with this if somebody already catered this problem.It will …

http://stackoverflow.com/q/52680467
has answer: http://stackoverflow.com/a/52680733
has answer: http://stackoverflow.com/a/52680515
type: Question
tagged with: numpy
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
upvote count: 8
tagged with: python
possible better answer: http://stackoverflow.com/a/52680733
accepted answer: http://stackoverflow.com/a/52680515
score: 8
type: AnsweredQuestion
has body: Following is what my dataframe looks like. Expected_Output is my desired/target column. Group Value1 Value2 Expected_Output 0 1 3 9 True 1 1 7 6 True 2 1 9 7 True 3 2 3 8 False 4 2 8 5 False 5 2 7 6 False If any Value1 == 7 AND if any Value2 == 9 within a given Group, then I want to return True. I tried to no avail: df['Expected_Output']= df.groupby('Group').Value1.isin(7) &amp; df.groupby('Group').Value2.isin(9) N.B:- Either True/False or 1/0 can be output.
has title: Check if a value exists using multiple conditions within group in pandas

http://stackoverflow.com/q/52683501
tagged with: django
tagged with: python
has body: Im trying to import a sage package (var) in a python file from sage.all import var but when run the file Im getting this error : Error Traceback (most recent call last): execfile("/home/sagefolder/SageMath/myapp/core/test.py") File "/home/sagefolder/SageMath/ubbr/engine/test.py", line 20, in &lt;module&gt; from sage.all import var File "/home/sagefolder/SageMath/local/lib/python2.7/site-packages/sage/all.py", line 71, in &lt;module&gt; from sage.env import SAGE_ROOT, SAGE_SRC, SAGE_DOC_SRC, SAGE_LOCAL, DOT_SAGE, SAGE_ENV File "/home/sagefolder/SageMath/local/lib/python2.7/site-packages/sage/env.py", line 123, in &lt;module&gt; _add_variable_or_fallback('SAGE_ETC', opj('$SAGE_LOCAL', 'etc')) File "/home/sagefolder/SageMath/local/lib/python2.7/site-packages/sage/env.py", line 103, in _add_variable_or_fallback value = sep.join(components) TypeError: sequence item 0: expected string, NoneType found my guess was that the problems was related to the env path. but even sys.path.append('/path/to/the/sage/') it does not work It seems it has problem with the value of some env variables like 'SAGE_ROOT' and ... but according to the installation manual, if I set the symbolic link ln -s /path/to/SageMath/sage /usr/local/bin/sage then all the required env variable are automatically handled. this module is called from a django views.py which is also installed as a Sage package. if I run the the module using sage test.py everything is ok but when it is called from a django view which is also installed as sage packages I got the mentioned error I would be pleased if anybody can help me as Im doing an important project and I really need to use sage.
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/92295188
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/92306786
has answer: http://stackoverflow.com/a/52697901
accepted answer: http://stackoverflow.com/a/52697901
has title: error with importing sage into a python file
tagged with: sage
tagged with: environment-variables
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52732744
tagged with: python
has comment: http://stackoverflow.com/comment/92390491
score: 2
has comment: http://stackoverflow.com/comment/92390432
has comment: http://stackoverflow.com/comment/92390914
answer count: 0
upvote count: 2
has body: I have created a model and post_save signal which will invoke a management command with something like this from django.core import management management.call_command('your_command', your_options) In that management command, I have to restart a process. I have same 15 machines serving with similar django server. If I change the model, post_save will be triggered on one of those machines and process will be started on that machine. However I want that post_save signal to be triggered in all machines. How can I do this?
has comment: http://stackoverflow.com/comment/92390399
tagged with: django
type: Question
has title: Triggering Django management command with post_save signal on multiple servers
has comment: http://stackoverflow.com/comment/92390437
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52675906
answers question: http://stackoverflow.com/q/52606704
type: Answer
downvote count: 0
has body: Hennion, You said that half_pension is your boolean field. Then try this code: @api.multi def convert_bin_dec(self): for rec in self: if rec.half_pension == True: print "Je suis dans la fonction convert" rec.half_pension_days_value = 5 or You can break your function.it limit multiple entries. @api.multi def convert_bin_dec(self): for rec in self: if rec.half_pension: print "Je suis dans la fonction convert" rec.half_pension_days_value = 5 break
score: 1
upvote count: 1

http://stackoverflow.com/a/52679963
has comment: http://stackoverflow.com/comment/92288615
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52679803
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52679803
type: Answer
has body: Assuming you wish to calculatd the sum of col_1 * col_2 groupwise, you can define a GroupBy object and use transform + sum twice: g = df.eval('prod=col_1*col_2').groupby('col_3') df['col_4'] = g['prod'].transform('sum') / g['col_2'].transform('sum') print(df) col_1 col_2 col_3 col_4 0 1 1 A 2.000000 1 2 1 A 2.000000 2 3 1 A 2.000000 3 4 0 A 2.000000 4 5 0 A 2.000000 5 6 1 B 8.333333 6 7 0 B 8.333333 7 8 0 B 8.333333 8 9 1 B 8.333333 9 10 1 B 8.333333
has comment: http://stackoverflow.com/comment/92288569
score: 3

http://stackoverflow.com/q/52695805
has comment: http://stackoverflow.com/comment/92325271
type: UnansweredQuestion
has title: Save a Tensorflow Model and Load it in Tensorflow.js
tagged with: python
has comment: http://stackoverflow.com/comment/92319767
has comment: http://stackoverflow.com/comment/92318754
tagged with: conv-neural-network
tagged with: tensorflow.js
score: 1
has answer: http://stackoverflow.com/a/53098051
upvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/92318982
type: Question
has comment: http://stackoverflow.com/comment/92349541
has comment: http://stackoverflow.com/comment/92319285
has body: In my regular python code, I have a CNN implemented. I save it using model.save and produce some four files (checkpoint, meta, index, and some other file). However, I cannot load these four files directly to tensorflow.js. Here is the sample CNN: import tflearn from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input') convnet = conv_2d(convnet, FIRST_NUM_CHANNEL, FILTER_SIZE, activation='relu') convnet = max_pool_2d(convnet, 2) convnet = conv_2d(convnet, FIRST_NUM_CHANNEL*2, FILTER_SIZE, activation='relu') convnet = max_pool_2d(convnet, 2) convnet = conv_2d(convnet, FIRST_NUM_CHANNEL*4, FILTER_SIZE, activation='relu') convnet = max_pool_2d(convnet, 2) convnet = fully_connected(convnet, FIRST_NUM_CHANNEL*8, activation='relu') convnet = dropout(convnet, 0.7) convnet = fully_connected(convnet, NUM_OUTPUT, activation='softmax') convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets') model = tflearn.DNN(convnet, tensorboard_dir='log') train = train_data[:7000] test = train_data[-1000:] X = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,1) Y = [i[1] for i in train] test_x = np.array([i[0] for i in test]).reshape(-1,IMG_SIZE,IMG_SIZE,1) test_y = [i[1] for i in test] model.fit({'input': X}, {'targets': Y}, n_epoch=NUM_EPOCHS, validation_set=({'input': test_x}, {'targets': test_y}), snapshot_step=500, show_metric=True, run_id=MODEL_NAME) model.save(MODEL_NAME) print('MODEL SAVED:', MODEL_NAME) The last two lines of this code snippet is for saving the model. I can just load the model in a flask app but I want to port it to tensorflow.js. Can anyone give me a tutorial on how to do this?
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/52644592
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92221971
has comment: http://stackoverflow.com/comment/92222152
answers question: http://stackoverflow.com/q/52644466
has comment: http://stackoverflow.com/comment/92221802
has comment: http://stackoverflow.com/comment/92221452
has comment: http://stackoverflow.com/comment/92222881
has comment: http://stackoverflow.com/comment/92222937
upvote count: 1
type: Answer
has body: You can use the function items() to iterate over both the keys and the values at the same time: from random import randint class Character: # Instantiates each character with personality traits def __init__(self, name, health, lives, gender, inventory): self.name = name self.health = int(health) self.lives = int(lives) self.gender = gender self.inventory = [] inventoryitems = { 'Breadstick': randint(0,5), 'Magic Axe': randint(50,100), 'Tiny Fists': randint(0,25), 'Sword': randint(15,30) } player = Character("Kate", 100, 3, 'female',None) # item will be a (key, value) pair for item in inventoryitems.items(): player.inventory.append(item) # or if you only want to add specific items items_to_add = ['Breadstick', 'Magic Axe'] for item in items_to_add: player.inventory.append((item, inventoryitems[item])) print(player.inventory) will print e.g. [('Breadstick', 5), ('Magic Axe', 51), ('Tiny Fists', 21), ('Sword', 17), ('Breadstick', 5), ('Magic Axe', 51)] Note how adding items twice will not apply new random values to each one, which might not be what you are looking for.

http://stackoverflow.com/q/52612982
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92161203
tagged with: queue
answer count: 1
favorite count: 0
score: 0
has title: Merging two queues in alphabetic orders
tagged with: python
has body: I'm trying to merge two queues (these two queues assume that have been alphabetically sorted) into a third queue and return the third queue in alphabetical order. For example: queue1 = ["a","d","x"] queue2 = ["b","c","y","z"] # the third queue should look like queue3 = ["a","b","c","d","x","y","z"] This is my code (I'm doing without using the method merge()): import string from pythonds.basic.stack import Stack class Stack1Queue: Stackone = Stack() Stackto = Stack() def __init__(self): self.items = [] def add(self, element): self.items.append(element) def remove(self): if len(Stackto) == 0: if len(Stackone) == 0: return None while not Stackone.isEmpty(): p = Stackone.pop() Stackto.push(p) return Stackto.pop() def peek(self): return self.items[len(self.items) - 1] def isEmpty(self): return self.items == [] def size(self): return len(self.items) class MergeQueue(Stack1Queue): adict = dict(enumerate(string.ascii_lowercase)) Queuethr = Stack() def merge(self, Stackone, Stackto): while not Stackone.isEmpty() and Stackto.isEmpty(): for k, v in adict.items(): if Stackone.peek() == adict.get(v): Queuethr.push(Stackone.peek()) else: Queuethr.push(Stackto.peek()) print(dict(Queuethr)) return 1 Basically my first class Stack1Queueis to implements two stack to create a queue. Anyway, I just wonder whether my merge function is correctly written or not. When I try to run: s = Stack1Queue() p = Stack1Queue() q = MergeQueue() s.add("z") s.add("y") s.add("d") s.add("b") s.add("a") p.add("x") p.add("d") p.add("c") print(q.merge(s, p)) It return 0 for the size of q
has answer: http://stackoverflow.com/a/52613266
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/52613266
type: Question

http://stackoverflow.com/q/52646124
favorite count: 0
has title: Changing a key's value in a dictionary in a list
linked to: http://stackoverflow.com/q/41464870
possible better answer: http://stackoverflow.com/a/52646252
tagged with: python
tagged with: dictionary
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/52646153
score: 2
type: AnsweredQuestion
tagged with: list
duplicate of: http://stackoverflow.com/q/41464870
type: Question
answer count: 2
has body: I have a dictionary in a list like: my_list = [{'Name':'John','Age':'50','Job':'NIL'},{'Name':'Sara','Age':'70','Job':'NIL'}] I want to change the value of the key Job in the list based on the parameter that whether their age is above or below 60, like if the age is below 60, the job value is changed to 1 and if the age is above 60 the job value is changed to 0. This is what out I am expecting: my_list = [{'Name':'John','Age':'50','Job':'1'},{'Name':'Sara','Age':'70','Job':'0'}]
downvote count: 0
has answer: http://stackoverflow.com/a/52646252
accepted answer: http://stackoverflow.com/a/52646153

http://stackoverflow.com/comment/92172954
type: QuestionComment
type: Comment
has text: `transactionDate` is `CharField`, which is not recommended
comment on: http://stackoverflow.com/q/52619441
score: 0

http://stackoverflow.com/q/52642756
has comment: http://stackoverflow.com/comment/92217780
has comment: http://stackoverflow.com/comment/92218083
answer count: 1
has comment: http://stackoverflow.com/comment/92222400
has body: I have a test set of 18000 examples. Χ_test.shape: (18000, 128, 128, 1) I have trained my model and want to use predict on X_test. If I try to just use: pred = model.predict_on_batch(X_test) it gives a memory error. I tried something like: X_test_split = X_test.flatten() X_test_split = np.array_split(X_test_split, 562) # batch size is 32 pred = np.empty(len(X_test_split), dtype=np.float32) for idx, _ in enumerate(X_test_split): pred[idx] = model.predict_on_batch(X_test_split[idx].reshape(32, 128, 128, 1)) but it either gives me memory error again or it gives me error about the reshape (depending on variations I am trying in the above code) I have the same problem using predict_generator also.
has comment: http://stackoverflow.com/comment/92220243
tagged with: keras
tagged with: python
has comment: http://stackoverflow.com/comment/92227399
has comment: http://stackoverflow.com/comment/92218380
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92222066
has answer: http://stackoverflow.com/a/52649588
type: Question
has title: memory error in predict_on_batch() on large data set
has comment: http://stackoverflow.com/comment/92217798
score: 0
has comment: http://stackoverflow.com/comment/92222232
accepted answer: http://stackoverflow.com/a/52649588
tagged with: deep-learning

http://stackoverflow.com/a/52621930
has body: urllib.request.Request is the class that the urllib.request module uses to abstract a request. To make an HTTP request you should use urllib.request.urlopen instead: response = urllib.request.urlopen(REST_API_URL, sample.encode('utf-8'))
type: Answer
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52621830

http://stackoverflow.com/q/52681587
favorite count: 0
tagged with: pandas-loc
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52682277
has answer: http://stackoverflow.com/a/52682277
type: Question
score: 5
has comment: http://stackoverflow.com/comment/92292167
upvote count: 5
has answer: http://stackoverflow.com/a/52682058
answer count: 2
accepted answer: http://stackoverflow.com/a/52682058
tagged with: pandas
downvote count: 0
has body: I would like to insert a row into an empty DataFrame. However, this seems to fail for a DataFrame with predefined indices and when the elements include a tuple or list prompting the error: ValueError: setting an array element with a sequence. The example code is as follows: df = pd.DataFrame(columns=['idx1', 'idx2', 'col1', 'col2', 'col3']) df.set_index(['idx1', 'idx2'], inplace=True) df.loc[(1,2),:] = [3,4,(5,6)] print(df)
has title: Inserting a tuple into an empty pandas dataframe

http://stackoverflow.com/q/52630632
has comment: http://stackoverflow.com/comment/92194887
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52631184
has comment: http://stackoverflow.com/comment/92195472
has title: Why is my verification code marking input wrong even when it's correct?
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/92194738
favorite count: 0
has comment: http://stackoverflow.com/comment/92194829
has body: I am trying to code a game that displays the first letter of a song and the artist and requires the user to guess the song in two tries. However, when I try to verify that the answer is correct (which is always is) it still says it is wrong. My code is as follows: import random for x in range(0, 13): randNum = int(random.randint(0, 13)) song = open("Songs.txt", "r") songname = str(song.readlines()[randNum]) print(songname[0]) song.close() artist = open("Artists.txt", "r") artistname = artist.readlines()[randNum] print(artistname) artist.close() songGuess = input("What is the song called?") for x in range(0,1): if songGuess == songname: print("Answer correct!") else: songguess = input("Incorrect! Try again:") x = x + 1 if x == 2: print("GAME OVER") break x = x+1 if x == 13: break quiz() What should happen is that the user should have two tries to guess the name of the song when only given the first letter of its name and the artist, and if they cannot guess it by the end of the game, it should end.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52631521
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/92195987

http://stackoverflow.com/comment/92160025
type: AnswerComment
comment on: http://stackoverflow.com/a/52602459
type: Comment
has text: I do have the entire separate csv files loaded into the same dataframe, so the to_sql statement knows which table to add it to. However, I'm using an Azure DB Server to connect to SQL Server if that provides any additional help or concerns.
score: 0

http://stackoverflow.com/comment/92413173
has text: Is there a way to manipulate those images online without downloading them? i.e giving the code image's url instead of local path ?
type: Comment
comment on: http://stackoverflow.com/a/52736785
score: 2
type: AnswerComment

http://stackoverflow.com/comment/92384974
has text: Try looking in $HOME/.bash_profile. The anaconda installer automatically generates and maintains this line. I am having the same problem: unusually long startup times for Terminal caused by this line.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52706888

xbrl
tag name: xbrl
tags question: http://stackoverflow.com/q/52743460
type: Tag

http://stackoverflow.com/comment/92199359
comment on: http://stackoverflow.com/q/52632912
score: 0
has text: Have you tried to use pandas (https://pandas.pydata.org/)? It is a powerful library that certainly does this in an elegant way.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/114280728
has text: This also solves the problem on LFT - ubuntu 18 on jetsons.
type: AnswerComment
comment on: http://stackoverflow.com/a/52819781
type: Comment
score: 1

http://stackoverflow.com/comment/92133437
type: AnswerComment
comment on: http://stackoverflow.com/a/52598577
type: Comment
score: 1
has text: @Yuca Oops, sorry. Ok, it would help if you could be more specific, but let me try: For example `helper[2:, 1:-1]` this has the same shape as `map_`. It marks upper neighbors of buildings, i.e. it has a `1` everywhere where the cell below in `map_` has a `0`. By `or`ing together the four shifted `helper`s we get _all_ (up down left right) neighbors of buildings. This still includes neighbors that are building themselves. To discard them we `and` with the original `map_`.

http://stackoverflow.com/q/52667908
has comment: http://stackoverflow.com/comment/92267825
tagged with: python
has title: Get more details from exception
answer count: 0
score: 0
type: UnansweredQuestion
tagged with: google-sheets-api
has comment: http://stackoverflow.com/comment/92265601
type: Question
has comment: http://stackoverflow.com/comment/92282265
tagged with: google-sheets
has body: Trying to run Google spreadsheets sample application. Got exception while uploading credentials: try: creds = store.get() except Exception as e: print(e) print("exception end") Strange is fact that only line _module was printed while executing Exception code block. How to understand what exactly was wrong? What does _module means? Whole code: from __future__ import print_function from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # If modifying these scopes, delete the file token.json. SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly' # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' SAMPLE_RANGE_NAME = 'Class Data!A2:E' def main(): print("starting") """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ #store = file.Storage('token.json') store = file.Storage('D:\pyth_nonsens\workspace_python\PyhonTutorial\google\credentials.json') #store = file.Storage('My Project aaa-8102e33b9fef.json') try: creds = store.get() except Exception as e: print(e) print("exception end") if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) # Call the Sheets API SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' RANGE_NAME = 'Class Data!A2:E' result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) if not values: print('No data found.') else: print('Name, Major:') for row in values: # Print columns A and E, which correspond to indices 0 and 4. print('%s, %s' % (row[0], row[4])) print(__name__) if __name__ == 'test_spread': print("true") main()

http://stackoverflow.com/q/52593518
has comment: http://stackoverflow.com/comment/92122517
score: -1
tagged with: optimization
type: Question
has comment: http://stackoverflow.com/comment/92122012
linked to: http://stackoverflow.com/q/582336
upvote count: 1
answer count: 1
tagged with: data-mining
has body: import os,re import math from math import log10 import nltk.corpus from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer from collections import defaultdict python_file_root = './presidential_debates' def getidf(token): document_occurance = 0 for filename in os.listdir(python_file_root): file = open(os.path.join(python_file_root, filename), "r") for line in file: if re.search(r'\b' +token+ r'\b', line): document_occurance = document_occurance + 1 break if (document_occurance != 0): idf = log10(30 / document_occurance) return idf return -1 def normalize(filename,token): file = open(os.path.join(python_file_root, filename), "r") counts = dict() square = [] count1 = 0 for line in file: count1 = count1 + 1 if line in counts: counts[line] += 1 else: counts[line] = 1 for key,value in counts.items(): tf = 1 +log10(value) idf = getidf(key.rstrip()) square.append((tf * idf)*(tf * idf)) summ = sum(square) sqroot = math.sqrt(summ) return sqroot def getweight(filename,token): hit_count1 = 0 final = 0 file = open(os.path.join(python_file_root, filename), "r") idft = getidf(token) for line in file: if re.search(r'\b' +token+ r'\b', line): hit_count1 = hit_count1 + 1 if (hit_count1 == 0): return 0 else: tf = 1 + log10(hit_count1) initial = idft * tf if(initial &lt;= 0): final = 0 return final else: normalize_fact = normalize(filename,token) final = initial / normalize_fact return final for filename in os.listdir(python_file_root): file = open(os.path.join(python_file_root, filename), "r") doc = file.read() doc = doc.lower() stemmed = [] tokenizer = RegexpTokenizer(r'[a-zA-Z]+') tokens = tokenizer.tokenize(doc) stoplist = stopwords.words('english') stop_removed = [word for word in tokens if word not in stoplist] with open(os.path.join(python_file_root, filename), "w") as f: for item in stop_removed: stemmer = PorterStemmer() stemmed = [stemmer.stem(item)] for items in stemmed: f.write("%s\n" % items) print("\nIDF\n") …
has answer: http://stackoverflow.com/a/52603588
favorite count: 0
accepted answer: http://stackoverflow.com/a/52603588
tagged with: tf-idf
tagged with: python
has title: Python code taking more than 15 minutes to generate output
downvote count: 2
type: AnsweredQuestion
tagged with: performance
has comment: http://stackoverflow.com/comment/92121832

http://stackoverflow.com/q/52654043
has title: Issue with openpyxl.styles module in python, unable to set font attribute
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52654303
tagged with: fonts
accepted answer: http://stackoverflow.com/a/52654303
tagged with: openpyxl
type: Question
has body: Having an issue using the openpyxl.styles.Font() function, I'm seeing it taught this way in the documentation as well, so unsure what might have changed. &gt;&gt;&gt; import openpyxl &gt;&gt;&gt; from openpyxl.styles import Font &gt;&gt;&gt; wb = openpyxl.Workbook() &gt;&gt;&gt; sheet = wb.get_sheet_by_name('Sheet') &gt;&gt;&gt; font_style = Font(sz=30, i=True) &gt;&gt;&gt; sheet['A1'].font = font_style Traceback (most recent call last): File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; sheet['A1'].font = font_style AttributeError: can't set attribute I've also tried it this way: sheet['A1'].font = Font(size=30, italic=True) sheet['A1'].font = Font(sz=30, i=True) Getting this error message when I try to set a cell to a font style, nothing seems to be working. Any suggestions are appreciated, thank you.
score: 0
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92255764

http://stackoverflow.com/a/52656455
upvote count: 1
answers question: http://stackoverflow.com/q/52656428
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92244376
has body: should work. You don't need to check all requirements if pass already does not meet one of them. And you actually don't need True in this while loop. import re attempts = 3 def validate(): for attempt in range(3): password = input("Enter a password that meets all of the requirments: ") if len(password) &lt; 6: print("Your password must be at lest 6-20 letters") print("attempt", attempt) continue if re.search('[0-9]',password) is None: print("Your password must have a number in it") continue if re.search('[A-Z]',password) is None: print("Your password must contain a capital letter in it") continue print("All password conditions have been met, great job your password is acceptable") return

http://stackoverflow.com/comment/92404319
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52723148
has text: Thanks for the answer.How can i make this works for PyQt4?
score: 0

http://stackoverflow.com/comment/92408130
comment on: http://stackoverflow.com/q/52741555
type: Comment
type: QuestionComment
has text: @Agile_Eagle The output the OP has is a square matrix. But you are right, they probably want formatted string output.
score: 0

http://stackoverflow.com/comment/92300519
type: Comment
has text: Please show us your attempt.
score: 1
comment on: http://stackoverflow.com/q/52686600
type: QuestionComment

http://stackoverflow.com/a/52738642
has comment: http://stackoverflow.com/comment/92451794
has comment: http://stackoverflow.com/comment/92405887
has comment: http://stackoverflow.com/comment/92405858
type: Answer
has comment: http://stackoverflow.com/comment/92452158
has body: I believe you need str for remove first and last [] or use str.strip: mask = df2['Item'].str[1:-1] == 'Phone' #alternative solution #mask = df2['Item'].str.strip('[]') == 'Phone' print (mask) 0 True 1 False 2 False 3 False 4 False Name: Item, dtype: bool If no missing values is possible use list comprehension, what is faster if large data: mask = [x[1:-1] == 'Phone'for x in df2['Item']] mask = [x.strip('[]') == 'Phone'for x in df2['Item']] print (mask) [True, False, False, False, False] Last for select multiple columns use list: df3 = df2.loc[mask, ['RelatedItem', 'CountinInventory']] print (df3) RelatedItem CountinInventory 0 [Phone cover] 20
has comment: http://stackoverflow.com/comment/92454710
has comment: http://stackoverflow.com/comment/92451407
score: 3
accepted answer of: http://stackoverflow.com/q/52738575
upvote count: 3
has comment: http://stackoverflow.com/comment/92405739
answers question: http://stackoverflow.com/q/52738575
has comment: http://stackoverflow.com/comment/92405644
has comment: http://stackoverflow.com/comment/92454959
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/92350624
type: AnswerComment
score: 0
has text: I'm using this and nothing is happening: `import msvcrt running = True pos = [0,0] while running: move = msvcrt.getch() if move == "w": pos[0] = (pos[0] + 1) print(pos) elif move == "d": pos[1] = (pos[1] + 1) print(pos) elif move == "x": break`
type: Comment
comment on: http://stackoverflow.com/a/52712256

http://stackoverflow.com/comment/92199452
type: Comment
has text: Just start coping over the code should work if everything you posted is similar to your actual environment. Edited my answer for that error. missed `()` after read
score: 0
comment on: http://stackoverflow.com/a/52632500
type: AnswerComment

http://stackoverflow.com/a/52666056
has body: def read_people(csv_filename): """reads file and sorts it then runs through a class""" lst = [] final = [] file = open(csv_filename, 'r') for row in file: print(row) lst.append(row) You should return your list at the end of your function
has comment: http://stackoverflow.com/comment/92261916
has comment: http://stackoverflow.com/comment/92262085
downvote count: 0
has comment: http://stackoverflow.com/comment/92261829
upvote count: 2
answers question: http://stackoverflow.com/q/52665924
type: Answer
score: 2

http://stackoverflow.com/comment/92138450
comment on: http://stackoverflow.com/q/52601676
has text: @ShioT Yes it would, thanks I've edited my description
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92135795
type: AnswerComment
type: Comment
score: 1
has text: haha aran called me out my explanation was 'Do this', I responded with I was being lazy hahaha
comment on: http://stackoverflow.com/a/52600436

http://stackoverflow.com/comment/92398376
type: Comment
has text: It should be noted that this seems to be caused simply by incompatible versions of gremlin-python and JanusGraph. You haven't said which version of JanusGraph you are using but your config file corresponds to versions 0.2.z which are compatible with TinkerPop - and therefore gremlin-python - versions of 3.2.z. That explains why you had problems with gremlin-python 3.3.3. JanusGraph supports TinkerPop versions of 3.3.z since version 0.3.0. The compatible version are always stated in [JanusGraph's version compatibility matrix](https://docs.janusgraph.org/latest/version-compat.html).
score: 2
comment on: http://stackoverflow.com/a/52725985
type: AnswerComment

http://stackoverflow.com/comment/126851680
comment on: http://stackoverflow.com/a/58243606
type: AnswerComment
has text: Is that required behavior or just how CPython does it? I looked at the docs and I didn’t see anything concrete about the order.
score: 0
type: Comment

http://stackoverflow.com/a/52710891
upvote count: 1
answers question: http://stackoverflow.com/q/52710749
type: Answer
has body: You have most of the framework already there. There are a number of pieces of code that run when a class is first created. The simplest one to use is the class body itself. You could use it to create a class variable containing the attributes you wanted with a snippet like the one you show here: class MyBaseClass: with open('config.json', 'r') as f: attributes = json.load(f) def __new__(cls): self = super().__new__(cls) self.__dict__.update(cls.attributes) Any name in the class namespace that remains after the class is run becomes a class variable, not just methods. Updating a dictionary will only work if you have a regular class that doesn't use slots or have conflicting properties. In those cases, use your setattr loop in __new__.
downvote count: 0
score: 1

http://stackoverflow.com/comment/92412765
score: 0
type: QuestionComment
type: Comment
has text: Is `final result` what you want the data to look like? Also, it's good etiquette to show what you've tried so far on your own before just posting your problem and asking for someone to solve it.
comment on: http://stackoverflow.com/q/52744105

http://stackoverflow.com/comment/92414996
type: Comment
has text: Can you show the complete error message?
type: QuestionComment
comment on: http://stackoverflow.com/q/52744713
score: 0

http://stackoverflow.com/comment/92378244
type: Comment
type: QuestionComment
score: 0
has text: Maybe the files are hidden for some reason - can you select 'Show hidden files...' in Folder Options?
comment on: http://stackoverflow.com/q/52726459

http://stackoverflow.com/a/52660677
type: Answer
answers question: http://stackoverflow.com/q/52660179
has body: Another solution would be to use a pivot table to group by the dates. pd.pivot_table(df1, values='Value', index='Date', aggfunc='count').plot(kind='bar')
score: 0

http://stackoverflow.com/q/52723597
upvote count: 1
has answer: http://stackoverflow.com/a/52723849
favorite count: 0
has answer: http://stackoverflow.com/a/52723662
accepted answer: http://stackoverflow.com/a/52723662
tagged with: python
tagged with: dictionary
answer count: 4
has comment: http://stackoverflow.com/comment/92372704
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52724223
tagged with: loops
has title: Python - Finding the average of a value in parallel dictionaries
possible better answer: http://stackoverflow.com/a/52723791
type: Question
has answer: http://stackoverflow.com/a/52723791
has body: So I have some .csv data files I have to clean up. An example of one of the lines of data is: u[i] = {'age': '44', 'salary': '117681.0', 'suburb': None, 'language': 'English'} I have filtered out the data I dont want and have returned multiple rows of relevant dictionaries. eg: {'age': '44', 'salary': '117681.0', 'suburb': None} {'age': '34', 'salary': '56456.0', 'suburb': 'Frankston'} {'age': '37', 'salary': '59370.0', 'suburb': 'Richmond'} {'age': '44', 'salary': '91399.0', 'suburb': 'Collingwood'} {'age': '36', 'salary': '74437.0', 'suburb': 'Toorak'} {'age': '41', 'salary': '89121.0', 'suburb': 'Frankston'} I now want to sum up the salary from each of these dictionaries to find the average salary, but I can't figure it out for the life of me. I've tried isolating just the salary values and using counters but I cant seem to get that to work. I've also tried making lists that I can loop through but I can't seem to get all the values on one single list. The problem for me is that when I isolate the values they are parallel values/lists and I don't know how to work with it. Would really appreciate any help, this has been driving me crazy! Thanks! Here's my code so far, but I haven't really got anything worth looking at at this stage: def average_salary(data, lower_age, upper_age): u = dict(sorted(data_cleaned.items())) count = 0 for i in u: age = u[i]['age'] sal = u[i]['salary'] tally = 0 if age is not None and sal is not None and lower_age &lt; float(age) &lt; upper_age: tally += float(u[i]['salary']) print(u[i]['salary'])
tagged with: counter

http://stackoverflow.com/q/52598619
tagged with: string
favorite count: 0
tagged with: python
tagged with: python-3.x
upvote count: 3
type: UnansweredQuestion
has body: So, I was looking for an algorithm for the following problem: You are given a desired string s, and a stamp t. t is also a string. Let the beginning string be len(s)*"?". Is it possible to use the stamp to transform the beginning string into the string s using the stamp? The whole stamp must fit inside the beginning string (the stamp's borders may not exceed the ?????... string's borders). Print the number of stamps required and print the left border of the stamp for each stamping. Example: AABCACA (desired result) ABCA (stamp) Solution: 3 1 4 2 explanation: ??????? → ABCA??? → ABCABCA → AABCACA. My solution: If the stamp's first letter is not the desired string's first letter, the task is not possible. The same goes for the last letter. If the stamp doesn't have all the letters in the desired string, the task is impossible. My algorithm goes like this: try to find the stamp in the desired string. If it is found, delete it and replace it with question marks. Mark down the left border of the stamp. Do this as long as you can. Then look for the stamp's contiguous subarrays of size len(stamp)-1. If you find any of those, delete them and replace with question marks. Mark down the left border of the stamp. Then look for the stamp's contiguous subarrays of size len(stamp)-2. If you find any of those, delete them and replace with question marks. Mark down the left border of the stamp. Do that until you are finished. There you have the answer. The problems I'm not sure what is wrong with my code as it can't seem to pass some test cases. There is probably a logical error. import sys desiredString = input() stamp = input() stampingSpots = [] if (len(set(desiredString)) != len(set(stamp)) or stamp[0] != desiredString[0] or stamp[-1] != desiredString[-1]): print("-1") sys.exit() def searchAndReplace(stringToFind, fix): #Search for stringToFind and replace it with len(stringToFind)*"?". Fix is used to fix the position. global desiredString for x in range(0, len(desiredString)-le…
score: 3
tagged with: algorithm
has title: Optimal way to "stamp" string into desired string
has comment: http://stackoverflow.com/comment/92133433
has answer: http://stackoverflow.com/a/52605745
type: Question
has answer: http://stackoverflow.com/a/52598855
answer count: 2
downvote count: 0

http://stackoverflow.com/a/52649457
has body: Try this: g = df.groupby(df.index.floor('D'))['y'] df[(np.abs(df.y - g.transform('mean')) &lt;= (3*g.transform('std')))]
type: Answer
answers question: http://stackoverflow.com/q/52648644
score: 0

http://stackoverflow.com/a/52668353
answers question: http://stackoverflow.com/q/52668183
type: Answer
has body: You have a few minor mistakes there is no maths module a is the number, not the list. You should append on a list you call print after the loop ends, not on every iteration from random import random def results(): numbers = [] for _ in range(1,10): a = random() print(a) numbers.append(a) return numbers
score: 0

http://stackoverflow.com/comment/92267057
has text: Can you describe more precisely what you mean by "fits in"? Or really, what might be an underlying similarity of your time series? I think clarity on this point is crucial. If the set of time series you have are all drawn from the same underlying process with same parent distribution, then it is a matter of a statistical test. If the time series are statistically independent but have, say, the same power spectrum, similarity testing is more about testing frequency distribution.
comment on: http://stackoverflow.com/q/52666862
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52683291
score: 1
has body: I am using Kivy with Python 3.5. I'm trying to set up an App where a button press schedules a function call. A premise: this is my first application with Kivy, and I am not very good with Python. Here's my simplified code: class MyApp(App): def build(self): layout = GridLayout(cols=2) TextStream = Label(text = 'Something will be written here: ') StartButton = Button(text = 'Start writing') StartButton.bind(on_press=lambda x:self.start_program(freq=10)) layout.add_widget(TextStream) layout.add_widget(StartButton) return layout def start_program(self, freq): Clock.schedule_interval(self.write_something, 1.0/freq) # Also tried Clock.schedule_interval(self.write_something(), 1.0/freq) def write_something(self): TextStream.text =+ 'Something ' if __name__ == '__main__': MyApp().run() What I get when I run the script is: TypeError: write_something() takes 1 positional argument but 2 were given Reading the answers to this question, about this specific error, I understood that methods in Python are actually implemented differently from how they appear in code. More precisely, from this comment I understand that properly declaring the method write_something giving it self as argument is the correct way to do it. Also, from this answer I get that the number of passed arguments counted by Python should be 1+N, where N are passed in the call. I am not passing any argument in the call however. So, are there some silent arguments passed with Kivy? Am I calling the method in the wrong way? Edit - Error stack As suggested by a comment, I include the entire error stack: Traceback (most recent call last): File "&lt;ipython-input-1-5d17b5569154&gt;", line 1, in &lt;module&gt; runfile('/home/raggot/Projects/MyApp/scripts/_test_kivy.py', wdir='/home/raggot/Projects/MyApp/scripts') File "/usr/local/lib/python3.5/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/usr/local/lib/python3.5/dist-packages/spyder/utils/site/sitecustomize…
type: Question
has comment: http://stackoverflow.com/comment/92294813
downvote count: 0
accepted answer: http://stackoverflow.com/a/52683704
favorite count: 0
has comment: http://stackoverflow.com/comment/92295255
tagged with: typeerror
has comment: http://stackoverflow.com/comment/92295208
has comment: http://stackoverflow.com/comment/92294671
answer count: 1
has comment: http://stackoverflow.com/comment/92294799
tagged with: kivy
has answer: http://stackoverflow.com/a/52683704
has title: Unexpected TypeError in a function call with Kivy
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/92295328
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/23944657

http://stackoverflow.com/comment/92408098
has text: @Mendhak Yes, I edited my question!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52741536
score: 1

http://stackoverflow.com/comment/92197627
type: Comment
comment on: http://stackoverflow.com/a/52632120
has text: Yes! Is this just a simple bug in `df.plot()`?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92251469
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52659950
has text: If you iterate readfile with a for loop, you get all the lines one by one. You can split or assign them however you want.

http://stackoverflow.com/comment/92408315
type: AnswerComment
comment on: http://stackoverflow.com/a/52740828
type: Comment
has text: I edited the answer to shape it in your desired outcome. `np.transpose` seems to work much faster than `np.moveaxis` from what I've tried. Does that work?
score: 0

http://stackoverflow.com/q/52637505
favorite count: 0
has comment: http://stackoverflow.com/comment/92208075
tagged with: pandas
tagged with: python
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/7586063
has body: I have a time-series data and i am trying to calculate angle (degree) between two points. Here is what i did so far but it doesn't seem to give the correct solution: bars = 2 df = pd.read_csv("EURUSD.csv") df = df.reset_index() df['A'] = np.rad2deg(np.arctan2(df['Low']-df['Low'].shift(pts), df['index']-df['index'].shift(pts))) df.dropna(inplace=True) However, sometimes this gives me weird outputs like: 2693 3.141258 2702 -3.141383 2708 -3.141451 2719 -3.141033 2724 -3.140893 2734 3.141550 I have also tried the following code: df['A'] = ((df['Low']-df['Low'].shift(pts))/(df['index']-df['index'].shift(pts))) 2693 -0.000334 2702 0.000210 2708 0.000142 2719 0.000560 2724 0.000700 2734 -0.000043 what am i doing wrong here? EDIT: Here is the screenshot i'm trying to do. I'm simply trying to find that -48 degree in Python. I am not trying to get these points automatically. I have spotted them manually and just need to do calculation.
has comment: http://stackoverflow.com/comment/92216118
type: Question
has title: Calculating angle between two points in time-series
has answer: http://stackoverflow.com/a/52642639
score: 1
tagged with: numpy
has answer: http://stackoverflow.com/a/69549581
answer count: 2
upvote count: 1

http://stackoverflow.com/q/52602251
tagged with: gradient-descent
type: UnansweredQuestion
tagged with: python
tagged with: linear-regression
has answer: http://stackoverflow.com/a/52602452
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/92138703
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92138711
score: 0
has comment: http://stackoverflow.com/comment/92138675
answer count: 1
has title: How to parallelize simple linear regression with gradient descent - using numpy?
has body: I'm having trouble using numpy to parallelize this for loop below (get_new_weights). With my first attempt for df_dm in update_weights, the weight is completely wrong. With my second attempt at df_dm, my weight overshoots the optimal weight. Note - bias is a single number and weight is a single number (one variable linear regression) and X is shape (442,1) and y is shape (442,1). Also note that updating my bias term works perfectly in update_weights - its just updating the weight that I'm having trouble with. # This is the for loop that I am trying to parallelize with numpy: def get_new_weights(X, y, weight, bias, learning_rate=0.01): weight_deriv = 0 bias_deriv = 0 total = len(X) for i in range(total): # -2x(y - (mx + b)) weight_deriv += -2*X[i] * (y[i] - (weight*X[i] + bias)) # -2(y - (mx + b)) bias_deriv += -2*(y[i] - (weight*X[i] + bias)) weight -= (weight_deriv / total) * learning_rate bias -= (bias_deriv / total) * learning_rate return weight, bias # This is my attempt at parallelization def update_weights(X, y, weight, bias, lr=0.01): df_dm = np.average(-2*X * (y-(weight*X+bias))) # this was my first guess # df_dm = np.average(np.dot((-X).T, ((weight*X+bias)-y))) # this was my second guess df_db = np.average(-2*(y-(weight*X+bias))) weight = weight - (lr*df_dm) bias = bias - (lr*df_db) return weight,bias This is the equation I am using for updating my weight and bias:

http://stackoverflow.com/comment/92365685
has text: @panda - hard question, because data dependent problem, I found [this](https://stackoverflow.com/q/48647122), [this](https://stackoverflow.com/a/33819765), [this](https://stackoverflow.com/q/31558994)
comment on: http://stackoverflow.com/a/52719115
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/92443468
type: Comment
comment on: http://stackoverflow.com/a/52746792
has text: Brilliant a step closer, im now getting the local and remote computer to talk to each other. im getting the following message twice : pydev debugger: warning: trying to add breakpoint to file that does not exist: /home/pi/testdebug/C:/IOT/Github/RaspberryPi/test_remote_debug/test_remote_debug.py (will have no effect). Any ideas why?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92283160
score: 1
type: AnswerComment
has text: Is this saturday which gmt time ?
type: Comment
comment on: http://stackoverflow.com/a/52677058

http://stackoverflow.com/q/52736004
tagged with: python
has title: Django - How to add data from AJAX button into html, so it updates everytime button is clicked?
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/92403602
type: Question
tagged with: javascript
score: 0
answer count: 1
has body: currently, I've got an ajax like button set up. The console shows that the like count is toggling when I press the button, but how do I actually retrieve the 'like_count' variable to put into my HTML. My button code is: &lt;script type="text/javascript"&gt; function toggleLike(){ $.ajax({ url: "{% url 'photo_blog-post_like_api' post.id %}", data: {like_count: 'like_count', 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(data) { console.log(data); } }); }; &lt;/script&gt; and the html for the button is: &lt;input type="button" onclick="toggleLike()" value="Like"/&gt; and the code for my view is: class LikePostAPI(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, slug=None, format=None, pk=None): obj = get_object_or_404(Post, id=pk) user = self.request.user updated = False liked = False if user.is_authenticated: if user in obj.likes.all(): liked = False obj.likes.remove(user) like_count = obj.likes.count() else: liked = True obj.likes.add(user) like_count = obj.likes.count() updated = True data = { "updated": updated, "liked": liked, "like_count": like_count } return Response(data)
tagged with: jquery
has comment: http://stackoverflow.com/comment/92403677
tagged with: ajax
has answer: http://stackoverflow.com/a/52736174

http://stackoverflow.com/comment/92388517
type: QuestionComment
has text: It's not clear what you're trying to ask. None of this is a bug, if that's what you're wondering.
score: 0
comment on: http://stackoverflow.com/q/52731672
type: Comment

http://stackoverflow.com/comment/92164691
score: 0
type: Comment
has text: all partition all the same in terms of json format, only data is different
type: AnswerComment
comment on: http://stackoverflow.com/a/52614174

http://stackoverflow.com/comment/92297460
score: 0
type: Comment
has text: I figured out the problem, thanks to your proof that the issue is definitely not Python. The api I am calling is get_daily() from alpha_vantage (https://github.com/RomelTorres/alpha_vantage) which is a Python wrapper around the https://www.alphavantage.co/ web API. The problem is the *free version* of the web API is limited to 5 requests per minute; and the Python wrapper defaults to 5 retries on a failure, so when sent an invalid key it burned up my 5 requests per minute. When I set retries=0 everything worked fine. Thanks for your help!
comment on: http://stackoverflow.com/a/52670188
type: AnswerComment

http://stackoverflow.com/a/52672778
type: Answer
score: 2
downvote count: 0
has body: This is tuple not string pd.DataFrame(df.Interval.values.tolist()) Out[1098]: 0 1 2 0 0.75 0.7 0.8 #df'Mean','Low', 'High'=pd.DataFrame(df.Interval.values.tolist()) After we change the data type to str , you regex will work df['Interval'].astype(str).str.extract(p,expand=True) Out[1103]: Mean Low High 0 0.75 0.7 0.8
upvote count: 2
answers question: http://stackoverflow.com/q/52672685

http://stackoverflow.com/comment/92292439
has text: But if I am writing logs to a file, then it will be better to create new threads, right? Like `with open('test.log', 'w') as log: log.write(msg)`
type: Comment
comment on: http://stackoverflow.com/a/52681877
score: 0
type: AnswerComment

http://stackoverflow.com/a/52734626
answers question: http://stackoverflow.com/q/52733830
has comment: http://stackoverflow.com/comment/92394262
type: Answer
has comment: http://stackoverflow.com/comment/92395134
has comment: http://stackoverflow.com/comment/92394294
has comment: http://stackoverflow.com/comment/92394061
score: 0
has body: You are thinking too complicated. for svc in data['services']: print(svc['name'], svc['routing']['port']) Done. General observation: You seem to cling to loop indexes. Don't. It's a good thing that Python loops have no indexes. Whenever you are tempted to write for thing in range(len(some_list)): stop, and write for thing in some_list: instead.

http://stackoverflow.com/a/52673825
accepted answer of: http://stackoverflow.com/q/52668844
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/92282666
has comment: http://stackoverflow.com/comment/92282800
has body: The &lt;input&gt; field for the Credit Card number is within an &lt;iframe&gt; so you have to: Induce WebDriverWait for the desired frame to be available and switch to it. Induce WebDriverWait for the desired element to be clickable and you can use the following solution: Code Block: WebDriverWait(session, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"braintree-hosted-field-number"))) WebDriverWait(session, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.number#credit-card-number"))).send_keys("0000000000000000")
has comment: http://stackoverflow.com/comment/92282587
has comment: http://stackoverflow.com/comment/92281198
has comment: http://stackoverflow.com/comment/92282706
answers question: http://stackoverflow.com/q/52668844
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92282679

http://stackoverflow.com/q/52599582
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52599682
score: 1
tagged with: dataframe
has title: how to use time to index in a datetimeIndex array
type: Question
possible better answer: http://stackoverflow.com/a/52599689
answer count: 2
has answer: http://stackoverflow.com/a/52599689
downvote count: 0
tagged with: pandas
tagged with: datetime
has answer: http://stackoverflow.com/a/52599682
tagged with: python
favorite count: 0
has body: I have a pandas dataframe which has datetime as its index (shown below) ['2018-02-13 11:55:00', '2018-02-13 12:00:00', '2018-02-13 12:05:00', '2018-02-13 12:10:00', '2018-02-13 12:15:00', '2018-02-13 12:20:00', '2018-02-13 12:25:00', '2018-02-13 12:30:00', '2018-02-13 12:35:00', '2018-02-13 12:40:00', ... '2018-02-19 04:40:00', '2018-02-19 04:45:00', '2018-02-19 04:50:00', '2018-02-19 05:05:00', '2018-02-19 05:10:00', '2018-02-19 05:15:00', '2018-02-19 05:20:00', '2018-02-19 05:25:00', '2018-02-19 05:30:00', '2018-02-19 05:40:00']) I would like to filter all the value which has time 12:00:00 for example, therefore I am looking for a return value of ['2018-02-13 12:00:00','2018-02-14 12:00:00','2018-02-15 12:00:00','2018-02-16 12:00:00','2018-02-17 12:00:00', '2018-02-18 12:00:00'] How can I perform such indexing please?

http://stackoverflow.com/comment/92161400
type: QuestionComment
comment on: http://stackoverflow.com/q/52613320
has text: because if you compare with 1: and 5 key value. its not exactly same.
score: 0
type: Comment

http://stackoverflow.com/a/52630486
type: Answer
answers question: http://stackoverflow.com/q/52630427
has comment: http://stackoverflow.com/comment/92194841
has comment: http://stackoverflow.com/comment/92196625
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/92194976
downvote count: 0
has comment: http://stackoverflow.com/comment/92194662
has body: I would use something like this, though it's a bit messy with all the re-naming: # Rename columns with dict comprehension so it can extend to more than week 1 and week 2 df2 = (df.rename(columns={i: int(i.split()[-1]) for i in df.columns[1:]}) .set_index('Shop') .stack() .reset_index() .rename(columns={'level_1':'Week', 0:'Hour'})) &gt;&gt;&gt; df2 Shop Week Hour 0 1 1 15 1 1 2 5 2 2 1 25 3 2 2 44 4 3 1 11 5 3 2 55 6 4 1 22 7 4 2 21 8 5 1 0 9 5 2 12 10 6 1 -1 11 6 2 51 12 7 1 15 13 7 2 -10 14 8 1 11 15 8 2 25 16 9 1 76 17 9 2 81 18 10 1 62 19 10 2 46
has comment: http://stackoverflow.com/comment/92194694

http://stackoverflow.com/a/52739814
answers question: http://stackoverflow.com/q/52738368
type: Answer
accepted answer of: http://stackoverflow.com/q/52738368
score: 1
upvote count: 1
has body: What you get after groupby(*multiple_columns*).*some_action* is a Dataframe with MultiIndex. You can reset it: ans = ( df_out .groupby(['grp', 'order'])['order'] .count() .to_frame(name='quantity') .reset_index()) Then you may use any column as index and drop that column: ans.index = ans['grp'] ans = ans.drop('grp', axis=1) ans is: order quantity grp 0 A 1 0 B 1 0 C 2 1 D 3 1 E 1 2 E 2 2 F 2 3 F 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52725852
upvote count: 1
has comment: http://stackoverflow.com/comment/92382723
type: Question
has body: I am attempting to connect to an RDS instance using Python's pymysql library. Unfortunately I'm getting an exception back. Here is my Python code: import pymysql #Connect connection = pymysql.connect(host='jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname', port='3306', user='username', password='pass', database='dbname') Upon executing it, I receive the following exception: Traceback (most recent call last): File "/path/to/file/test.py", line 8, in &lt;module&gt; database='treemigodb') File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__ self.connect() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 629, in connect raise exc pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname' ([Errno 8] nodename nor servname provided, or not known)") Here is what I've tried: I've opened up the security group on the AWS side to traffic. I had previously performed this connection in Java, with success. AWS is configured as it should be. I've seen in other examples that the host format tends to vary. Therefore, I've tried: jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname jdbc:mysql://url.us-east-1.rds.amazonaws.com/dbname jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/ jdbc:mysql://url.us-east-1.rds.amazonaws.com/ dbname.url.us-east-1.rds.amazonaws.com/dbname url.us-east-1.rds.amazonaws.com/dbname dbname.url.us-east-1.rds.amazonaws.com/ Is there some potential setup that I could be missing? I've double-checked that every other parameter matches.
has comment: http://stackoverflow.com/comment/92378567
downvote count: 0
tagged with: pymysql
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/92378479
favorite count: 0
type: UnansweredQuestion
has title: Cannot Connect To RDS Instance Using Python pymysql Library
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92378785
score: 1
tagged with: amazon-rds
tagged with: mysql

http://stackoverflow.com/comment/92362537
type: QuestionComment
has text: @user10389994 merge method has two optional parameters left_on and right_on if dataframes do not share same key name
comment on: http://stackoverflow.com/q/52718220
score: 0
type: Comment

http://stackoverflow.com/comment/92380732
comment on: http://stackoverflow.com/q/52727590
score: 0
has text: I really didn’t need the while choice=="y" thanks! There shouldn’t have been a loop to start with! Thanks
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92237127
type: QuestionComment
has text: Can you reformat your dataframe (for example: df1 and df2) and also add the desired output you are looking for.
comment on: http://stackoverflow.com/q/52652649
score: 0
type: Comment

http://stackoverflow.com/q/52633819
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52634042
has comment: http://stackoverflow.com/comment/92201018
has comment: http://stackoverflow.com/comment/92201064
has answer: http://stackoverflow.com/a/52634042
has comment: http://stackoverflow.com/comment/92201090
score: 1
upvote count: 1
has title: Removing duplicate records from CSV file using Python Pandas
has body: I would like to remove duplicate records from a CSV file using Python Pandas. The CSV file contains records with three attributes, scale, minzoom, and maxzoom. I want to have a resulting dataframe with minzoom and maxzoom and the records left being unique. I.e., Input CSV file (lookup_scales.csv) Scale, minzoom, maxzoom 2000, 0, 15 3000, 0, 15 10000, 8, 15 20000, 8, 15 200000, 15, 18 250000, 15, 18 Required distinct_lookup_scales.csv (Without scale column) minzoom, maxzoom 0,5 8,15 15,18 My code so far is lookup_scales_df = pd.read_csv('C:/Marine/lookup/lookup_scales.csv', names = ['minzoom','maxzoom']) lookup_scales_df = lookup_scales_df.set_index([2, 3]) file_name = "C:/Marine/lookup/distinct_lookup_scales.csv" lookup_scales_df.groupby('minzoom', 'maxzoom').to_csv(file_name, sep=',')
type: Question
has answer: http://stackoverflow.com/a/61958101
tagged with: distinct-values
has comment: http://stackoverflow.com/comment/92201147
has comment: http://stackoverflow.com/comment/92201089
has answer: http://stackoverflow.com/a/52634045
answer count: 3
tagged with: pandas
tagged with: grouping
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52634045

http://stackoverflow.com/q/52656480
has body: I have a large dataset on which I want to plot boxplot charts on some columns, so that I aggregate values in SQL and pass them on to python. Is it possible to create a boxplot chart in holowievs using just aggregated values instead of raw data? Can anybody demonstrate on this simplified example please import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(1000000, 1), columns=list('A'))
accepted answer: http://stackoverflow.com/a/52656798
type: Question
score: 0
answer count: 1
has title: holoviews - boxplot from aggrgated data only
has answer: http://stackoverflow.com/a/52656798
tagged with: holoviews
tagged with: python
type: AnsweredQuestion
tagged with: bokeh

http://stackoverflow.com/q/52593716
has body: from urllib.request import urlopen from bs4 import BeautifulSoup page_origin = urlopen("https://stackoverflow.com") page_html = page_origin.read() page_origin.close() print(page_html) The result is the full html code of https://stackoverflow.com. It works fine. Because it's too long enough, I don't paste it on. The problem is with BeautifulSoup. I add two lines' code to use BeautifulSoup to analyze the html. Strange things happened. It didn't work at all. from urllib.request import urlopen from bs4 import BeautifulSoup page_origin = urlopen("https://stackoverflow.com") page_html = page_origin.read() page_origin.close() # print(page_html) page_soup = BeautifulSoup(page_html, features="lxml", from_encoding="gbk") print(page_soup) The result is very very simple. &lt;!DOCTYPE html&gt; &lt;html class="html__responsive"&gt; &lt;head&gt; &lt;title&gt; Stack Overflow - Where Developers Learn, Share, &amp;amp; Build Careers &lt;/title&gt; &lt;link href="https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico?v=4f32ecc8f43d" rel="shortcut icon"/&gt; &lt;link href="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a" rel="apple-touch-icon image_src"/&gt; &lt;link href="/opensearch.xml" rel="search" title="Stack Overflow" type="application/opensearchdescription+xml"/&gt; &lt;/head&gt; &lt;/html&gt; It's not the full code of html and I can't analyze it at all. Please help me, I debug it for too much time. Thanks.
has answer: http://stackoverflow.com/a/52596137
type: UnansweredQuestion
tagged with: web-scraping
type: Question
has title: BeautifulSoup can't get all source code of the page, only a little lines
score: 0
answer count: 1
tagged with: beautifulsoup
tagged with: python

http://stackoverflow.com/a/52729570
downvote count: 2
answers question: http://stackoverflow.com/q/52729452
score: -2
has body: You have to modify your DATABASES dict in project settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'usr', 'PASSWORD': 'pwd', 'HOST': 'host.cloudapp.azure.com', 'PORT': 'your_port', }
upvote count: 0
has comment: http://stackoverflow.com/comment/92384330
type: Answer

http://stackoverflow.com/q/52713314
has body: as per the title, how to find list length of sublist that made from list and int. For example, give a list ListNo=[[6,2,5],[3,10],4,1] it should return LengthSubList 3,2,1,1. I make the following code, LengthSubList=[len(x) for x in ListNo] But, compiler give the following error object of type 'int' has no len() May I know what I do wrong? Thanks in advance
tagged with: python
type: AnsweredQuestion
has title: Find list length of sublist that made from list and int
upvote count: 1
accepted answer: http://stackoverflow.com/a/52713328
downvote count: 1
type: Question
tagged with: variable-length
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52713333
has answer: http://stackoverflow.com/a/52713333
favorite count: 0
has answer: http://stackoverflow.com/a/52713328
tagged with: compiler-errors

http://stackoverflow.com/comment/92402769
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52737631
type: QuestionComment
has text: @Sam: Can you explain what do you mean by n is independent of B. The above examples you gave can be solved by the solution posted in link 2. Can you post an example of when n is not equal to B

http://stackoverflow.com/comment/92365011
has text: What error are you getting? Post the complete stack trace, if possible
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52717470
score: 0

http://stackoverflow.com/comment/92215677
type: AnswerComment
comment on: http://stackoverflow.com/a/52641370
has text: So, the equivalent without `with` would be by replacing `with` with `set` and deleting `endwith` also
type: Comment
score: 0

http://stackoverflow.com/q/52629222
has comment: http://stackoverflow.com/comment/92191946
has answer: http://stackoverflow.com/a/52629774
has answer: http://stackoverflow.com/a/52629473
accepted answer: http://stackoverflow.com/a/52629473
has comment: http://stackoverflow.com/comment/92192058
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/10062954
has comment: http://stackoverflow.com/comment/92191974
score: 4
upvote count: 4
duplicate of: http://stackoverflow.com/q/19549634
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/92192096
has comment: http://stackoverflow.com/comment/92191943
has comment: http://stackoverflow.com/comment/92192013
possible better answer: http://stackoverflow.com/a/52629774
tagged with: python
linked to: http://stackoverflow.com/q/19549634
has body: I have a numpy array full of integers, let's say [[1,2],[3,4]] I want to get a binary array containing 1 if the element satisfies belongs to a list, and 0 otherwise. If I write condition = arr == 2 I get [[false, true], [false, false]] which is what I want. But what if I want to keep the elements 2 and 3 ? I tried condition = arr in [2,3] but it doesn't work, I get a ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I would like to do that for any possible list. Is there any efficient way to do that? I know how to do it brutally, but I'm need to be efficient. Thank you very much!
has title: Get elements of a numpy array that satisfy some condition
type: AnsweredQuestion

http://stackoverflow.com/q/52598720
has comment: http://stackoverflow.com/comment/92168631
duplicate of: http://stackoverflow.com/q/51578145
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52598916
upvote count: 3
type: Question
has title: python type hinting, get the type inside a container type
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/48572831
has body: Lets say I have a type hinted List[int], how do I programmatically get the type inside the container? from typing import List x = List[int] The container is of type List, but how I get what's inside that (int), is there a python api for it?
accepted answer: http://stackoverflow.com/a/52598916
duplicate of: http://stackoverflow.com/q/48572831
linked to: http://stackoverflow.com/q/51578145
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92168606

http://stackoverflow.com/a/52652204
answers question: http://stackoverflow.com/q/52651741
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92261061
has comment: http://stackoverflow.com/comment/92266536
has body: The system Python and Anaconda Python interpreters should not come into conflict. The motivation for this lies with virtual environmnets. If you want to use the modules in your anaconda python, you don't necessarily need to execute from the anaconda prompt. To do this (as in how I would do this), you will need to determine the filepath of your anaconda python instance. You can set that path as your default by modifying your $PATH (see related post) environment variable. If you don't want to set it as your default, but just use for some scripts, you can always call the C:\path\to\anaconda\env\python.exe to execute whatever script. If you do this, might be worth setting as an environment variable of its own to make calling easier (something like $CONDA_PYTHON). There are other ways to execute such as setting the shebang line in the script directly, but this isn't supported on all versions of windows and python. More details on that can be found here. Hope this helps.
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52651741

http://stackoverflow.com/comment/92236443
comment on: http://stackoverflow.com/a/52651442
has text: If you want the raw html in table format, you can save the styler to a variable then call `.render()` on it to output the table, as found [here](https://stackoverflow.com/questions/40421893/how-do-i-use-pandas-dataframe-style)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92193149
comment on: http://stackoverflow.com/q/52625544
score: 0
has text: See https://stackoverflow.com/q/51146054/901925
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92396653
score: 0
has text: @PM2Ring correct, thanks. But even if it didn't short-circuit, it would still behave the same. We have this [mechanism in C as well](https://stackoverflow.com/questions/26716255/why-does-this-program-print-forked-4-times/26716300#26716300), but that's beside the point.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52735770

import
type: Tag
tags question: http://stackoverflow.com/q/52694261
tag name: import
tags question: http://stackoverflow.com/q/52624531
tags question: http://stackoverflow.com/q/52681133
tags question: http://stackoverflow.com/q/52618450
tags question: http://stackoverflow.com/q/52659755
tags question: http://stackoverflow.com/q/52654136
tags question: http://stackoverflow.com/q/52590597
tags question: http://stackoverflow.com/q/52611754
tags question: http://stackoverflow.com/q/52727746
tags question: http://stackoverflow.com/q/52641676
tags question: http://stackoverflow.com/q/52616803

http://stackoverflow.com/comment/92414033
type: QuestionComment
comment on: http://stackoverflow.com/q/52742370
has text: If you used pip to install packages that can be installed with conda (like scipy), then you most probably corrupted your Anaconda installation and you have to reinstall it. That's because pip and conda packages are not compatible.
score: 0
type: Comment

http://stackoverflow.com/comment/92353139
comment on: http://stackoverflow.com/q/52713631
score: 0
type: QuestionComment
type: Comment
has text: @a_k_v the `group` is a mirror of `name` and `code`.

http://stackoverflow.com/comment/92138105
score: 0
type: Comment
type: QuestionComment
has text: Should `[1, 2, 1, 2, 1]` match? If yes, then you would want to change "different from the first 3" to just "different from the 3". If no, then you would want to change "check if 3 of these integers" to "check if the first 3 integers".
comment on: http://stackoverflow.com/q/52601676

http://stackoverflow.com/a/52692340
has body: An upgrade to Bokeh version 0.13.0 solved the issue.
score: 2
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52674515
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52674515
type: Answer

http://stackoverflow.com/comment/92406288
comment on: http://stackoverflow.com/a/52738737
has text: I guess @jezrael has answered your question.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92205882
type: AnswerComment
comment on: http://stackoverflow.com/a/52636226
type: Comment
score: 0
has text: @JLuxton the one that i use is much bigger, i just practised with small one =)

http://stackoverflow.com/comment/92226163
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52646581
type: Comment
has text: @depperm I don't really understand your question, your example is part of the possibilities I detailed

http://stackoverflow.com/comment/92163578
score: 0
type: Comment
type: QuestionComment
has text: Sorry, what about `request.data`?
comment on: http://stackoverflow.com/q/52607950

http://stackoverflow.com/a/52696804
upvote count: 3
has body: You can use zip() to join the list elements and a list comprehension to create the resulting list: list1 = [4,1,3] list2 = [2,5,2] list1_greater_list2_value = [a &gt; b for a,b in zip(list1,list2)] print ("list1-value greater then list2-value:", list1_greater_list2_value) Output: list1-value greater then list2-value: [True, False, True] This does the same work as a normal loop - but looks more pythonic.
type: Answer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/52696711
answers question: http://stackoverflow.com/q/52696711
type: AcceptedAnswer

http://stackoverflow.com/a/52664721
has comment: http://stackoverflow.com/comment/92262294
has comment: http://stackoverflow.com/comment/92353152
has comment: http://stackoverflow.com/comment/92259797
type: Answer
downvote count: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/92259986
score: 2
has body: I don't see why you don't wanna use .replace() but here's an edit s = "foo bar baz" result = "" for i in s.split(): if i == "foo": i = "chocolate" result += i print(result) # "chocolate bar baz" I however strongly recommend to use str.replace(), I mean it's in the standard library, if you don't want to use it then why using for or list() or even print()?
answers question: http://stackoverflow.com/q/52664689

http://stackoverflow.com/q/52741194
linked to: http://stackoverflow.com/q/52741046
score: 1
linked to: http://stackoverflow.com/q/52741039
has body: I have been working with python and scrapy for the past week using the following tutorial: https://realpython.com/web-scraping-with-scrapy-and-mongodb/ What this tutorial does is it goes through scraping the top questions and their urls on stackoverflow with the scrapy web crawler then stores it into a mongoDB database and collection. I'm trying to adapt what has been done in the tutorial to scrape and store multiple items into multiple collections for the same mongoDB database and then export it in CSV format, I've figured out how to do most of it but i'm having trouble with the "xpaths" which scrapy uses to search for specified items on the web page, to be more spesific I've figured out how to do the pipleline to mongodb and the storing multiple collections as well as changing the collection names based on the name of the item that is being scraped but I cannot get the "spiders" working specifically the xpaths or to my understanding the problem lies with the xpaths being wrong. I have no prior experience with scrapy and i've done days of research trying to figure out how to do the xpaths but I can't seem to get it working. The page i'm trying to scrape : https://stackoverflow.com/ The spider for question titles and urls that is working as intended : from scrapy import Spider from scrapy.selector import Selector from stack.items import QuestionItem class QuestionSpider(Spider): name = "questions" allowed_domains = ["stackoverflow.com"] start_urls = [ "http://stackoverflow.com/questions?pagesize=50&amp;sort=newest", ] def parse(self, response): questions = Selector(response).xpath('//div[@class="summary"]/h3') for question in questions: item = QuestionItem() item['title'] = question.xpath( 'a[@class="question-hyperlink"]/text()').extract()[0] item['url'] = question.xpath( 'a[@class="question-hyperlink"]/@href').extract()[0] yield item The spider for number of answers, votes and views that is not working as intended : from scrapy import Spider from scrapy.selector im…
tagged with: web-scraping
tagged with: scrapy
linked to: http://stackoverflow.com/q/52741029
linked to: http://stackoverflow.com/q/52741038
linked to: http://stackoverflow.com/q/52741023
type: Question
tagged with: mongodb
accepted answer: http://stackoverflow.com/a/52742371
linked to: http://stackoverflow.com/q/52741041
linked to: http://stackoverflow.com/q/52741015
linked to: http://stackoverflow.com/q/52741010
has answer: http://stackoverflow.com/a/52742371
linked to: http://stackoverflow.com/q/52741021
linked to: http://stackoverflow.com/q/52741016
answer count: 1
downvote count: 0
has title: XPaths with Scrapy and Python, can't get the XPaths working correctly
has comment: http://stackoverflow.com/comment/92407389
has comment: http://stackoverflow.com/comment/92409244
linked to: http://stackoverflow.com/q/52741013
favorite count: 0
tagged with: xpath
linked to: http://stackoverflow.com/q/52741043
has comment: http://stackoverflow.com/comment/92407514
linked to: http://stackoverflow.com/q/52741027
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/52741031
linked to: http://stackoverflow.com/q/52741028
linked to: http://stackoverflow.com/q/52741045
type: AnsweredQuestion

http://stackoverflow.com/q/52730668
tagged with: python
has title: Concatenating multiple images into one
has body: This function receives a list of numpy arrays that consist of cropped parts of an image. The crops are all the same size, except for the right-most and bottom-most images which might be of smaller size. predictions[2] would return the 3rd sub-image that was cropped from the original image. Each crop is a numpy array. There are WxH crops, enumerated from left to right, top to bottom (so if there are 4 sub-images constituting the width, the 5th image in predictions would be the first sub-image on the left from the 2nd row of sub-images). crops contains the necessary information to find number of horizontal and vertical images that will constitute the reconstructed images. crops[2][3] will contain the 3rd from the top, 4th from the left image cropped. The images contained by crops are of smaller dimension than the ones in predictions (I am basically making a model that increases the resolution of images). The reconstructed image if from the images in predictions, arranged in the same order as the ones in crops. def reconstruct(predictions, crops): if len(crops) != 0: print("use crops") # TODO: properly extract the size of the full image width_length = 0 height_length = 0 full_image = np.empty(shape=(height_length, width_length)) print(full_image.shape) # TODO: properly merge the crops back into a single image for height in range(len(predictions[0])): for width in range(len(predictions)): # concatenate here print(height, width) return full_image I was going to use numpy.concatenate, but according to other answers I've seen on SO it wouldn't be an efficient way of doing it (apparently numpy will just recreate a new variable in memory, copy the old one, and add the new data, etc.). So now I'm left wondering how to properly merge my multiple images into a single image. The current idea I was going for was to create a python list of the proper shape and progressively fill it with each numpy array's data, but even that I'm not sure if it's the proper idea. Here is more or le…
linked to: http://stackoverflow.com/q/14822184
score: 1
has answer: http://stackoverflow.com/a/52733370
upvote count: 1
type: AnsweredQuestion
tagged with: image
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52733370
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/52462058
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/52728174
downvote count: 0
answers question: http://stackoverflow.com/q/52715217
type: Answer
accepted answer of: http://stackoverflow.com/q/52715217
upvote count: 3
has body: There's no way to do this, because objects in GCS are immutable. From https://cloud.google.com/storage/docs/key-terms#immutability: Objects are immutable, which means that an uploaded object cannot change throughout its storage lifetime. An object's storage lifetime is the time between successful object creation (upload) and successful object deletion. In practice, this means that you cannot make incremental changes to objects, such as append operations or truncate operations. However, it is possible to overwrite objects that are stored in Cloud Storage, and doing so happens atomically — until the new upload completes the old version of the object will be served to readers, and after the upload completes the new version of the object will be served to readers. So a single overwrite operation simply marks the end of one immutable object's lifetime and the beginning of a new immutable object's lifetime.
score: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/92371138
type: QuestionComment
comment on: http://stackoverflow.com/q/52722315
has text: Have you imported sql functions as `from pyspark.sql.functions import *`? If so, change it to `import pyspark.sql.functions as F`. Check my similar [answer](https://stackoverflow.com/questions/52557734/python-round-function-issues-with-pyspark/52558189#52558189).
score: 0
type: Comment

cryptography
tag name: cryptography
tags question: http://stackoverflow.com/q/52714024
type: Tag
tags question: http://stackoverflow.com/q/52614720
tags question: http://stackoverflow.com/q/52686732
tags question: http://stackoverflow.com/q/52685218

http://stackoverflow.com/a/52737827
has body: You can also do that like this: flist = ['0.png','10.png', '3.png', '4.png', '100.png'] flist.sort(key=lambda x: '{0:0&gt;8}'.format(x)) print(flist)
downvote count: 0
answers question: http://stackoverflow.com/q/52737587
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/52718192
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92362111
downvote count: 1
has comment: http://stackoverflow.com/comment/92361960
has comment: http://stackoverflow.com/comment/92362254
score: -1
has comment: http://stackoverflow.com/comment/92362447
type: Question
tagged with: http://stackoverflow.com/tag/r
has title: Filtering while summarizing in python
answer count: 2
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/68123390
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/92362275
favorite count: 0
has comment: http://stackoverflow.com/comment/92361987
has comment: http://stackoverflow.com/comment/92362359
tagged with: python
tagged with: dplyr
has answer: http://stackoverflow.com/a/52718545
has comment: http://stackoverflow.com/comment/92362546
has body: I am an R user currently learning python. Usually, I use dplyr to group by and summarize my data. For e.g., data1 %&gt;% dplyr::group_by(city) %&gt;% dplyr::summarize(unique_customers = n_distinct(user_id, na.rm = TRUE), converted_customers = n_distinct(user_id[type == "CONVERTED"], na.rm = TRUE)) %&gt;% data.frame() I have been able to achieve the group_by and the unique_customers, but I am having some trouble putting the condition type == "CONVERTED" in python. How do I do this? Edit: My python code as it stands now: data1.fillna(method = "ffill").groupby("city").agg({"user_id": "nunique"})

http://stackoverflow.com/q/52606331
has title: Creating pandas column from two columns of strings contains NAs
has body: I have two columns containing strings and NAs and I want to combine them into 1. I feel this should be fairly simple but cannot seem to get it to work or find the answer on here. Below is the result I am after. S1 S2 S A Nan A A Nan A A Nan A A Nan A Nan C C Nan C C Nan C C Nan C C Nan Nan Nan Nan Nan Nan Nan Nan Nan B Nan B B Nan B B Nan B B Nan B B Nan B I thought df['S'] = df['S1']+ df['S2'] would work but no. Really feel like there will be an obvious fix, thanks in advance.
duplicate of: http://stackoverflow.com/q/34989341
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52606356
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52606356
linked to: http://stackoverflow.com/q/34989341
type: Question

http://stackoverflow.com/comment/92354633
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52713809
has text: i am getting my text in command prompt but i want to save a file in scroll area widget but i don't know how to save a file in scroll area
score: 0

http://stackoverflow.com/comment/92163811
comment on: http://stackoverflow.com/q/52614688
score: 0
type: Comment
type: QuestionComment
has text: The `/` directory normally has permissions like `drwxr-xr-x 24 root root`.

http://stackoverflow.com/comment/92383199
type: QuestionComment
has text: Sorry for the late update, my first post here.
comment on: http://stackoverflow.com/q/52728538
score: 0
type: Comment

http://stackoverflow.com/q/52700621
linked to: http://stackoverflow.com/q/37874838
linked to: http://stackoverflow.com/q/38694111
linked to: http://stackoverflow.com/q/46725323
has comment: http://stackoverflow.com/comment/92894249
upvote count: 15
possible better answer: http://stackoverflow.com/a/52956563
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/92805292
has comment: http://stackoverflow.com/comment/92805345
accepted answer: http://stackoverflow.com/a/53055899
has comment: http://stackoverflow.com/comment/92805848
type: Question
linked to: http://stackoverflow.com/q/36610290
has comment: http://stackoverflow.com/comment/92805268
tagged with: python
has body: EDIT2: Github link below contains possible solutions to the problem of calling TF model from process. They include eager execution and dedicated server process, serving TF model predictions via http requests. I wonder if with custom server and requests I win any time compared to initializing global variables each time and calling tf.train.Server, but it seems to be more elegant way. I will investigate memory leak, and if it is gone, close this question. EDIT: Added simple reproducible example of the problem: https://github.com/hcl14/Tensorflow-server-launched-from-child-process Background: I am running Tensorflow server, and connecting to it from 'forked' processes. Creating (and destroying) processes dynamically is essential for me - I moved highly loaded part of code there because of a weird memory leak, not visible to Python profilers (threads do not solve the issue). Therefore, I want processes to be initialized fast and immediately start working. Memory is freed only when process is destroyed. Doing experiments, I found a solution when loaded model and graph are saved into global variable, then taken by child process (which uses 'fork' mode by default) and then server is called. Problem: The strange thing for me is that, after loading keras models, I cannot lock graph which I do not expect to modify, and I need to run tf.global_variables_initializer() each time I open new session in child process. However, dummy run in the main flow without any session creation works Ok. I know that in this case tensorflow uses default session, but all the variables on a graph should be initialized after model run, so I expected new session to work Ok with previously defined graph. Thus, I think that modifying model makes Python to pickle a lot to the child process ('fork' mode), which creates computational and memory overhead. Please, excuse me for a lot of code. The model I use is legacy and black box for me, so it is possible that my problem is related to it. Tensorflow vers…
favorite count: 0
score: 15
has comment: http://stackoverflow.com/comment/92966594
has title: Tensorflow server: I don't want to initialize global variables for every session
has comment: http://stackoverflow.com/comment/92805696
answer count: 2
has comment: http://stackoverflow.com/comment/92803890
has comment: http://stackoverflow.com/comment/92805266
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/92782826
has comment: http://stackoverflow.com/comment/92805500
has comment: http://stackoverflow.com/comment/92805462
has answer: http://stackoverflow.com/a/53055899
has comment: http://stackoverflow.com/comment/92805062
has comment: http://stackoverflow.com/comment/92952438
has answer: http://stackoverflow.com/a/52956563

http://stackoverflow.com/q/52705347
favorite count: 0
type: Question
tagged with: python
tagged with: google-authenticator
linked to: http://stackoverflow.com/q/34520928
tagged with: one-time-password
answer count: 2
upvote count: 1
has body: I've been trying to use OtpSharp along with Google Authenticator in an application I'm developing. However, I don't understand why the code produced by OtpSharp does not match that of Google Authenticator. I've even tried to correct the time input to OtpSharp according to my local OS without any luck. On another note, the pyotp library from python works just fine without any special effort. Here is the code I'm using: var bSharedKey = System.Text.Encoding.Unicode.GetBytes("TESTTESTTESTTEST"); //var correction = new TimeCorrection(DateTime.UtcNow.ToLocalTime()); //var totp = new Totp(bSharedKey, timeCorrection: correction); var totp = new Totp(bSharedKey); var realOtp = totp.ComputeTotp(); long timestep = 0; var OTPmatch = totp.VerifyTotp(passwords[1], out timestep);
tagged with: c#
has answer: http://stackoverflow.com/a/59872010
has title: OtpSharp not working with google authenticator
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52735335
downvote count: 0
score: 1

http://stackoverflow.com/comment/92181560
type: AnswerComment
score: 0
has text: He specified values should be the together. In your case, you are not considering the consecutive values.
type: Comment
comment on: http://stackoverflow.com/a/52623782

http://stackoverflow.com/a/52718151
answers question: http://stackoverflow.com/q/52709073
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52709073
has comment: http://stackoverflow.com/comment/92373941
has body: Here is how you can do it with tf.gather_nd: import tensorflow as tf # Input values A = tf.placeholder(tf.int32, [None, None, None]) B = tf.placeholder(tf.int32, [None, None]) # Make indices for first dimension of B idx = tf.range(tf.shape(B)[0], dtype=A.dtype)[tf.newaxis, :, tf.newaxis] # Tile first dimension indices to match the size of A idx = tf.tile(idx, (tf.shape(A)[0], 1, tf.shape(A)[2])) # Stack first dimension indices with A to complete index tensor idx = tf.stack([idx, A], axis=-1) # Make result gathering from B C = tf.gather_nd(B, idx) Here is an example, testing that the result matches your code: import tensorflow as tf import numpy as np # Non-TensorFlow implementation for result comparison A_value = np.random.randint(0, 4, size=(2, 4, 2)) B_value = np.random.randint(100, size=(4, 4)) C_value = np.empty(A_value.shape, dtype=B_value.dtype) for i in range(A_value.shape[0]): for j in range(A_value.shape[2]): for k in range(A_value.shape[1]): C_value[i][k][j] = B_value[k][A_value[i][k][j]] # TensorFlow implementation A = tf.placeholder(tf.int32, [None, None, None]) B = tf.placeholder(tf.int32, [None, None]) idx = tf.range(tf.shape(B)[0], dtype=A.dtype)[tf.newaxis, :, tf.newaxis] idx = tf.tile(idx, (tf.shape(A)[0], 1, tf.shape(A)[2])) idx = tf.stack([idx, A], axis=-1) C = tf.gather_nd(B, idx) # Check result with tf.Session() as sess: C_value_tf = sess.run(C, feed_dict={A: A_value, B: B_value}) print(np.all(np.equal(C_value_tf, C_value))) Output: True
type: AcceptedAnswer

http://stackoverflow.com/a/52663023
type: Answer
has body: Finding thread messages You need to use the conversations.history method to retrieve the parent message of a thread. And then the conversations.replies method to retrieve the thread including all thread messages for a parent message. You can detect a parent message by looking on the ts and thread_ts properties: When a message has a thread_ts value and it matches the same message's ts, the message is a thread parent. For more information check out the official documentation: Finding message threads in the wild Deleting thread messages You can delete a thread message the same way as with normal message using the chat.delete method.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52657092
score: 3
answers question: http://stackoverflow.com/q/52657092
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/q/52596100
type: AnsweredQuestion
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/92127085
has answer: http://stackoverflow.com/a/52596162
has body: I have two data frames, take the example below df1 userid| name 33| Paul 2 | jack 32| Ryan df2 userid| sport | song 79 | tennis | lovelies 33 | swimmin | Beatles 21 | boxing | stones how would I get a df3, where if the userids match between df1, and df2, I want to df3 to contain only those rows from df2 where they matched with df1 I don't think a JOIN is the answer here, because I want ONLY the rows from df2. not the rows from df1. Thanks!
has comment: http://stackoverflow.com/comment/92126879
has title: Get all rows from a dataframe, which have matching values from another data frame
tagged with: dataframe
tagged with: querying
accepted answer: http://stackoverflow.com/a/52596162
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/40342583
answer count: 1
duplicate of: http://stackoverflow.com/q/40342583
tagged with: python

http://stackoverflow.com/comment/92412882
comment on: http://stackoverflow.com/a/52744130
score: 0
type: AnswerComment
type: Comment
has text: Done but still same problem.

http://stackoverflow.com/comment/92387174
type: QuestionComment
score: 1
has text: If you want to use gevent you will need to use a [gevent based WSGI server](http://flask.pocoo.org/docs/0.12/deploying/wsgi-standalone/#gevent). The simple built-in development server will not run in a gevent loop.
comment on: http://stackoverflow.com/q/52730739
type: Comment

http://stackoverflow.com/q/52601444
accepted answer: http://stackoverflow.com/a/52601476
has title: Python how to validate user input with multiple acceptable options
downvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/92137220
has comment: http://stackoverflow.com/comment/92138005
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92137229
tagged with: python
has body: “C”, “c”, “coffee” or ANY combination of upper and lower case letters that correctly spells “coffee”, i.e., “Coffee”, “COFFEE”, “coffEE” are acceptable, if doesn't meet requirement program ends, or else the program continues.
linked to: http://stackoverflow.com/q/500864
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52601476

http://stackoverflow.com/a/52638270
type: Answer
has body: yhat is your estimate for a given observation. You can obtain all of your estimates simultaneously using the dot product via X.dot(betas). Your sum square of errors would be the following (note the correction to version you gave: you need to square the difference, i.e. square the errors): y_hat = X.dot(betas) errors = y - y_hat sse = (errors ** 2).sum() Your total sum of squares: tss = ((y - y.mean()) ** 2).sum() And the resulting R-squared (coefficient of determination): r2 = 1 - sse / tss Also, I wouldn't use int as a variable name to avoid clobbering the built in int function (just call it ones or const instead).
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/92228380
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52637971
accepted answer of: http://stackoverflow.com/q/52637971

http://stackoverflow.com/comment/92343868
type: Comment
type: QuestionComment
has text: @martineau added code to be runnable. thanks!
score: 1
comment on: http://stackoverflow.com/q/52708418

http://stackoverflow.com/comment/92343800
has text: What does your code currently print, and how is it different from what you want?
comment on: http://stackoverflow.com/q/52707117
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52724627
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52725059
accepted answer: http://stackoverflow.com/a/52725059
linked to: http://stackoverflow.com/q/44574551
has title: Match two consecutive sequences with fixed overall length
has comment: http://stackoverflow.com/comment/92385737
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52724986
linked to: http://stackoverflow.com/q/29283628
has body: I would like to match all strings that start with 1 to 4 (lower case) letters followed by 1 to 4 digits and the overall length of that sequence (letters + digits) should be 5. The letters and digits must not intermingle. The actual string however is much longer and this 5-sequence is not followed by any distinct word boundary (it can be followed by [a-z0-9] for example). The regex in question however should only be concerned with the first 5 characters. For example: Positive matches: a1111, aa111, abc12def, abc12345, ... Negative matches: a1a1a, aa11a, aa11, 1aaaa x, ... So I would need something like ^([a-z]{1,4})[0-9]{5 - length of \1}. This question seems to be slightly related but I couldn't figure out how to make the length of the second group dependent on the first. This answer suggests to perform a lookahead on all the possible characters but doesn't prevent intermingling. I don't want to perform a match on only the first five characters of the string (and then check the length of the actual match), since I would like to augment this regex in order to match the remainder of the string with some other pattern. The length of the groups is small for the sake of the example but they are actually much longer (so manually specifying the various combinations is not an option; auto-generating a regex that contains all the combinations makes me worry about performance). Specifically I am using Python 3.6 but I am happy about solutions considering other regex flavors as well.
possible better answer: http://stackoverflow.com/a/52724986
score: 0
has comment: http://stackoverflow.com/comment/92384981
has comment: http://stackoverflow.com/comment/92375249
tagged with: regex
tagged with: python

http://stackoverflow.com/a/56576264
has body: I got this error when creating a client for S3 but AFAIK it is the same issue. There's non-thread-safe code that is used in the process of creating a client: if name in self._deferred: factory = self._deferred[name] self._components[name] = factory() # Only delete the component from the deferred dict after # successfully creating the object from the factory as well as # injecting the instantiated value into the _components dict. del self._deferred[name] (from botocore/session.py in the get_component method - that is the code that raises the KeyError when trying to delete a key that was deleted by a different thread) Locking the client creation solved it for me (as suggested in https://github.com/boto/boto3/pull/806)
type: Answer
answers question: http://stackoverflow.com/q/52675027
score: 0

http://stackoverflow.com/comment/92436725
type: AnswerComment
type: Comment
has text: Great answer, but I have question to it. Would you then save the choices in the list chosenCoworker at the time of the event? or will I be able to go back and check at a later point what the values are of each choice?
comment on: http://stackoverflow.com/a/52728691
score: 0

http://stackoverflow.com/q/52712386
accepted answer: http://stackoverflow.com/a/52712617
downvote count: 0
has comment: http://stackoverflow.com/comment/92350918
possible better answer: http://stackoverflow.com/a/52712627
tagged with: pandas
has title: Given a DatetimeIndex and a collection of datetime-aware records, how to create a Pandas DataFrame?
has body: I've got a pre-defined DatetimeIndex and a list of tuples of this kind: (datetime, float, float, float). I need to create a Pandas DataFrame and populate it with the data from the list. Needless to say, the first element of each record (a tuple) defines its supposed position in the resulting DataFrame and not a value of a column, there are to be just 3 float columns in the resulting DataFrame. The records that don't have a matching element in the DatetimeIndex should be discarded (and I don't mind an error to be risen on such an occasion). Given the list of the tuples itself pd.DataFrame.from_records() treats every element of a tuple as a value of a column (and raises an error if I don't include the datetime column in the columns list). Given a dictionary defined as {r[0]: (r[1], r[2], r[3]) for r in rs} (where rs is the source list of the tuples) pd.DataFrame.from_records() returns a DataFrame where every value in every field of every column is NaN. I've also tried using lists instead of tuples ({r[0]: [r[1], r[2], r[3]] for r in rs}) but the result was the same. I've double-checked - the values in the source tuples are pretty much defined floats and there are no NaNs or Nones. Setting coerce_float doesn't change anything. UPDATE: I've also tried using a dictionary of dictionaries to specify column names according to the columns list ({r[0]: {'A': r[1], 'B': r[2], 'C': r[3]} for r in rs}) and the result is the same - all NaNs. UPDATE: Here goes an example: dts = [ datetime(2018, 1, 1, 0, 0, 0, 0, timezone.utc), datetime(2018, 1, 2, 0, 0, 0, 0, timezone.utc), datetime(2018, 1, 3, 0, 0, 0, 0, timezone.utc) ] dti = pd.DatetimeIndex(dts, tz=timezone.utc) rs = [ (datetime(2018, 1, 1, 0, 0, 0, 0, timezone.utc), 0.1, 0.2, 0.3), (datetime(2018, 1, 2, 0, 0, 0, 0, timezone.utc), 0.4, 0.5, 0.6), (datetime(2018, 1, 3, 0, 0, 0, 0, timezone.utc), 0.7, 0.8, 0.9) ] # ... dtf = pd.DataFrame.from_records(rs, index=dti, columns=['A', 'B', 'C'], coerce_float=True) print(dtf) should re…
favorite count: 0
linked to: http://stackoverflow.com/q/42196337
has comment: http://stackoverflow.com/comment/92351131
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52712617
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92350931
score: 1
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52712627

http://stackoverflow.com/q/52669880
has title: How to get datastore name/id column value
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/92279610
favorite count: 0
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/52730948
accepted answer: http://stackoverflow.com/a/52730948
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I am trying to get name/id column value for a datastore kind entity using next(iter(result)) below but looking for other ways to do it. I tried this way result[0]['id'] but it did not work . Any suggestions? query = self.ds.query(kind=self.__tablename__) query.add_filter('email', '=', self.email) result = query.fetch(1) id = next(iter(result))
type: Question
tagged with: google-cloud-datastore

http://stackoverflow.com/comment/92225978
comment on: http://stackoverflow.com/q/52646902
type: Comment
type: QuestionComment
score: 0
has text: related https://stackoverflow.com/a/19122532/6360875

http://stackoverflow.com/a/52606806
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52606775
upvote count: 2
answers question: http://stackoverflow.com/q/52606775
type: AcceptedAnswer
has body: Better here is create dictionary of DataFrames: list_of_strings = ['string1', 'string2', 'string3', 'string4'] list_of_dfs = [df1, df2, df3, df4] d = dict(zip(list_of_strings, list_of_dfs)) And tne select by keys: print (d['string1']) print (d['string2'])

http://stackoverflow.com/comment/92347290
has text: You should include the error log in the question. If you don't log errors, then you should start doing so.
comment on: http://stackoverflow.com/q/52710305
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52721643
has title: jsonschema check if key exists
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52722259
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/134051645
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/52722259
linked to: http://stackoverflow.com/q/56299562
tagged with: jsonschema
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: I have JSON: {"price" : 12} and schema: schema = { "type" : "object", "properties" : { "price" : {"type" : "number"} }, } It works to validate the type of value validate({"price" : 12}, schema). However JSONs like: {"price_blabla" : 'blabla'} are also considered valid. How should I change schema so it would check that a JSON contains the particular keys? Basically I have a lot of JSONs and I need to get all that have a certain pattern.
type: Question

http://stackoverflow.com/comment/92406636
type: Comment
type: QuestionComment
has text: where does this "laboratory" thing comes from ? It's not mentionned anywhere in your snippets.
score: 0
comment on: http://stackoverflow.com/q/52740918

http://stackoverflow.com/comment/99380250
type: Comment
has text: `temp` does work for outputs containing wildcards.
comment on: http://stackoverflow.com/q/52636101
score: 0
type: QuestionComment

http://stackoverflow.com/q/52728531
has title: Python, importing custom libraries from subdirectory, working in IDE, not in shell
score: 1
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/2632199
has comment: http://stackoverflow.com/comment/92382568
type: Question
has comment: http://stackoverflow.com/comment/92382745
has body: For sake of organization, I've placed all my custom libraries into a subdirectory. When I run my script file in the spyder IDE, it imports everything as intended, and runs smoothly, but when I execute the script from shell, it fails to import. (I have created an __init__.py file in the modules/ directory). Also, this is being run on Linux. Here is my code: import os dirpath = os.path.dirname(__file__) sys.path.append('{}/modules/'.format(dirpath)) #custom libraries in dirpath/modules/ import data_pull import features import create_listings example = data_pull.mp(pool) data = features.generate(example) Shell output: Traceback (most recent call last): File "data_manager.py", line 15, in import data_pull ModuleNotFoundError: No module named 'data_pull'
downvote count: 0

http://stackoverflow.com/comment/92160632
score: 0
type: QuestionComment
has text: how can I find the old version?
type: Comment
comment on: http://stackoverflow.com/q/52612693

apache-drill
tags question: http://stackoverflow.com/q/52595623
tag name: apache-drill
type: Tag

flash
tags question: http://stackoverflow.com/q/52626163
tag name: flash
type: Tag

http://stackoverflow.com/comment/92175156
type: AnswerComment
comment on: http://stackoverflow.com/a/52597350
type: Comment
has text: That helped me, I finally wrote it all yesterday
score: 0

openresty
tag name: openresty
type: Tag
tags question: http://stackoverflow.com/q/52714103

http://stackoverflow.com/comment/119653754
has text: Is you K8s cluster having troubling pulling the container image?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52674264

powerpoint
tags question: http://stackoverflow.com/q/52728142
tag name: powerpoint
type: Tag

http://stackoverflow.com/a/52646252
score: 1
has comment: http://stackoverflow.com/comment/92225913
has comment: http://stackoverflow.com/comment/92225820
has body: If you are happy using a 3rd party library, you can use Pandas: import pandas as pd df = pd.DataFrame(my_list) df['Job'] = df['Age'].astype(int).le(60).astype(int).astype(str) res = df.to_dict(orient='records') [{'Age': '50', 'Job': '1', 'Name': 'John'}, {'Age': '70', 'Job': '0', 'Name': 'Sara'}] There are specific reasons why this is preferable. You are using vectorised operations on Boolean arrays rather than a ternary statement in a loop. For big data workflows, this should be time and memory efficient.
has comment: http://stackoverflow.com/comment/92224838
answers question: http://stackoverflow.com/q/52646124
has comment: http://stackoverflow.com/comment/92224642
has comment: http://stackoverflow.com/comment/92224474
type: Answer
has comment: http://stackoverflow.com/comment/92224524
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/92224719

http://stackoverflow.com/q/52741739
has title: Is it possible to make a web scraper use a plugin (in Chrome's extension bar)?
tagged with: python
tagged with: plugins
type: AnsweredQuestion
tagged with: web-scraping
tagged with: web-crawler
type: Question
tagged with: automation
has answer: http://stackoverflow.com/a/52742257
accepted answer: http://stackoverflow.com/a/52742257
linked to: http://stackoverflow.com/q/16511384
score: 0
has body: TO be specific, I want to make a Python web crawler that uses a plugin on Chrome called "Adapt Prospector," which allows you to find people's emails once you land on their linkedin page. Here is an example of what I mean: https://i.postimg.cc/DyxWzxWJ/example_pic.png You first go on the person's linkedin page, then click the plugin logo on Chrome's extension bar, then the plugin will show you the linkedin profile's email (if there is one). Basically, I want to create a program that goes to a person's linkedin page, then clicks the plugin logo on the extension bar, then scrapes the data the plugin is showing. I definitely know how to do the first part, but I'm not sure if the last 2 parts are possible. I searched extensively on if its possible to make a web scraper that uses a plugin, but I haven't found any "yes" or "no" answers to this.
answer count: 1

http://stackoverflow.com/comment/92346019
type: AnswerComment
comment on: http://stackoverflow.com/a/52674640
has text: Unfortunately this only works for that particular match, and not with the rest of the 15=< character slices of the mixed up url encoded string I am trying to reassemble. I chose to write a custom brute force approach to comparing the beginning or end of the template string `s1` to the target string `s2`. I will take a look at `SequenceMatcher.get_matching_blocks()` and see if there a bug fix for this issue missing substrings issue could be implemented.
type: Comment
score: 0

http://stackoverflow.com/comment/92235159
type: QuestionComment
comment on: http://stackoverflow.com/q/52651178
has text: I just updated the main post, so you can have more informations ! Thank you again !
score: 0
type: Comment

http://stackoverflow.com/a/55013458
downvote count: 0
has body: The global "salt" you specify in SECURITY_PASSWORD_SALT is combined with the unique salt generated for each password that gets created. That combined value is then used to salt the password when it gets hashed. So yes, you do need to set this, it's not a spurious error. (Others have noted that it's quite confusing to refer to this as a salt, when that strongly implies that the value in this variable is going to be used to salt the password for every user. Fortunately, that's not what happens.) Here are some options for generating a random string.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52662675
score: 2
has comment: http://stackoverflow.com/comment/100957521
has comment: http://stackoverflow.com/comment/100946025

http://stackoverflow.com/comment/104344184
type: Comment
comment on: http://stackoverflow.com/a/56443793
score: 14
type: AnswerComment
has text: On jupyter lab I get the error `Javascript Error: IPython is not defined`

http://stackoverflow.com/a/52722886
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52722677
answers question: http://stackoverflow.com/q/52722677
downvote count: 0
score: 1
has body: Your problem is that you define the variable ednotes_name in your config to be Notes therefore only the files having Notes after three _ are read by your script.

http://stackoverflow.com/q/52654607
type: AnsweredQuestion
downvote count: 0
has body: I have an array of strings, for example import numpy as np foo = np.array( [b'2014-04-05', b'2014-04-06', b'2014-04-07'] ) To check for the data type of the array, I print it with print( foo.dtype ) which results in |S10. Obviously, it consists of strings of length 10. I want to convert it into NumPy's datetime64 type. More precisely, I want to change the data type of the array without looping through a for-loop and copying it element-wise into a new array (the real array is actually very large). Naive as I am, I thought the following might work: [ np.datetime64(x) for x in foo ] Spoiler: it does not. Printing the data type of the array results in the same output as before (i.e., |S10). Is there a memory efficient way to convert the data type of the existing array without the necessity of copying everything to a new array?
type: Question
tagged with: numpy
has title: Converting a NumPy array of strings to datetime
score: 5
tagged with: arrays
answer count: 1
favorite count: 0
upvote count: 5
has answer: http://stackoverflow.com/a/52654647
accepted answer: http://stackoverflow.com/a/52654647
tagged with: python

http://stackoverflow.com/q/52670057
has title: Get all values from Django QuerySet plus additional fields from a related model
upvote count: 4
answer count: 2
tagged with: django-queryset
downvote count: 0
favorite count: 0
has body: I was wondering if there is a shortcut to getting all fields from a Django model and only defining additional fields that are retrieved through a join (or multiple joins). Consider models like the following: class A(models.Model): text = models.CharField(max_length=10, blank=True) class B(models.Model): a = models.ForeignKey(A, null=True, on_delete=models.CASCADE) y = models.PositiveIntegerField(null=True) Now I can use the values() function like this B.objects.values('y', 'a__text') to get tuples containing the specified values from the B model and the actual field from the A model. If I only use B.objects.values() I only get tuples containing fields from the B model (i.e., y and the foreign key id a). Let's assume a scenario where B and A have many fields, and I am interested in all of those belonging to B but only in a single field from A. Manually specifying all the field names in the values() call would be possible, but tedious and error-prone. So is there a way to specify that I want all local fields, but only a (few) specific joined field(s)? Note: I'm currently using Django 1.11, but if a solution only works with a more recent version I am interested in that too.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52670136
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/52670205
score: 4

http://stackoverflow.com/q/52723479
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92372626
type: Question
has comment: http://stackoverflow.com/comment/92372731
has body: Here is my code to web scraping.I use concurrent.futures to speed it up.But there is a problem I don't know how to solve. import logging import json import requests import re from lxml import etree from concurrent.futures import ThreadPoolExecutor import time def chem960(cas_no = str(64173962),time_out=(10,20)): #logging.info("start chem960") try: r = requests.get("http://www.chem960.com/structure/sc{cas_no}".format(cas_no=cas_no),timeout=time_out) root = etree.HTML(r.text) selector = "/html/body/div[6]/div[2]/div[1]/div[2]/p[1]/text()" smiles_key = root.xpath(selector) smiles = smiles_key[1].strip() logging.info("finish chem960") return {"smiles":smiles,"source":"chem960"} except: logging.info("finish chem960") return {"source":"chem960"} def chemexper(cas_no = "2040906",time_out=(10,20)): #logging.info("start chemexper") try: url = "http://www.chemexper.com/searchResult.shtml?format=ccd2013%2Cccd&target=structure&options=brandqtyoffercrm&searchValue="+cas_no+"&searchTemplate=rn.value%3D%22%3F%22&Search=Search" start_html = requests.get(url,timeout=time_out).text #logging.info(start_html) index_link = re.findall(' ',start_html) index_link = index_link[0] index_html = requests.get(index_link,timeout=time_out).text #logging.info(index_html) final_url = re.findall('here',index_html) final_url = "http://newsearch.chemexper.com/"+final_url[0] final_html = requests.get(final_url,timeout=time_out).text #logging.info(final_html) root = etree.HTML(final_html) #InChI = root.xpath('/html/body/table[1]//tr[2]/td[1]/table//tr[1]/td/text()')[1].strip() InChIKey =root.xpath('/html/body/table[1]//tr[2]/td[1]/table//tr[2]/td/text()')[0] #logging.info("finish chemexper") return {"InChIKey":InChIKey,"source":"chemexper"} except: logging.info("finish chemexper") return {"source":"chemexper"} def ncbi(cas_no = "2040906",time_out=(10,20)): #logging.info("start ncbi") try: url = "https://www.ncbi.nlm.nih.gov/pccompound?term="+cas_no start_html = requests.get(url,timeout=time_out).text fi…
score: 0
answer count: 1
tagged with: python-3.x
has title: How to exit when I get any result from a thread pool in python?
has answer: http://stackoverflow.com/a/52723697
tagged with: python
accepted answer: http://stackoverflow.com/a/52723697

http://stackoverflow.com/comment/112029594
score: 0
type: Comment
has text: Actually, the two sets of lines that prevent tuple scores are [***(170:172)***](https://github.com/maxbachmann/rapidfuzz/blob/master/src/rapidfuzz/process.py#L170) and [***(189:191)***](https://github.com/maxbachmann/rapidfuzz/blob/master/src/rapidfuzz/process.py#L189) in [process.py](https://github.com/maxbachmann/rapidfuzz/blob/master/src/rapidfuzz/process.py). When dealing with identical scores, fuzzywuzzy does simply return the first one it finds within (what appears to be) an unordered iterable... Admittedly debatable.
comment on: http://stackoverflow.com/a/61371170
type: AnswerComment

http://stackoverflow.com/q/52594468
linked to: http://stackoverflow.com/q/52591657
tagged with: python
has comment: http://stackoverflow.com/comment/92435105
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52595261
accepted answer: http://stackoverflow.com/a/52595261
upvote count: 1
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/36177958
has comment: http://stackoverflow.com/comment/92124239
has body: I use the tf.data API for my models. For now I define the output of the tf.data iterator as input for my network. After I got rid of the feed_dict method, my performance increased significantly. Now I want to implement a validation set that runs at least after each training once. Is there a way to implement a validation run for tf.data or do I have to set a placeholder and manually switch the tf.datasets and use feed_dicts again? What is the recommended way for validation tests?
score: 1
has title: Tensorflow graph with multiple inputs wihtout tf.placeholder for validation
answer count: 1
downvote count: 0
tagged with: tensorflow-datasets
favorite count: 0

http://stackoverflow.com/comment/92151213
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52604824
score: 0
has text: Thanks, I tried stopping it now, did not matter. Same error: _Response status code does not indicate success: 400. _ I actually tried pushing an app I know does not exist, and the exact same thing happens... Could this indicate an error with the "connection" with Azure?

http://stackoverflow.com/comment/92174706
score: 0
has text: @ZarKha [cont.] having a widget only to create a layout that is established in another widget does not make sense, since the widget never gets it will show and therefore it will never be useful that in programming it implies spending of memory and time. If you have Qt Designer you will have seen that these elements are represented with lines but when they are executed they are not shown, the lines are a representation so that your organization is easily understood
comment on: http://stackoverflow.com/a/52617980
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92160199
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52612685
has text: @45Yoda, quote from [docs](https://pycryptodome.readthedocs.io/en/latest/src/introduction.html): "One must avoid having both PyCrypto and PyCryptodome installed at the same time, as they will interfere with each other."

elasticsearch
tags question: http://stackoverflow.com/q/52742943
tags question: http://stackoverflow.com/q/52677832
tags question: http://stackoverflow.com/q/52742306
type: Tag
tags question: http://stackoverflow.com/q/52738694
tags question: http://stackoverflow.com/q/52666528
tags question: http://stackoverflow.com/q/52739989
tags question: http://stackoverflow.com/q/52637098
tag name: elasticsearch
tags question: http://stackoverflow.com/q/52690078
tags question: http://stackoverflow.com/q/52598527

http://stackoverflow.com/q/52746826
has comment: http://stackoverflow.com/comment/92418492
has comment: http://stackoverflow.com/comment/92418408
score: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/92418322
has title: Rolling sum over an array in Python
has answer: http://stackoverflow.com/a/52747071
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/28288252
has body: I am given an array X and I am asked to return another array Y where y[t] = x[t] + x[t-1] and y[0] = 0 without using a for loop in Python. What I can think of is using rolling sum but I am not sure if this is the fastest way since I need to convert x into a dataframe/ a series for rolling to work. Is there a faster way to do that? Thanks! df = pd.DataFrame(X).rename(columns={0: 'X'}) df['Y'] = df['X'].rolling(2).sum().fillna(0) Y = df['Y'].values
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/52746865
tagged with: rolling-sum
favorite count: 0
answer count: 3
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52747091

http://stackoverflow.com/comment/95407527
type: AnswerComment
comment on: http://stackoverflow.com/a/53075836
score: 0
type: Comment
has text: @dankal444 glad it worked but this doesn't actually fix the root cause, which is your toco_from_protos shell command being set up incorrectly. This is just a hack.

http://stackoverflow.com/q/52736914
has comment: http://stackoverflow.com/comment/92398585
has body: I want to plot two different histograms in different plots but opening in same window. With the following code, I am getting two histogram in same plot. I could not get the histogram with subplot don't know where I went wrong. from matplotlib import pyplot as plt img = cv2.imread(f) img1 = cv2.imread('compressed_' + f) color = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img], [i], None, [256], [0, 256]) hist = cv2.calcHist([img1], [i], None, [256], [0, 256]) plt.plot(histr, color=col) plt.plot(hist, color=col) plt.xlim([0, 256]) plt.title('Original image') plt.show()
tagged with: python
has comment: http://stackoverflow.com/comment/92398629
tagged with: opencv
type: AnsweredQuestion
score: 1
has title: Plot two histogram in same window but in different plots
type: Question
has answer: http://stackoverflow.com/a/52737221
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52737221
has comment: http://stackoverflow.com/comment/92398848
has comment: http://stackoverflow.com/comment/92398707
upvote count: 2
has comment: http://stackoverflow.com/comment/92398762
linked to: http://stackoverflow.com/q/1358977
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/52647509
score: 0
has body: This is somewhat cheating as I use a regular expression with lookahead to verify the format digit{5}/digit{3}, then verify that there is at most one whitespace left and right of the / and then match an arbitrary number of digits and whitespace: \b(?:(?:(?=[\d\s]{6})(?=\d*\s\d*\/\d{3}\b))(\d*\s*\d*)\/(\d{3})|(?:\d{5}\/(?=[\d\s]{4}\b)(\d*\s*\d*)))\b This is not much better than simply enumerating the whitespace in all positions, sorry. Edit: Fixed the regexp to be a bit simpler and to allow floating matches against example string. ( Regex 101 )
type: Answer
answers question: http://stackoverflow.com/q/52646581

database
tags question: http://stackoverflow.com/q/52686407
tags question: http://stackoverflow.com/q/52649322
tags question: http://stackoverflow.com/q/52695632
type: Tag
tags question: http://stackoverflow.com/q/52744580
tags question: http://stackoverflow.com/q/52605666
tags question: http://stackoverflow.com/q/52695025
tags question: http://stackoverflow.com/q/52685016
tags question: http://stackoverflow.com/q/52598285
tags question: http://stackoverflow.com/q/52740009
tag name: database
tags question: http://stackoverflow.com/q/52609828
tags question: http://stackoverflow.com/q/52607737
tags question: http://stackoverflow.com/q/52729491
tags question: http://stackoverflow.com/q/52731437
tags question: http://stackoverflow.com/q/52664005
tags question: http://stackoverflow.com/q/52643775
tags question: http://stackoverflow.com/q/52705496

http://stackoverflow.com/comment/92287182
type: Comment
type: QuestionComment
has text: Unfortunately, the JSON library included with Python needs your JSON to actually be valid to work. You can check out https://docs.python.org/3.7/library/json.html and https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file should help you get started. You can use https://jsonlint.com/ to validate your JSON data.
comment on: http://stackoverflow.com/q/52672598
score: 0

binning
tags question: http://stackoverflow.com/q/52637106
tags question: http://stackoverflow.com/q/52647454
tags question: http://stackoverflow.com/q/52703172
tag name: binning
type: Tag

http://stackoverflow.com/q/52673285
possible better answer: http://stackoverflow.com/a/52674028
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92277266
tagged with: performance
downvote count: 0
linked to: http://stackoverflow.com/q/13331698
has comment: http://stackoverflow.com/comment/92276929
has comment: http://stackoverflow.com/comment/92278215
has comment: http://stackoverflow.com/comment/92277503
type: Question
tagged with: numpy
answer count: 2
score: 152
has comment: http://stackoverflow.com/comment/92340543
tagged with: arrays
has comment: http://stackoverflow.com/comment/92277175
has comment: http://stackoverflow.com/comment/92277396
has comment: http://stackoverflow.com/comment/92276962
has comment: http://stackoverflow.com/comment/92277108
has title: Performance of Pandas apply vs np.vectorize to create new column from existing columns
linked to: http://stackoverflow.com/q/26886653
has comment: http://stackoverflow.com/comment/92277187
upvote count: 152
has comment: http://stackoverflow.com/comment/92276713
tagged with: pandas
has answer: http://stackoverflow.com/a/52674448
linked to: http://stackoverflow.com/q/16353729
accepted answer: http://stackoverflow.com/a/52674448
favorite count: 0
has answer: http://stackoverflow.com/a/52674028
has comment: http://stackoverflow.com/comment/92277357
has comment: http://stackoverflow.com/comment/92277330
has body: I am using Pandas dataframes and want to create a new column as a function of existing columns. I have not seen a good discussion of the speed difference between df.apply() and np.vectorize(), so I thought I would ask here. The Pandas apply() function is slow. From what I measured (shown below in some experiments), using np.vectorize() is 25x faster (or more) than using the DataFrame function apply() , at least on my 2016 MacBook Pro. Is this an expected result, and why? For example, suppose I have the following dataframe with N rows: N = 10 A_list = np.random.randint(1, 100, N) B_list = np.random.randint(1, 100, N) df = pd.DataFrame({'A': A_list, 'B': B_list}) df.head() # A B # 0 78 50 # 1 23 91 # 2 55 62 # 3 82 64 # 4 99 80 Suppose further that I want to create a new column as a function of the two columns A and B. In the example below, I'll use a simple function divide(). To apply the function, I can use either df.apply() or np.vectorize(): def divide(a, b): if b == 0: return 0.0 return float(a)/b df['result'] = df.apply(lambda row: divide(row['A'], row['B']), axis=1) df['result2'] = np.vectorize(divide)(df['A'], df['B']) df.head() # A B result result2 # 0 78 50 1.560000 1.560000 # 1 23 91 0.252747 0.252747 # 2 55 62 0.887097 0.887097 # 3 82 64 1.281250 1.281250 # 4 99 80 1.237500 1.237500 If I increase N to real-world sizes like 1 million or more, then I observe that np.vectorize() is 25x faster or more than df.apply(). Below is some complete benchmarking code: import pandas as pd import numpy as np import time def divide(a, b): if b == 0: return 0.0 return float(a)/b for N in [1000, 10000, 100000, 1000000, 10000000]: print '' A_list = np.random.randint(1, 100, N) B_list = np.random.randint(1, 100, N) df = pd.DataFrame({'A': A_list, 'B': B_list}) start_epoch_sec = int(time.time()) df['result'] = df.apply(lambda row: divide(row['A'], row['B']), axis=1) end_epoch_sec = int(time.time()) result_apply = end_epoch_sec - start_epoch_sec start_epoch_sec = int(time.time(…
tagged with: python

http://stackoverflow.com/comment/92288546
has text: [This answer](https://stackoverflow.com/a/52353721/2099607) might give you a visual overview of how 1D convolution works.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52679712
type: Comment

http://stackoverflow.com/comment/92418701
comment on: http://stackoverflow.com/q/52747061
score: 0
type: QuestionComment
has text: Can you explain it more?
type: Comment

http://stackoverflow.com/comment/92128296
type: AnswerComment
has text: Your function `print_from_stream` instantiates a new `even_stream()` _object_ called `stream`. The _same_ object is then called again, which updates it's existing state and prints it.
comment on: http://stackoverflow.com/a/52596767
type: Comment
score: 0

http://stackoverflow.com/a/52743820
answers question: http://stackoverflow.com/q/52743329
has body: If all you want to do is replace K with M, then you can simply do either: 1) re.sub('K', 'M', original_text) 2) original_text.replace('K', 'M') Both will yield: context PQ-4662-33-M64C-C-DDxxx-Sxxxx If your requirements are more specific, and the input strings always follow a prescribed pattern: re.sub(r'(?&lt;=context [A-Z]{2}-\d{4}-\d{2}-)[A-Z]', 'M', original_text) Again yields: context PQ-4662-33-M64C-C-DDxxx-Sxxxx
score: 0
has comment: http://stackoverflow.com/comment/92413449
type: Answer

http://stackoverflow.com/comment/92237453
type: AnswerComment
score: 0
type: Comment
has text: @jedwards: I blanked when I thought I got the import wrong but you are correct.
comment on: http://stackoverflow.com/a/52652714

http://stackoverflow.com/a/52702350
upvote count: 1
answers question: http://stackoverflow.com/q/52701594
has body: You could leave the IDs in the X array, carry them through train_test_split but then not use them in fitting and predicting, for example: model.fit(X_train[:, 1:], y) model.predict(X_test[:, 1:]) Then all the IDs are still in X_train and X_test so your plotting function can make use of them.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/52701594

http://stackoverflow.com/comment/132317640
comment on: http://stackoverflow.com/a/56296451
type: Comment
has text: @gumdropsteve css and js typically go into a static folder, i.e. static -> css and static -> js folders inside your application folder. And source at top of html template like. ` `
score: 1
type: AnswerComment

http://stackoverflow.com/comment/92575508
has text: I am having the same problem. This seems to be a long-standing, unresolved issue of anaconda on OSX ([github issue](https://github.com/ContinuumIO/anaconda-issues/issues/199)). I am at the same point as you are.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52629661

http://stackoverflow.com/comment/92299118
has text: I’ve updated my answer: assuming the `o["duedate"]` string is _*always*_ formatted the same way, you can extract the [substring using Python’s slice notation](https://stackoverflow.com/questions/663171/is-there-a-way-to-substring-a-string-in-python).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52685798
score: 0

http://stackoverflow.com/comment/92333135
type: Comment
type: QuestionComment
has text: I get this error of "Select a valid choice. Male is not one of the available choices" in my web form. when I select either male or female in the webform
comment on: http://stackoverflow.com/q/52702033
score: 0

http://stackoverflow.com/comment/92235239
type: AnswerComment
comment on: http://stackoverflow.com/a/52651636
type: Comment
has text: Welcome to SO. Though we thank you for your answer, it would be better if it provided additional value on top of the other answers. In this case, your answer does not provide additional value, since another user already posted that solution. If a previous answer was helpful to you, you should vote it up once you have enough reputation
score: 1

http://stackoverflow.com/q/52596243
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/92127252
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52596352
has body: I am trying to create the following "algorithm" df['x'] = np.where(sum(df['x'][i-1],3)&gt;10, 10, 5) The idea here is that if the rolling sum of the last 3 elements, starting from the previous one, is positive then 5 else 10. I am looking for a data frame style solution without loops. Caution: df['x'] does not exist previously; it is a new column. So the result should be like that: x 5 5 5 10 10 . . . 10
type: Question
has title: Dataframe if case based on its previous elements
tagged with: dataframe
score: 0

http://stackoverflow.com/a/52624070
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52606908
answers question: http://stackoverflow.com/q/52606908
has body: def filter_function(df,filter_df): lvl_=list() lvl=list() vlv=list() df1=pd.DataFrame() n=filter_df.apply(lambda x: x.tolist(), axis=1) for i in range(0,len(n)): for j in range(0,len(n[i])): if i==0: lvl_.append(n[i][j].split('==')[0]) lvl.append(n[i][j].split('==')[1]) if len(lvl)==len(n[i]): vlv.append(lvl) lvl=list() final_df=df[lvl_] for k in range(0,len(vlv)): df1=df1.append(final_df[final_df.isin(vlv[k])].dropna()) return(df1) filter_function(df,filter_df)
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/92406647
comment on: http://stackoverflow.com/a/52730513
type: AnswerComment
has text: Another issue is cropping up, getting the following issue: 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: Comment

http://stackoverflow.com/q/52688203
type: AnsweredQuestion
tagged with: oop
has comment: http://stackoverflow.com/comment/92303653
upvote count: 5
accepted answer: http://stackoverflow.com/a/52688274
has comment: http://stackoverflow.com/comment/92303614
answer count: 2
score: 5
has title: Instantiating a python class from within the same class definition
downvote count: 0
has comment: http://stackoverflow.com/comment/92303538
has body: from collections import defaultdict #This class represents a directed graph using adjacency list representation class Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function that returns reverse (or transpose) of this graph def getTranspose(self): g = Graph(self.V) # Recur for all the vertices adjacent to this vertex for i in self.graph: for j in self.graph[i]: g.addEdge(j,i) return g g = Graph(5) g.addEdge(1, 0) g.addEdge(0, 2) g.addEdge(2, 1) g.addEdge(0, 3) g.addEdge(3, 4) The above code seems to work fine, but I am confused how can the class instantiation in getTranspose be done from within the same class?
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/52688274
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52688271
has answer: http://stackoverflow.com/a/52688271
type: Question

http://stackoverflow.com/comment/92339036
comment on: http://stackoverflow.com/q/52705767
type: Comment
type: QuestionComment
has text: @tarun , please look at the given answer below if helps you then accept as an answer so it can be removed from the un-accepted ans queue.
score: 0

http://stackoverflow.com/comment/92210203
score: 1
has text: There is nothing in your program that opens a file. You are only working with the filename.
comment on: http://stackoverflow.com/q/52638666
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92360497
score: 2
comment on: http://stackoverflow.com/q/52717452
has text: Using keywords as names of variables gives unexpected results. It may not throw an error but it will likely cause the script to execute in an unexpected manner affecting your result.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92268531
comment on: http://stackoverflow.com/q/52669094
score: 0
type: Comment
type: QuestionComment
has text: Whats in the CSV and what you write as a hardcoded check are not the same thing, though

http://stackoverflow.com/comment/92182411
has text: See [this answer](https://stackoverflow.com/a/50399219/9209546) for why you should not use built-ins like `sum` / `zip` with NumPy arrays.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52624079
type: Comment

http://stackoverflow.com/a/52672420
score: 0
answers question: http://stackoverflow.com/q/52668844
type: Answer
has body: You could wait until the Loading spinner no longer appears on the page anymore before checking for the credit card input. We have a C# solution that you could try to adapt to python where you wait in a loop for an element to be displayed, catching the exceptions until reaching the timeout. //Assert an element is displayed before the timeout milliseconds run out. public void AssertElementIsDisplayed(int timeout, IWebElement element, string elementName = "element") { Action&lt;IWebElement&gt; target = delegate (IWebElement e) { if (e == null) { throw new AssertionException("Failed to find " + elementName + ". It is null"); } if (!e.Displayed) { elementName = (elementName == "element" &amp;&amp; !String.IsNullOrEmpty(e.GetAttribute("title"))) ? e.GetAttribute("title") : elementName; throw new AssertionException("Expected (" + elementName + ") to be displayed but it was not"); } }; AssertInLoop(element, (long)timeout, 100L, target); } //Assert some Action on a WebElement for as long as the timeoutMillis allow. private void AssertInLoop(IWebElement element, long timeoutMillis, long millisBetweenAttempts, Action&lt;IWebElement&gt; callable) { AssertionException lastAssertionError = null; WebDriverException lastWebDriverException = null; long startTime = DateTimeOffset.Now.Ticks / TimeSpan.TicksPerMillisecond; if (timeoutMillis &lt; 500 || timeoutMillis &gt; 120 * 1000) { throw new ArgumentException("Timeout outside expected range. timeout_millis=" + timeoutMillis); } long millisLeft = timeoutMillis; while (millisLeft &gt;= 1) { long lastAttemptStartMillis = DateTimeOffset.Now.Ticks / TimeSpan.TicksPerMillisecond; try { callable(element); return; } catch (AssertionException e) { lastAssertionError = e; lastWebDriverException = null; } catch (StaleElementReferenceException e) { lastAssertionError = null; lastWebDriverException = e; } catch (NotFoundException e) { lastAssertionError = null; lastWebDriverException = e; } catch (SystemException e) { throw e; } long elapsedMill…

http://stackoverflow.com/q/52667705
has answer: http://stackoverflow.com/a/52679857
type: Question
has comment: http://stackoverflow.com/comment/92267725
has body: I have a pandas dataframe that roughly looks like this: df = pd.DataFrame(data, columns=["property_1", "property_2", "value"], index=my_index) my_index property_1 property_2 value &lt;1, 1, 1&gt; "A" "X" ... &lt;1, 1, 1&gt; "A" "Y" ... &lt;1, 1, 2&gt; "A" "X" ... &lt;1, 1, 4&gt; "A" "X" ... &lt;1, 1, 4&gt; "A" "Y" ... &lt;1, 1, 4&gt; "B" "X" ... &lt;1, 1, 4&gt; "B" "Y" ... I'm wanting to produce a grouped bar chart like this: This is quite complicated, but basically: I need to reduce my_index to the unique indices that have a value for each combination of property_1 and property_2 I need to find the unique combinations of property_1 AND property_2, not just the unique values of each column individually! I am trying to group them primarily by my_index, and then by the combination of property_1 and property_2 I would have guessed that the way of going about this is by having a dataframe with the following layout: my_index A-X A-Y B-X B-Y ... &lt;1, 1, 1&gt; ... ... NaN NaN ... &lt;1, 1, 2&gt; ... ... NaN NaN ... And so on. Then one could drop the columns with any NaN values in it. You could then just call df.plot.bar(...) on that resulting dataframe. But I am not sure how to rearrange these rows into the columns in this way. Does anyone have any ideas? EDIT: I should note that I don't need an answer in pandas, I am just asking if there is one. If not, I can wrangle the data out myself. But maybe pandas has a nifty one-liner for making this kind of work easier.
tagged with: dataframe
tagged with: pandas
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
has title: Rearranging pandas dataframe for grouped bar charts
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/20109391
score: 1

http://stackoverflow.com/q/52730234
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/52730530
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52730530
downvote count: 0
has title: Descending Filtering for Dataframe
tagged with: if-statement
score: 1
tagged with: dataframe
linked to: http://stackoverflow.com/q/52731563
type: Question
tagged with: for-loop
has body: I have a dataframe such as Index Results Price 0 Buy 10 1 Sell 11 2 Buy 12 3 Neutral 13 4 Buy 14 5 Sell 15 I would like to ultimately return the price difference for the first continuous combination of Buy and then Sell Results in a descending manner. Such that the first output is a difference of 1, second output 3. for buy in df: if buy: df['Buy Price'] = df['Price'] for sell in df: if sell: df['Sell Price'] = df['Price'] df['Difference'] = df['Sell Price'] - df['Buy Price'] Desired Output Index Results Price Difference 0 Buy 10 1 Sell 11 1 2 Buy 12 3 Neutral 13 4 Buy 14 5 Sell 15 3 I have attempted to implement a counter but with no such luck. Thanks in advance.
answer count: 1
tagged with: filter
upvote count: 1

http://stackoverflow.com/comment/92283925
has text: Thanks for your comment :D!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52676396
score: 0

http://stackoverflow.com/comment/92341820
type: AnswerComment
score: 0
type: Comment
has text: "Your approach doesn't work because you don't understand what the algorithm is doing." The addition of "simply" to that wouldn't make it more judgmental. Anyway, the process is stochastic. It doesn't matter if I compute the transition probabilities of going from `0 -> 0, 0 -> 1, 0 ->2 ...` now or when I'm thinking about the particle actually going through the transition. It's the same.
comment on: http://stackoverflow.com/a/52706091

http://stackoverflow.com/comment/92379154
comment on: http://stackoverflow.com/q/52722653
score: 0
type: Comment
type: QuestionComment
has text: edit and improve your indentation, another error I see is that the Word class is not defined

http://stackoverflow.com/comment/92246517
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52657899
has text: if user guessed 'p' do u want to replace blanks in this list `['_', '_', '_', '_', '_']` to get --> `_ p p _ _`

http://stackoverflow.com/a/52693785
type: Answer
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/92320838
answers question: http://stackoverflow.com/q/52693311
has body: Using groupby and itemgetter we could first create a flat list of tuples that represent the keys and values of each subdict. Then we can use groupby on our sorted new list. From there we can create our new dictionary using k and the items in index[1] of list(g) from itertools import groupby from operator import itemgetter d = {} new_lod = sorted([(j, i[j]) for i in lod for j in i], key=itemgetter(0)) for k, g in groupby(new_lod, key=itemgetter(0)): d[k] = [i[1] for i in list(g)] # {0: [3523, 7245], 1: [3524, 7246, 20898], 2: [3540, 7247, 20899], 3: [7248, 20900], 4: [3541, 20901], 5: [3542, 7249, 20902], 6: [7250]}
score: 0

http://stackoverflow.com/comment/92186513
type: Comment
has text: Ill edit my question with the code that i use for the winner variable
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52626456

http://stackoverflow.com/a/52689244
type: Answer
score: 1
has body: It looks like you are converting UTF-16 encoded characters to ASCII. UTF-16 is the default encoding in Windows, and represents all characters in two bytes, which means that all characters in the ascii set will include a null byte \x00. Reading to the docs, I would expect msvcrt.getch() to return ASCII encoded characters, so this is unexpected. In any case, if you replace decode("ASCII") with decode('utf16'), you should get the expected output.
upvote count: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52688917
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52688917
has comment: http://stackoverflow.com/comment/92306780
has comment: http://stackoverflow.com/comment/92306177

http://stackoverflow.com/a/52660230
upvote count: 4
downvote count: 0
has body: The error AttributeError: module 'pyarrow' has no attribute 'compat' is sadly a bit misleading. To execute the to_pandas() function on a pyarrow.Table instance you need pandas installed. The above error is a sympton of the missing requirement. pandas is a not a hard requirement of pyarrow as most of its functionality is usable with just Python built-ins and NumPy. Thus users of pyarrow which include pandas can work with it without needing to have pandas pre-installed.
score: 4
answers question: http://stackoverflow.com/q/52656972
type: Answer

http://stackoverflow.com/q/52727017
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52728834
upvote count: 1
type: Question
tagged with: opencv
score: 1
has answer: http://stackoverflow.com/a/52728834
has title: OpenCV: Object tracking with denoising
has comment: http://stackoverflow.com/comment/92381458
tagged with: image-segmentation
has body: I'm attempting to extract a blue object, very much like the one described in https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html#object-tracking An example of a raw image with three blue shapes to extract is here: The captured image is noisy and the unfiltered shape detection returns hundreds to thousands of "blue" shapes. In order to mitigate this, I applied the following steps: Blurring the image before filtering it, resulting in closed surfaces Converting the masked image (after bitwise_and) back to grayscale Applying an OTSU threshold Finally, detect the contours The complete code is: import cv2 import numpy as np cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() blur = cv2.GaussianBlur(frame, (15, 15), 0) hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV) lower_red = np.array([115, 50, 50]) upper_red = np.array([125, 255, 255]) mask = cv2.inRange(hsv, lower_red, upper_red) blue = cv2.bitwise_and(blur, blur, mask=mask) gray = cv2.cvtColor(blue, cv2.COLOR_BGR2GRAY) (T, ted) = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU) im2, contours, hierarchy = cv2.findContours( ted, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: cv2.drawContours(frame, [cnt], 0, (0, 255, 0), 3) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(frame, str(len(contours)), (10, 500), font, 2, (0, 0, 255), 2, cv2.LINE_AA) cv2.imshow('mask', mask) cv2.imshow('blue', blue) cv2.imshow('grey', gray) cv2.imshow('thresholded', ted) cv2.imshow('frame', frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() Unfortunately, there are still 6-7 contours left whereas there should be three. How can I further refine image processing to get just the three shapes?
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92343035
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52708397
has text: [mcve] please. it's unclear what your inputs are
score: 0

http://stackoverflow.com/comment/92426005
type: QuestionComment
comment on: http://stackoverflow.com/q/52746014
has text: Use `communicate` (again) instead of `write`-`close`-`read` to avoid the risk of deadlock.
score: 0
type: Comment

http://stackoverflow.com/comment/92414735
type: Comment
type: QuestionComment
has text: @HenryYik Exactly, I can place label and I can even divide the frame into a grid of 5*2(5 rows and 2 columns) and in one column I can create a line by using canvas_createLine and in the second column I can add text with canvas.createText but it is very static and then it will contain many lines of code as you can't pack a grid inside frame then I have to configure rows and columns each of them seperately.
score: 0
comment on: http://stackoverflow.com/q/52739941

http://stackoverflow.com/comment/92223299
has text: You failed to base64-decode the key.
score: 0
comment on: http://stackoverflow.com/q/52639703
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92288870
type: QuestionComment
has text: Are you assuming the server is running Windows? Pretty much all other systems use a forward slash (which is also supported on Windows), and that's what os.path.join and os.path.sep are for. Python 3 extends this with the [pathlib](https://docs.python.org/3/library/pathlib.html) module.
comment on: http://stackoverflow.com/q/52680148
score: 4
type: Comment

http://stackoverflow.com/comment/92391748
type: QuestionComment
comment on: http://stackoverflow.com/q/52732600
type: Comment
has text: So you want to cluster 1D vector as I understand?
score: 0

http://stackoverflow.com/q/52593336
has answer: http://stackoverflow.com/a/52593381
upvote count: 1
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52593432
accepted answer: http://stackoverflow.com/a/52593381
has answer: http://stackoverflow.com/a/52593432
downvote count: 0
score: 1
favorite count: 0
tagged with: pandas
tagged with: python
has body: I have a data-frame (df) which looks like: ID Location Score 23 London A 34 Bristol C 2 Swansea D 67 London A 32 Bath D I have a validation data-frame called valid, which looks like: Main_Location Sub_Location1 Sub_location2 London Bristol Bath I would like to return a data-frame that picks up any rows in df (lets call the data-frame error) which do not have a location in the valid data-frame So my error data-frame would look like: ID Location Score 2 Swansea D As Swansea is not in the valid dataframe the row of information is returned to the error dataframe. Have tried to use without success: error = ~df['Location'].isin(valid)
type: AnsweredQuestion
has title: Check a dataframe against another dataframe and return errors

http://stackoverflow.com/q/52665061
has title: The right data format for silhouette_score with pandas
accepted answer: http://stackoverflow.com/a/52671702
has comment: http://stackoverflow.com/comment/92270908
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92263098
score: 1
upvote count: 1
type: Question
has body: I'd like to use silhouette_score to estimate the optimum number of clusters. I'm using an official example from sklearn but it gives me this error: TypeError: silhouette_score() takes 1 positional argument but 2 were given. My data (X) is a pandas dataframe with 20 features (all non-null float64) and index as unique ID strings (can this be a problem?). f1 f2 f3 … f20 ID AA2 0.33 0 0.31 … 0.16 BS4 0 0 0 … 0.41 VK9 0 0 0 … 0.48 I'm using data.values to turn it into a matrix (see the code below). Will appreciate your help! X = data.values for n_clusters in range_n_clusters: # Create a subplot with 1 row and 2 columns fig, (ax1, ax2) = plt.subplots(1, 2) fig.set_size_inches(18, 7) # The 1st subplot is the silhouette plot # The silhouette coefficient can range from -1, 1 but in this example all # lie within [-0.1, 1] ax1.set_xlim([-0.1, 1]) # The (n_clusters+1)*10 is for inserting blank space between silhouette # plots of individual clusters, to demarcate them clearly. ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10]) # Initialize the clusterer with n_clusters value and a random generator # seed of 10 for reproducibility. clusterer = KMeans(n_clusters=n_clusters, random_state=10) cluster_labels = clusterer.fit_predict(X) # The silhouette_score gives the average value for all the samples. # This gives a perspective into the density and separation of the formed # clusters silhouette_avg = silhouette_score(X, cluster_labels) print("For n_clusters =", n_clusters, "The average silhouette_score is :", silhouette_avg) # Compute the silhouette scores for each sample sample_silhouette_values = silhouette_samples(X, cluster_labels) y_lower = 10 for i in range(n_clusters): # Aggregate the silhouette scores for samples belonging to # cluster i, and sort them ith_cluster_silhouette_values = \ sample_silhouette_values[cluster_labels == i] ith_cluster_silhouette_values.sort() size_cluster_i = ith_cluster_silhouette_values.shape[0] y_upper = y_lower + size_cluster_i color = cm.nipy_spec…
tagged with: arrays
tagged with: cluster-analysis
downvote count: 0
has answer: http://stackoverflow.com/a/52671702
tagged with: pandas
has comment: http://stackoverflow.com/comment/92260715
answer count: 1
has comment: http://stackoverflow.com/comment/92267018
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/comment/92387545
type: Comment
has text: As the linked question explains, you can define all your number variables as `Decimal` objects instead. Remember to initialize the objects with strings rather than number literals.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52731171

http://stackoverflow.com/q/52739018
favorite count: 0
upvote count: 7
has answer: http://stackoverflow.com/a/52739069
has body: The structure of the project is: project - main.py - session.py - spider.py There is a class in session.py: import requests class Session: def __init__(self): self.session = requests.Session() print('Session created.') And another class in spider.py: from session import Session class Spider: def __init__(self, sess: Session = Session()): print('Spider created.') When I import class Spider from spider.py in main.py like this: from spider import Spider if __name__ == '__main__': print('Main function.') spider = Spider() And run main.py, I get: Session created. Main function. Spider created. It confuses me. I think __init__ is the initial function used when initializing an instance, but in this case the __init__ function of Session is called when Session is imported in spider.py. I think it must be related to the default value of __init__ function in spider.py, but why?
type: AnsweredQuestion
score: 7
type: Question
answer count: 1
downvote count: 0
has title: Why import class from another file will call __init__ function?
tagged with: python
accepted answer: http://stackoverflow.com/a/52739069

http://stackoverflow.com/a/52604434
answers question: http://stackoverflow.com/q/52604414
accepted answer of: http://stackoverflow.com/q/52604414
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92144932
score: 4
has body: Use reindex: #if x is column #df = df.set_index('x').reindex(np.arange(df.index.min(), df.index.max() + 1)) #if x is index df = df.reindex(np.arange(df.index.min(), df.index.max() + 1)) print (df) text x 1 one 2 two 3 NaN 4 four 5 five 6 NaN 7 seven
has comment: http://stackoverflow.com/comment/92144766
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/92146463
downvote count: 0

http://stackoverflow.com/comment/92267102
type: QuestionComment
comment on: http://stackoverflow.com/q/52668645
score: 0
has text: Variable number of names? Use a dictionary. `grouped = {}`, then in the loop `grouped.setdefault(tag, []).append(x)`.
type: Comment

http://stackoverflow.com/q/52745001
tagged with: apache-beam
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52781753
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/71966498
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/53036548
tagged with: google-cloud-dataflow
accepted answer: http://stackoverflow.com/a/52781753
has answer: http://stackoverflow.com/a/52745580
has comment: http://stackoverflow.com/comment/92476891
has title: Apache Beam Python SDK: How to access timestamp of an element?
has answer: http://stackoverflow.com/a/53071947
possible better answer: http://stackoverflow.com/a/52745580
has comment: http://stackoverflow.com/comment/92422969
favorite count: 0
has body: I'm reading messages via ReadFromPubSub with timestamp_attribute=None, which should set timestamps to the publishing time. This way, I end up with a PCollection of PubsubMessage elements. How can I access the timestamps of these element in order, e.g. save them to a database? The only properties I can see are data and attributes, and the attributes only has keys coming from Pub/Sub. Edit: Sample code with beam.Pipeline(options=pipeline_options) as p: items = (p | ReadFromPubSub(topic=args.read_topic, with_attributes=True) | beam.WindowInto(beam.window.FixedWindows(args.time_window)) | 'FormatMessage' &gt;&gt; beam.Map(format_message) | 'WriteRaw' &gt;&gt; WriteToBigQuery(args.raw_table, args.dataset, args.project, write_disposition='WRITE_APPEND') ) where format_message would take a PubsubMessage and return a dictionary representing a row to append to the table: def format_message(message): formatted_message = { 'data': base64.b64encode(message.data), 'attributes': str(message.attributes) } return formatted_message

regex
tags question: http://stackoverflow.com/q/52639573
tags question: http://stackoverflow.com/q/52600940
tags question: http://stackoverflow.com/q/52618015
tags question: http://stackoverflow.com/q/52619364
tags question: http://stackoverflow.com/q/52686143
tags question: http://stackoverflow.com/q/52711467
tags question: http://stackoverflow.com/q/52614773
tags question: http://stackoverflow.com/q/52689035
tags question: http://stackoverflow.com/q/52742330
tags question: http://stackoverflow.com/q/52743344
tags question: http://stackoverflow.com/q/52599549
tags question: http://stackoverflow.com/q/52597841
tags question: http://stackoverflow.com/q/52745224
tags question: http://stackoverflow.com/q/52646581
tags question: http://stackoverflow.com/q/52638675
tags question: http://stackoverflow.com/q/52732448
tag name: regex
tags question: http://stackoverflow.com/q/52689716
tags question: http://stackoverflow.com/q/52726935
tags question: http://stackoverflow.com/q/52663935
tags question: http://stackoverflow.com/q/52710165
tags question: http://stackoverflow.com/q/52681629
tags question: http://stackoverflow.com/q/52599565
tags question: http://stackoverflow.com/q/52711913
tags question: http://stackoverflow.com/q/52640981
tags question: http://stackoverflow.com/q/52730150
tags question: http://stackoverflow.com/q/52696365
tags question: http://stackoverflow.com/q/52708397
tags question: http://stackoverflow.com/q/52618381
tags question: http://stackoverflow.com/q/52705943
tags question: http://stackoverflow.com/q/52628720
tags question: http://stackoverflow.com/q/52631632
tags question: http://stackoverflow.com/q/52676396
tags question: http://stackoverflow.com/q/52738452
tags question: http://stackoverflow.com/q/52694875
tags question: http://stackoverflow.com/q/52626356
tags question: http://stackoverflow.com/q/52702788
tags question: http://stackoverflow.com/q/52640007
tags question: http://stackoverflow.com/q/52662494
tags question: http://stackoverflow.com/q/52644714
tags question: http://stackoverflow.com/q/52694599
tags question: http://stackoverflow.com/q/52619740
tags question: http://stackoverflow.com/q/52725104
tags question: http://stackoverflow.com/q/52724641
tags question: http://stackoverflow.com/q/52705416
tags question: http://stackoverflow.com/q/52726309
tags question: http://stackoverflow.com/q/52670596
tags question: http://stackoverflow.com/q/52741573
tags question: http://stackoverflow.com/q/52638349
tags question: http://stackoverflow.com/q/52697707
tags question: http://stackoverflow.com/q/52743329
tags question: http://stackoverflow.com/q/52683571
tags question: http://stackoverflow.com/q/52659009
tags question: http://stackoverflow.com/q/52700246
tags question: http://stackoverflow.com/q/52601558
tags question: http://stackoverflow.com/q/52606736
tags question: http://stackoverflow.com/q/52620140
tags question: http://stackoverflow.com/q/52599978
tags question: http://stackoverflow.com/q/52667072
tags question: http://stackoverflow.com/q/52710140
tags question: http://stackoverflow.com/q/52620953
tags question: http://stackoverflow.com/q/52673419
tags question: http://stackoverflow.com/q/52683619
tags question: http://stackoverflow.com/q/52745290
tags question: http://stackoverflow.com/q/52620752
tags question: http://stackoverflow.com/q/52724639
tags question: http://stackoverflow.com/q/52728307
tags question: http://stackoverflow.com/q/52612059
tags question: http://stackoverflow.com/q/52726555
tags question: http://stackoverflow.com/q/52607540
tags question: http://stackoverflow.com/q/52630820
tags question: http://stackoverflow.com/q/52640941
tags question: http://stackoverflow.com/q/52603661
tags question: http://stackoverflow.com/q/52593109
tags question: http://stackoverflow.com/q/52610930
tags question: http://stackoverflow.com/q/52652945
tags question: http://stackoverflow.com/q/52700287
tags question: http://stackoverflow.com/q/52696757
tags question: http://stackoverflow.com/q/52658463
tags question: http://stackoverflow.com/q/52708315

http://stackoverflow.com/a/52744760
score: 0
type: Answer
has body: I'm sure there is a better way of doing this but to simply maintain your syntax and give the proper answer your if statement should be if 'blazer' in compareName and ('ten' in compareName or '10' in compareName): func() else: pass
answers question: http://stackoverflow.com/q/52744591

http://stackoverflow.com/q/52743160
has title: Strange behavior of exception section during unit test in Python 3.7
has comment: http://stackoverflow.com/comment/92411337
tagged with: xunit
tagged with: python-3.7
has comment: http://stackoverflow.com/comment/92411347
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92411423
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92411356
tagged with: python
has comment: http://stackoverflow.com/comment/92411329
has answer: http://stackoverflow.com/a/52743356
upvote count: 0
has body: I have some sqlite DB creation code. There are several options - if the file existed or not, or if it gets an error (writing to the HDD, wrong DB name, format, etc.). If the method works right, it returns True, if it throws an exception, it will return False: def create_db(): try: db = sqlite3.connect(db_name) with db: db.execute("SELECT name FROM db_name WHERE type='table'") if os.path.isfile(db_name): my_logger.info('The DB already existed!') return 'DB existed' else: db = sqlite3.connect(db_name) with db: db.execute('''CREATE TABLE IF NOT EXISTS City_Weather (fields_description_here)''') my_logger.info('The DB was created successfully!') return 'DB created' except Exception as e: my_logger.info(e) return False And I wrote this unit test for the function: class ReadersTest(unittest.TestCase): def test_create_db(self): self.assertEqual(create_db(), 'DB existed') The strange behaviour begins where I try to init my tests: DB existed != False Expected :False Actual :DB existed &lt;Click to see difference&gt; Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2018.2.2\helpers\pycharm\teamcity\diff_tools.py", line 32, in _patched_equals old(self, first, second, msg) File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", line 839, in assertEqual assertion_func(first, second, msg=msg) File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", line 832, in _baseAssertEqual raise self.failureException(msg) AssertionError: False != 'DB existed' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", line 59, in testPartExecutor yield File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\unittest\case.py", line 615, in run testMethod() File "C:\file_path_to_project\utest.py", line 12, in test_create_db self.assertEqual(readers.Readers.create_db(), 'DB existed') Why i…
has comment: http://stackoverflow.com/comment/92411265
has comment: http://stackoverflow.com/comment/92411509
tagged with: unit-testing
type: Question
score: -1

http://stackoverflow.com/comment/92165660
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52615087
type: Comment
has text: Yeah, I guess I error on the side of not using g a key function if possible

http://stackoverflow.com/a/52727904
score: -1
answers question: http://stackoverflow.com/q/52725568
type: Answer
downvote count: 2
has body: Note that you do not necessarily need to use yield: def last(d): c = [i for b in d.items() for i in ([b] if not isinstance(b[-1], dict) else last(b[-1]))] return c print(dict(last({'a': {'b': {'c': 'd', 'e': 'f'}}}))) Output: {'c': 'd', 'e': 'f'}
upvote count: 1

http://stackoverflow.com/comment/92217483
score: 0
comment on: http://stackoverflow.com/a/52642456
type: Comment
type: AnswerComment
has text: Just after you declare the class, put something like `ChildClassName.name = ChildClassName.__name__ + 'something else'`

http://stackoverflow.com/a/52720620
has body: The for item in data['response'] iterates through a dict. In python, when you iterate though a dict, you iterate through its keys only. So, each item is a string, hence the error. In your case, you can directly write data['response']['speed']
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52720552

http://stackoverflow.com/comment/92229195
type: AnswerComment
type: Comment
has text: 2500 inches? That's a lotta scrolling. =)
comment on: http://stackoverflow.com/a/52648576
score: 0

http://stackoverflow.com/comment/92141333
score: 0
type: QuestionComment
has text: Klaus D., when I used 'FROM python' I got a bunch of compile errors.
type: Comment
comment on: http://stackoverflow.com/q/52603324

http://stackoverflow.com/q/52724255
has comment: http://stackoverflow.com/comment/92374174
has comment: http://stackoverflow.com/comment/92394442
has comment: http://stackoverflow.com/comment/92375045
type: Question
has comment: http://stackoverflow.com/comment/92374362
has comment: http://stackoverflow.com/comment/92375331
has comment: http://stackoverflow.com/comment/92373928
score: 0
has comment: http://stackoverflow.com/comment/92374206
has comment: http://stackoverflow.com/comment/92374779
has title: ImportError at / No module name ___ even though requirement satisfied
has comment: http://stackoverflow.com/comment/92375231
has comment: http://stackoverflow.com/comment/92375306
has comment: http://stackoverflow.com/comment/92374026
has comment: http://stackoverflow.com/comment/92374561
has comment: http://stackoverflow.com/comment/92375129
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92407606
tagged with: pip
tagged with: django
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/92375153
has body: I'm runnning a django app and getting this error: ImportError at / No module named svglib.svglib my code for importing this is: from svglib.svglib import svg2rlg when I run pip list I see that I have svglib (0.8.1) installed already. Is this due to the import being in parent.file format? What is work around here? EDIT: I have Django 1.11.8 and Pip 9.0.1

http://stackoverflow.com/comment/92375536
comment on: http://stackoverflow.com/q/52704923
score: 0
type: Comment
has text: There's no suggestion. You cannot use hashlib with remote path. Read carefuly my answer to the duplicate question.
type: QuestionComment

http://stackoverflow.com/a/52676556
has comment: http://stackoverflow.com/comment/92318738
downvote count: 0
upvote count: 2
has body: self.item = {} initializes self.items to an empty dictionary. A dictionary does not have an append() method because its primary purpose is to associate keys with values. Looking at the code, the intention is for self.menu to be a dict (mapping menu items to prices) and self.items to be a list (of bill items), and list does have an append method. To intialize self.items as an empty list instead, modify the assignment to: self.item = []
has comment: http://stackoverflow.com/comment/92291619
has comment: http://stackoverflow.com/comment/92291438
accepted answer of: http://stackoverflow.com/q/52676526
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52676526
has comment: http://stackoverflow.com/comment/92298372
type: Answer
has comment: http://stackoverflow.com/comment/92299339
score: 2

http://stackoverflow.com/comment/92293896
comment on: http://stackoverflow.com/a/52674229
type: AnswerComment
score: 0
type: Comment
has text: @Abhishek question how would I edit the code so it would print out multiple names if they had the same amount of largest hours

http://stackoverflow.com/comment/92377769
type: QuestionComment
comment on: http://stackoverflow.com/q/52726072
score: 1
has text: `pd.to_datetime(df['column_name']).dt.year`
type: Comment

http://stackoverflow.com/comment/92363398
type: Comment
has text: What do you mean by "builtin"? Just plain `numpy`?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52706447

http://stackoverflow.com/comment/92270882
score: 1
has text: Did you try an axis parameter for `stack`? like `np.stack([arr1, arr2, arr3], axis=2)`?
comment on: http://stackoverflow.com/q/52670278
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92235747
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52651442
has text: Edited with solution

http://stackoverflow.com/a/52681788
accepted answer of: http://stackoverflow.com/q/52681662
upvote count: 2
answers question: http://stackoverflow.com/q/52681662
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92291818
type: Answer
has body: find (and findall) lets you specify a path to elements as well, for example you can do: root = ET.fromstring(input_xml) for a in root.findall('a'): print(a, a.find('from/b').text) assuming you do always have exactly one from and b element. otherwise, I might be tempted to use findall and do checks in Python code if this is designed to be more robust

http://stackoverflow.com/q/52683619
has answer: http://stackoverflow.com/a/52683644
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92295229
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92295217
tagged with: python
tagged with: regex
downvote count: 3
has body: "Name":"abc" Expected output: Name Here in this case, when I have the value "abc", I need to fetch the word Name by using positive look behind and extracting the words between the occurences of ".
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/92295228
has title: positive lookbehind multiple times
score: -3

http://stackoverflow.com/comment/92145638
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/a/842096/7698247 have a look
comment on: http://stackoverflow.com/q/52605706

http://stackoverflow.com/comment/92296637
score: 0
type: Comment
type: QuestionComment
has text: I'll make a wild guess that the web server process doesn't have permission to access the file location.
comment on: http://stackoverflow.com/q/52684364

http://stackoverflow.com/comment/92518898
comment on: http://stackoverflow.com/a/52685457
has text: Parens are very optional
type: Comment
score: 3
type: AnswerComment

http://stackoverflow.com/comment/92246721
comment on: http://stackoverflow.com/q/52658139
score: 0
has text: I'm confused, do you want to concatenate and sort or not? Your post says `sort=False` but your title seems to imply you want to sort.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92162287
type: QuestionComment
has text: Are you starting this from cmd terminal or anaconda gui environment?
comment on: http://stackoverflow.com/q/52601988
score: 0
type: Comment

http://stackoverflow.com/comment/92271228
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52670717
has text: What do you mean by "without specifying the model name" ? In your code you specified the model as `Permission`.
score: 0

http://stackoverflow.com/comment/92258059
comment on: http://stackoverflow.com/a/52664116
score: 0
type: AnswerComment
has text: how would i change that? im not exactly experienced.
type: Comment

http://stackoverflow.com/q/52692674
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: output
has title: How to print curly brackets with new formatting
type: Question
accepted answer: http://stackoverflow.com/a/52692706
score: 4
has body: I am trying to have python output something that I can then copy and past into a latex document. I need the output to look like this: q_{00} q_{01} etc, I am using this code here, but, is there a way to get the curly bracket to print, the formatted number, and the other curly bracket, without adding whitespace or spaces? for rows in range(nst): print("q_{{0:0=2d}}".format(rows)) which just yields q_{0:0=2d}
has answer: http://stackoverflow.com/a/52692706
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52619874
has comment: http://stackoverflow.com/comment/92194836
linked to: http://stackoverflow.com/q/51447460
answer count: 2
has comment: http://stackoverflow.com/comment/92196434
downvote count: 0
has answer: http://stackoverflow.com/a/52651940
favorite count: 0
linked to: http://stackoverflow.com/q/11232597
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52629493
score: 2
has comment: http://stackoverflow.com/comment/92173698
has comment: http://stackoverflow.com/comment/92175203
has body: I just accidentally discovered that I can mix sympy expressions up with numpy arrays: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import sympy as sym &gt;&gt;&gt; x, y, z = sym.symbols('x y z') &gt;&gt;&gt; np.ones(5)*x array([1.0*x, 1.0*x, 1.0*x, 1.0*x, 1.0*x], dtype=object) # I was expecting this to throw an error! # sum works and collects terms etc. as I would expect &gt;&gt;&gt; np.sum(np.array([x+0.1,y,z+y])) x + 2*y + z + 0.1 # dot works too &gt;&gt;&gt; np.dot(np.array([x,y,z]),np.array([z,y,x])) 2*x*z + y**2 &gt;&gt;&gt; np.dot(np.array([x,y,z]),np.array([1,2,3])) x + 2*y + 3*z This is quite useful for me, because I'm doing both numerical and symbolic calculations in the same program. However, I'm curious about the pitfalls and limitations of this approach --- it seems for example that neither np.sin nor sym.sin are supported on Numpy arrays containing Sympy objects, since both give an error. However, this numpy-sympy integration doesn't appear to be documented anywhere. Is it just an accident of how these libraries are implemented, or is it a deliberate feature? If the latter, when is it designed to be used, and when would it be better to use sympy.Matrix or other solutions? Can I expect to keep some of numpy's speed when working with arrays of this kind, or will it just drop back to Python loops as soon as a sympy symbol is involved? In short I'm pleased to find this feature exists, but I would like to know more about it!
has title: Sympy-numpy integration exists - where is it documented?
type: Question
tagged with: numpy
tagged with: sympy

http://stackoverflow.com/q/52715471
has comment: http://stackoverflow.com/comment/92356966
type: Question
has comment: http://stackoverflow.com/comment/92358435
has answer: http://stackoverflow.com/a/52723776
answer count: 1
tagged with: python
tagged with: bottle
has body: I have a python bottle application, and use gevent server run(host=ip, port=8080, server="gevent") with monkey.patch_all(). The application will call API method on remote server then process result and return JSON result, like {"ret": "success", "code": "0", "message": null, "id": "00001"} . I use curl to test application, like curl http://10.10.10.10:8080/Check , it can return success. But when I try 2 client access at the same time, the first access return incomplete JSON result, just like {"ret": "success", "code": "0", "message": null, "id" , the second can return success. How to handle this parallel access? In my application, it will received some parameter such as id , then use those parameters will create class, when client access at the same time, those variables value are overrided.
type: UnansweredQuestion
score: 0
tagged with: gevent
has comment: http://stackoverflow.com/comment/92681350
has title: bottle + gevent parallel support

http://stackoverflow.com/comment/92220730
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52644161
score: 0
has text: I don't think this is what OP wants. `pip-autoremove` removes "unused dependencies", but `package1` might not be the dependency of some other package but just something that is used in scripts written by OP.

http://stackoverflow.com/a/53105743
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: Upgrading to the latest version of tfjs (currently 0.13.3) solves the issue. More context to the question can be viewed here and there
score: 3
accepted answer of: http://stackoverflow.com/q/52683723
answers question: http://stackoverflow.com/q/52683723
upvote count: 3

http://stackoverflow.com/comment/92358501
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52716473
type: Comment
has text: You could create a list and keep appending results to it and then return the list outside the loop

http://stackoverflow.com/comment/92405504
score: 0
type: Comment
type: QuestionComment
has text: re-install the package and try..
comment on: http://stackoverflow.com/q/52740351

http://stackoverflow.com/comment/92393549
has text: I don't think so, please see my reply to @ninjin's comment
comment on: http://stackoverflow.com/a/52716323
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/92380794
type: QuestionComment
has text: @justFathi I've been programming for about 5 years, and I still draw flow charts on paper before I go after a complicated project sometimes. Especially user interface situations where you end up with all sorts of menus and submenus with many choices.
score: 0
comment on: http://stackoverflow.com/q/52727590
type: Comment

http://stackoverflow.com/q/52634533
has title: How to Subset Text File in Python Using Grouping?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52635832
has answer: http://stackoverflow.com/a/52635471
type: Question
possible better answer: http://stackoverflow.com/a/52635832
has body: I am just starting out in python. I am unable to solve the following problem. Any help is greatly appreciated. Thank you. I have a txt file that looks like this: &gt; #code1 information about code here abcdefghijklmnopqrst information line continures #code2 information about code here xyz #code3 &gt; information about code here klm #code4 details found here, information &gt; {}}} information and details continued #code5.... I want my output to be 2 txt files. one with all lines pertaining to code1 and 1 with all lines pertaining to code4. with open("C:\\Users\\name\\Desktop\\Codes.txt","r") as f: d = {} for line in f: start = "#code" code,number = line.strip().split(start) if d.has_key(number): d[number].append(code) else: d[number] = [] d[number].append(code) for key,value in d.iteritems(): f = open("C:\\Users\\name\\Desktop\\New folder\{}.txt".format(number), "w") for item in value: f.write("{}\n".format(item)) f.close() I am not sure how to (1) group all lines pertaining to codes that bleed over to a new line and (2) how to select only the two codes (code1 and code4) to write to new files.
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52635471

http://stackoverflow.com/comment/92352024
type: Comment
comment on: http://stackoverflow.com/a/52698965
has text: Thanks for the information. Any workaround to get the desired output.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92388785
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52731801
has text: @jedwards, given that this is a contrived example, I didn't flesh out `__getattr__` fully. I've added a comment to show where the real logic would go. (Edit: @jedwards has since deleted their comment)
score: 0

http://stackoverflow.com/q/52614592
downvote count: 0
has comment: http://stackoverflow.com/comment/92163747
favorite count: 0
linked to: http://stackoverflow.com/q/57298901
linked to: http://stackoverflow.com/q/43143014
answer count: 5
tagged with: python
possible better answer: http://stackoverflow.com/a/65240100
has comment: http://stackoverflow.com/comment/92163609
accepted answer: http://stackoverflow.com/a/52614965
upvote count: 13
has answer: http://stackoverflow.com/a/65240100
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/43409916
tagged with: selenium-chromedriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69432754
tagged with: selenium
linked to: http://stackoverflow.com/q/76550506
score: 13
has body: Been searching for a while and tried all the solutions present but none appear to be working. I created a "slide show" that will first log in, then alternate between tabs. All of that is working but i cannot get rid of the "Chrome is being controlled by automated test software" bar. Any advise? Code 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 usernameStr = 'test' passwordStr = 'test' browser = webdriver.Chrome() #first tab browser.get(('www.testwebsite.com?')) # fill in username and hit the next button username = browser.find_element_by_id('username') username.send_keys(usernameStr) password = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.ID, 'password'))) password.send_keys(passwordStr) nextButton = browser.find_element_by_class_name('emp-submit') nextButton.click() #second tab browser.execute_script("window.open('about:blank', 'tab2');") browser.switch_to.window("tab2") browser.get('www.testwebsite.com')
tagged with: webdriver
has comment: http://stackoverflow.com/comment/138261183
type: Question
has answer: http://stackoverflow.com/a/75641527
has answer: http://stackoverflow.com/a/73100883
has title: How to get rid of the infobar "Chrome is being controlled by automated test software" through Selenium
has answer: http://stackoverflow.com/a/52614965

http://stackoverflow.com/comment/113731859
type: Comment
has text: I'm now having this issue too @SuminKim and I can tell the Florian Weimer advice misled us and broke our ubuntu. shame on you, Florian. I now have to reinstall my ubuntu server
comment on: http://stackoverflow.com/a/52626003
score: 0
type: AnswerComment

http://stackoverflow.com/a/52681139
has body: As &lt;Sco&gt; is not a direct child of the root, you have to access it with using findall(.//&lt;node&gt;) (depth first search). import xml.etree.ElementTree as ET tree = ET.parse('sshs_eval.xml') root = tree.getroot() for ScoreEvent in root.findall('.//Sco'): Event = ScoreEvent.find('Ev').text Start = ScoreEvent.find('St').text print(Event,Start)
accepted answer of: http://stackoverflow.com/q/52680823
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52680823
has comment: http://stackoverflow.com/comment/92290774
has comment: http://stackoverflow.com/comment/92290706
type: Answer
has comment: http://stackoverflow.com/comment/92290867
score: 0

http://stackoverflow.com/a/52653028
answers question: http://stackoverflow.com/q/52652945
type: Answer
has body: Using .extend(): for i in a: h.extend(re.findall(r'/(\w+)', i)) Using += (just another way to call .extend): for i in a: h += re.findall(r'/(\w+)', i) Using unpacking: for i in a: h.append(*re.findall(r'/(\w+)', i))
score: 0

http://stackoverflow.com/q/52716590
upvote count: 2
type: UnansweredQuestion
tagged with: arima
tagged with: machine-learning
tagged with: python
tagged with: statsmodels
answer count: 0
has title: ML or Time Series Models when we have multiple variables?
has comment: http://stackoverflow.com/comment/92359095
has body: I have been working on Time Series (forecasting) models in python. I haven't managed to create an ARIMA model (with statsmodels) for multi-variables. Firstly, I am assuming this is possible!? I have managed though to create a set of ML models for multi-variables. My question is: Are ML models generally better than ARIMA/other time series models, when we are dealing with multi-variables? I would appreciate any comments or references comparing the two.
downvote count: 1
has comment: http://stackoverflow.com/comment/92358682
type: Question
has comment: http://stackoverflow.com/comment/92358728
has comment: http://stackoverflow.com/comment/92358821
tagged with: forecasting
score: 1
has comment: http://stackoverflow.com/comment/92358919
favorite count: 0

http://stackoverflow.com/comment/92145197
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52605466
has text: Okay that was quick and an unexpected Question i allready hat something like that but I threw it away because it didnt gave a MultiIndex

http://stackoverflow.com/comment/92362155
type: QuestionComment
has text: Without a [MCVE] it is unclear what you're asking. The code you posted seems to be completely irrelevant for the actual question (comparing elements from different dataframes). Give us some sample dataframes and the output you want.
score: 0
comment on: http://stackoverflow.com/q/52718330
type: Comment

http://stackoverflow.com/comment/92201745
comment on: http://stackoverflow.com/q/52633511
score: 0
type: Comment
type: QuestionComment
has text: @Sraw; I added the screenshot of the headers. Does that help?

http://stackoverflow.com/q/52685078
has comment: http://stackoverflow.com/comment/92297978
type: AnsweredQuestion
has title: How to determine if XML tags, attributes exist using Python?
type: Question
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52685571
score: 0
answer count: 1
tagged with: python
has body: I'm trying to find out if xml contains the subtypemismatch="true" text in the following xml. &lt;boardgames termsofuse="https://boardgamegeek.com/xmlapi/termsofuse"&gt; &lt;boardgame objectid="45987" subtypemismatch="true"&gt; &lt;yearpublished/&gt; If I use BeautifulSoup with the following code, I can get to a 'true' or 'false', but most of the xml I need to read in does not contain the subtypemismatch text, which causes a "KeyError: 'subtypemismatch'" to occur. How do I determine if the xml has this text to begin with? data = response.read() text = data.decode('utf-8') soup = BeautifulSoup(text,'xml') if soup.find('boardgame')['subtypemismatch'] != 'true': do something....
tagged with: http://stackoverflow.com/tag/xml
accepted answer: http://stackoverflow.com/a/52685571

http://stackoverflow.com/a/52650082
score: 1
accepted answer of: http://stackoverflow.com/q/52650041
has body: This will work: df'A','B','C' = pd.DataFrame(df.averages.values.tolist(), index= df.index)
answers question: http://stackoverflow.com/q/52650041
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/q/52624736
type: AnsweredQuestion
tagged with: enums
has body: I have this piece of code: import enum class Color(enum.Enum): RED = '1' BLUE = '2' GREEN = '3' def get_color_return_something(some_color): pass How do I properly add type annotations to the some_color variable in this function, if I suppose that I'll receive an enum attribute from the Color enum (for example: Color.RED)?
accepted answer: http://stackoverflow.com/a/52624948
answer count: 6
possible better answer: http://stackoverflow.com/a/68758590
has answer: http://stackoverflow.com/a/68758590
type: Question
has answer: http://stackoverflow.com/a/64301952
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/79098112
has answer: http://stackoverflow.com/a/52624948
tagged with: python
upvote count: 149
tagged with: python-typing
has answer: http://stackoverflow.com/a/68519883
has title: Type annotations for Enum attribute
score: 149
has answer: http://stackoverflow.com/a/52624924

http://stackoverflow.com/comment/92258560
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52664315
has text: I closed as duplicate, the answers provide all the use cases, your question is covered, I feel that there's no need to clutter the site with more answers. thanks to other goldbadge owners for adding more relevant dupes.
type: Comment

http://stackoverflow.com/a/52646080
upvote count: 2
has comment: http://stackoverflow.com/comment/92224202
has comment: http://stackoverflow.com/comment/92225388
answers question: http://stackoverflow.com/q/52646004
type: Answer
has body: You try to add values to same dictionary every time in the loop and as loop progresses, you keep replacing the values. You need to define dictionary in every iteration to create separate references of the dictionary: def update_dict(): f = [] for i, j in enumerate(list_range): test_dict = {'a': i} j['c'] = test_dict f.append(j) print(f) list_range = [{'b': i} for i in range(0, 5)] update_dict() # [{'b': 0, 'c': {'a': 0}}, # {'b': 1, 'c': {'a': 1}}, # {'b': 2, 'c': {'a': 2}}, # {'b': 3, 'c': {'a': 3}}, # {'b': 4, 'c': {'a': 4}}]
has comment: http://stackoverflow.com/comment/92224569
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/92224366
has comment: http://stackoverflow.com/comment/92224515
has comment: http://stackoverflow.com/comment/92225846
has comment: http://stackoverflow.com/comment/92224906

series
tag name: series
tags question: http://stackoverflow.com/q/52616959
type: Tag
tags question: http://stackoverflow.com/q/52612333
tags question: http://stackoverflow.com/q/52679418
tags question: http://stackoverflow.com/q/52736900
tags question: http://stackoverflow.com/q/52746012
tags question: http://stackoverflow.com/q/52612471
tags question: http://stackoverflow.com/q/52687240
tags question: http://stackoverflow.com/q/52656330
tags question: http://stackoverflow.com/q/52699153
tags question: http://stackoverflow.com/q/52664433
tags question: http://stackoverflow.com/q/52671308
tags question: http://stackoverflow.com/q/52698072
tags question: http://stackoverflow.com/q/52689825
tags question: http://stackoverflow.com/q/52668209
tags question: http://stackoverflow.com/q/52594959
tags question: http://stackoverflow.com/q/52632912
tags question: http://stackoverflow.com/q/52603891
tags question: http://stackoverflow.com/q/52726042
tags question: http://stackoverflow.com/q/52709872
tags question: http://stackoverflow.com/q/52687216
tags question: http://stackoverflow.com/q/52609585
tags question: http://stackoverflow.com/q/52615056
tags question: http://stackoverflow.com/q/52693136

http://stackoverflow.com/q/52616338
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52630999
tagged with: http://stackoverflow.com/tag/mp3
type: Question
answer count: 2
downvote count: 0
has body: I have my personal mp3 collection which partially damaged after my HDD broken. I need find names of damaged mp3s inside quite a lot (aprox. >5k files) in folders and sub-folders. Can you please give me a tip about python 3 libraries which can open mp3 file, read it and find bit rate issues in it.
score: 2
accepted answer: http://stackoverflow.com/a/52630999
favorite count: 0
tagged with: python-3.x
has title: How to find broken mp3 files with python 3?
upvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/52617026
has answer: http://stackoverflow.com/a/52617026

http://stackoverflow.com/comment/92247445
has text: Could we see how `i` is defined in the `calculations` file?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52658443

http://stackoverflow.com/comment/92155756
comment on: http://stackoverflow.com/q/52610672
score: 1
has text: I think you should use iloc instead of loc in the `new_names.append(df_tags.loc[j][1])` but it's hard guessing. Can you post part of df_input and df_tags?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52718705
has body: I needed to run both from the same webserver. I used python/flasks development server for testing purposes but the main idea is the same and should work with other scenarios. I added the routes and handled them using flasks template renderer from flask import render_template @app_instance.app.route('/') @app_instance.app.route('/create') @app_instance.app.route('/snippet/&lt;path:path&gt;') #dynamic route def index(path=None): return render_template("index.html") And configured Nginx to handle the requests. server { listen 80; listen [::]:80; server_name somedomain; root some/path/to_the/front/dist; index index.html; location / { try_files $uri /index.html; gzip_static on; } } Result I can now make requests from the front end to http://127.0.0.1:5000/api/snippets/api since flask is operating on that port and I also have access to my index.html without using the 5000 port.
score: 0
answers question: http://stackoverflow.com/q/52697848
type: Answer
accepted answer of: http://stackoverflow.com/q/52697848
type: AcceptedAnswer

http://stackoverflow.com/comment/92183387
has text: i just ran the updated code and it dropped the first column "icense_number"
type: AnswerComment
comment on: http://stackoverflow.com/a/52624740
type: Comment
score: 1

http://stackoverflow.com/comment/92213095
type: Comment
comment on: http://stackoverflow.com/a/52640164
type: AnswerComment
has text: I updated my EB CLI version but still same error issue is while installing EB CLI version shows awsebcli-3.14.6 and if i try this command eb --version it show AWS Elastic Beanstalk Command Line Interface v2.6.5 what should i do
score: 0

http://stackoverflow.com/comment/92268628
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52669097
has text: HI Divakar, I cannot test your code because I get the follwoing error. module 'numpy' has no attribute 'take_along_axis'. Although I am importing numpy as np. any idea?
score: 0

scikit-learn
tags question: http://stackoverflow.com/q/52727700
tags question: http://stackoverflow.com/q/52661363
tags question: http://stackoverflow.com/q/52614267
tags question: http://stackoverflow.com/q/52628272
tags question: http://stackoverflow.com/q/52592107
tags question: http://stackoverflow.com/q/52606360
tags question: http://stackoverflow.com/q/52637106
tags question: http://stackoverflow.com/q/52609929
tags question: http://stackoverflow.com/q/52724006
tags question: http://stackoverflow.com/q/52596609
tags question: http://stackoverflow.com/q/52720270
tags question: http://stackoverflow.com/q/52594585
tags question: http://stackoverflow.com/q/52629035
tags question: http://stackoverflow.com/q/52721773
tags question: http://stackoverflow.com/q/52590111
tags question: http://stackoverflow.com/q/52617729
tags question: http://stackoverflow.com/q/52618490
tags question: http://stackoverflow.com/q/52717060
tags question: http://stackoverflow.com/q/52592434
tags question: http://stackoverflow.com/q/52648383
tags question: http://stackoverflow.com/q/52604751
tags question: http://stackoverflow.com/q/52733998
tags question: http://stackoverflow.com/q/52666142
tags question: http://stackoverflow.com/q/52732600
tags question: http://stackoverflow.com/q/52728958
tags question: http://stackoverflow.com/q/52712254
tags question: http://stackoverflow.com/q/52675842
tags question: http://stackoverflow.com/q/52592549
tags question: http://stackoverflow.com/q/52702986
tags question: http://stackoverflow.com/q/52600611
tags question: http://stackoverflow.com/q/52739346
tags question: http://stackoverflow.com/q/52728119
tags question: http://stackoverflow.com/q/52722912
tags question: http://stackoverflow.com/q/52674498
tags question: http://stackoverflow.com/q/52644634
tags question: http://stackoverflow.com/q/52665061
tags question: http://stackoverflow.com/q/52642940
tags question: http://stackoverflow.com/q/52746769
tag name: scikit-learn
tags question: http://stackoverflow.com/q/52679784
tags question: http://stackoverflow.com/q/52724468
tags question: http://stackoverflow.com/q/52596204
tags question: http://stackoverflow.com/q/52609734
tags question: http://stackoverflow.com/q/52684331
tags question: http://stackoverflow.com/q/52621438
tags question: http://stackoverflow.com/q/52733452
type: Tag
tags question: http://stackoverflow.com/q/52636337
tags question: http://stackoverflow.com/q/52612841
tags question: http://stackoverflow.com/q/52591137
tags question: http://stackoverflow.com/q/52735192
tags question: http://stackoverflow.com/q/52701594
tags question: http://stackoverflow.com/q/52739532
tags question: http://stackoverflow.com/q/52654280
tags question: http://stackoverflow.com/q/52742283
tags question: http://stackoverflow.com/q/52742984
tags question: http://stackoverflow.com/q/52746279
tags question: http://stackoverflow.com/q/52698815
tags question: http://stackoverflow.com/q/52640386
tags question: http://stackoverflow.com/q/52633319
tags question: http://stackoverflow.com/q/52740089
tags question: http://stackoverflow.com/q/52746193
tags question: http://stackoverflow.com/q/52650100
tags question: http://stackoverflow.com/q/52740254
tags question: http://stackoverflow.com/q/52717219
tags question: http://stackoverflow.com/q/52629767
tags question: http://stackoverflow.com/q/52599933
tags question: http://stackoverflow.com/q/52720733
tags question: http://stackoverflow.com/q/52611498
tags question: http://stackoverflow.com/q/52653993
tags question: http://stackoverflow.com/q/52661107

http://stackoverflow.com/q/52687495
downvote count: 3
has answer: http://stackoverflow.com/a/52698384
type: Question
has body: Is there any way in Python to modify a standard class in such a way that 1) the modified class is only seen by one specific application, 2) all instances created within that application use the modified class, and 3) when I upgrade Python, my modifications will not get lost? The standard approach would involve creating a child of the class in question. This would satisfy requirement #1 and #3, but not #2, and that doesn't help me at all (unfortunately, I do not control the creation of the class's instances, I would have to rewrite a lot of other people's code). I imagine I could modify the actual class source in Python/lib/..., but that would only satisfy requirement #2, not #1 and #3. Also, it would only work for me - if I wanted to give the final application to someone else, they would also have to modify their library code, which can't really be expected. Unfortunately, I am not familiar enough with Python to know any other solutions. I know that with Delphi, I could either use a method hook, possibly in combination with a class helper, or simply copy the library file involved to my application's directory and modifying it there - that file would take precedence over the system library. Can I do something like that in Python, preferably both in version 2 and 3? (Specifically, I need to modify the standard HTTPConnection and the Urllib's HTTPConnectionPool.)
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Modify a standard class for one application only
type: UnansweredQuestion
score: -3
tagged with: python
upvote count: 0

http://stackoverflow.com/q/52627739
answer count: 2
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: lstm
linked to: http://stackoverflow.com/q/51469446
has title: How to Merge Numerical and Embedding Sequential Models to treat categories in RNN
has answer: http://stackoverflow.com/a/61404379
has comment: http://stackoverflow.com/comment/92190851
has comment: http://stackoverflow.com/comment/92191906
accepted answer: http://stackoverflow.com/a/52629902
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/92190450
upvote count: 17
type: AnsweredQuestion
has body: I would like to build a one layer LSTM model with embeddings for my categorical features. I currently have numerical features and a few categorical features, such as Location, which can't be one-hot encoded e.g. using pd.get_dummies() due to computational complexity, which is what I originally intended to do. Let's visualise an example: Sample Data data = { 'user_id': [1,1,1,1,2,2,3], 'time_on_page': [10,20,30,20,15,10,40], 'location': ['London','New York', 'London', 'New York', 'Hong Kong', 'Tokyo', 'Madrid'], 'page_id': [5,4,2,1,6,8,2] } d = pd.DataFrame(data=data) print(d) user_id time_on_page location page_id 0 1 10 London 5 1 1 20 New York 4 2 1 30 London 2 3 1 20 New York 1 4 2 15 Hong Kong 6 5 2 10 Tokyo 8 6 3 40 Madrid 2 Let's look at the person visiting a website. I'm tracking numerical data such as time on page and others. Categorical data includes: Location (over 1000 uniques), Page_id (> 1000 uniques), Author_id (100+ uniques). The simplest solution would be to one-hot encoding everything and put this into LSTM with variable sequence lengths, each timestep corresponding to a different page view. The above DataFrame will generate 7 training samples, with variable sequence lengths. For example, for user_id=2 I will have 2 training samples: [ ROW_INDEX_4 ] and [ ROW_INDEX_4, ROW_INDEX_5 ] Let X be the training data, and let's look at the first training sample X[0]. From the picture above, my categorical features are X[0][:, n:]. Before creating sequences, I factorized the categorical variables into [0,1... number_of_cats-1], using pd.factorize() so the data in X[0][:, n:] is numbers corresponding to their index. Do I need to create an Embedding for each of the Categorical Features separately? E.g. an embedding for each of x_*n, x_*n+1, ..., x_*m? If so, how do I put this into Keras code? model = Sequential() model.add(Embedding(?, ?, input_length=variable)) # How do I feed the data into this embedding? Only the categorical inputs. model.add(LSTM()) model.ad…
has answer: http://stackoverflow.com/a/52629902
score: 17
possible better answer: http://stackoverflow.com/a/61404379
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/92372485
has text: Ah that makes sense!
type: AnswerComment
comment on: http://stackoverflow.com/a/52723550
score: 0
type: Comment

http://stackoverflow.com/comment/92323938
type: QuestionComment
score: 3
has text: PATCH/PUT only applies to an instance, not the list of instance. Your url should be like http://127.0.0.1:8000/usertitles/123/
comment on: http://stackoverflow.com/q/52698369
type: Comment

http://stackoverflow.com/comment/92254743
comment on: http://stackoverflow.com/q/52661840
score: 0
type: Comment
type: QuestionComment
has text: i know the regex pattern is not right,but is there any way to get this@norok2

http://stackoverflow.com/comment/92210192
has text: @c2huc2hu: Amusingly, it's only called if something goes wrong. It should still be cleaned up on interpreter exit, but there have been bugs in the interpreter causing files to go unflushed even though they're supposed to be cleaned up on exit.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52638621
type: Comment

http://stackoverflow.com/comment/92375771
has text: What is the problem you are having? I wanted to provide you with an answer but then when I copy pasted your code, I found missing modules, and no data. That's enough for several people including me to just skip your question and move on to answer other. Therefore, it would be best if you provide a reproducible code. And yes, your code seems perfectly fine
comment on: http://stackoverflow.com/q/52724468
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52592177
answers question: http://stackoverflow.com/q/52589682
has comment: http://stackoverflow.com/comment/92148122
type: AcceptedAnswer
has body: root is the old (pre-conda 4.4) name for the main environment; in conda 4.4, it was renamed to be base. Most likely the reason you have a Jupyter environment named root is because you have a kernel installed with that name in it.
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52589682
score: 9
upvote count: 9

http://stackoverflow.com/a/52717796
has comment: http://stackoverflow.com/comment/92364014
has body: If you want to check that all required column headers are present, you can use sets, and use the columns attribute of a dataframe: if set(required_columns) &lt;= set(df.columns): print("all required columns are there") If you need to find the missing required columns, use the set difference, with the required columns first (so that additional columns are ignored): missing = set(required_columns) - set(df.columns) and combine the two as follows: missing = set(required_columns) - set(df.columns) if missing: print("Missing required columns:", missing)
has comment: http://stackoverflow.com/comment/92364489
has comment: http://stackoverflow.com/comment/92363236
answers question: http://stackoverflow.com/q/52717580
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52717580

http://stackoverflow.com/a/53051487
score: 19
upvote count: 19
has comment: http://stackoverflow.com/comment/138755968
answers question: http://stackoverflow.com/q/52625307
has body: similar question raised here: https://github.com/has2k1/plotnine/issues/152 from plotnine import * from plotnine.data import mpg from mizani.formatters import percent_format p = ggplot(mpg) + geom_bar(aes(x='manufacturer', fill='class'), position='fill') p = p + scale_y_continuous(labels=percent_format()) print(p) other predefined filters can be found here: https://mizani.readthedocs.io/en/stable/formatters.html
downvote count: 0
type: Answer

http://stackoverflow.com/q/52687990
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/92304256
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/92303314
has answer: http://stackoverflow.com/a/52688059
type: UnansweredQuestion
tagged with: python
has title: Error crawling through locally hosted website
type: Question
has body: I want to crawl through a website, which is currently hosted locally. Isn't it possible to crawl locally hosted website? I am getting this error: File "C:/Users/hero/PycharmProjects/project/Crawler.py", line 22, in &lt;module&gt; imagefile.write(urllib.request.urlopen("http://192.168.1.1/Webpage.html"+img_src).read()) urllib.error.HTTPError: HTTP Error 404: Not Found The code for crawler: import urllib.request from bs4 import BeautifulSoup def make_soup(url): thepage = urllib.request.urlopen(url) soupdata = BeautifulSoup(thepage, "html.parser") return soupdata i = 1 soup = make_soup("http://192.168.1.1/Webpage.html") unique_srcs = [] for img in soup.findAll('img'): if img.get('src') not in unique_srcs: unique_srcs.append(img.get('src')) for img_src in unique_srcs: filename = str(i) i = i + 1 imagefile = open(filename + '.png', 'wb') imagefile.write(urllib.request.urlopen("http://192.168.1.1/Webpage.html"+img_src).read()) imagefile.close()
tagged with: web-crawler

http://stackoverflow.com/comment/92401512
has text: Oops, sorry was away from computer to check with my code. And didn't see you're comment. haha thanks! *edited*
comment on: http://stackoverflow.com/a/52738429
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52589054
upvote count: 3
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92113028
has comment: http://stackoverflow.com/comment/92113975
tagged with: matplotlib
has title: df.plot() not showing even after using plt.show()?
tagged with: ipython
tagged with: pandas
has comment: http://stackoverflow.com/comment/92116302
has comment: http://stackoverflow.com/comment/92114058
has comment: http://stackoverflow.com/comment/92112932
favorite count: 0
has comment: http://stackoverflow.com/comment/92114003
type: UnansweredQuestion
tagged with: python
has body: I am working with a California housing price dataframe with multiple columns and want to make a scatter plot between two of them. I am using the following code: df.plot(kind='scatter', x = 'longitude', y='latitude') plt.show() The first line gives me the output: matplotlib.axes._subplots.AxesSubplot at 0x7fbd88118d30 Figure size 432x288 with 2 Axes But it does not show any plot, the command just executes without any error and no new window opens showing the plot. I am using ipython(6.4.0) with python(3.6.5) using anaconda and working on the terminal. I can produce plots by using matplotlib (which opens in a new window) but I want to use the pandas plot function. Any idea why this is not working?
score: 2
answer count: 0

http://stackoverflow.com/comment/92212369
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52606360
has text: I used `df.loc[df['Age'].isna(), 'Age'] = result` and it worked. May I ask why do you use `result.values`? Since the predication value of should be an array but not dictionary. Thank you so much!

http://stackoverflow.com/q/52634441
has answer: http://stackoverflow.com/a/52651353
has body: I have the following peewee model (simplified): class Foo(BaseModel): a = IntegerField() # actually a ForeignKey b = IntegerField(null=True) # ForeignKey c = IntegerField(null=True) # ForeignKey d = TextField() e = TextField(null=True) I want to create a unique index on fields (a, b, c, d) treating NULL values as equal. For example it should be possible to insert (1, NULL, NULL, 2, NULL) only once. I managed to write raw SQL query to add the index (-1 should be safe, since b and c are foreign keys on int>0) CapsuleTranslatorBundle.add_index(SQL('''CREATE UNIQUE INDEX foo_idx ON foo ( a, # a_id if a is a foreign key COALESCE(b, -1), COALESCE(c, -1), d ); ''')) I tried idx = Foo.index(Foo.a, fn.COALESCE(Foo.b, -1), fn.COALESCE(Foo.c, -1), Foo.d, unique=True) Foo.add_index(idx) but got peewee.OperationalError: near "USING": syntax error How can I add the index without using raw SQL?
favorite count: 0
has answer: http://stackoverflow.com/a/52649995
accepted answer: http://stackoverflow.com/a/52651353
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/52649995
type: AnsweredQuestion
score: 1
type: Question
answer count: 2
has title: How to create index on computed fields in peewee
tagged with: peewee
downvote count: 0

http://stackoverflow.com/comment/92284144
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52673683
type: QuestionComment
has text: No problem. It's considered bad practice to use global variables because they generally create confusion, see [this question](https://stackoverflow.com/q/19158339/8201979).

http://stackoverflow.com/comment/92280277
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52675415
type: AnswerComment
has text: @CosmicCat Again, this is because `volume` is defined as a local variable in the `cubeVolume` function. Callers to this function have no access to its local variables, and the proper way that a caller can get a value from a function is through its returning value.

http://stackoverflow.com/q/52653042
has title: Python List Comprehension Flow Control
answer count: 1
score: 0
tagged with: control-flow
has comment: http://stackoverflow.com/comment/92237796
has comment: http://stackoverflow.com/comment/92237889
tagged with: python
type: UnansweredQuestion
has body: Can anyone help me get a list comprehension to run inside a function, It runs from the REPL. I have tried various indentations and placements inside and outside of the while loop and the code will run without error but the ‘newlist’ object is not defined/created I’m using this list comprehension to split the input string of collect_places(). and I cannot see why the comprehension doesn’t produce a new list. INPUT STRING 'uk, london' LIST COMPREHENSION newlist = [str.split(',') for str in placeList] THIS IS THE CODE import sys import re placeList=[] visits=[[],[]] # created for later use def collect_places(): """this function will collect country city pairs""" while True: placed = input('Enter a country and city separated by a comma: ') if placed =="": sys.exit() p=re.search('.*\,.*', placed) try: placeList.append(p.group(0)) except AttributeError as atr: print('Try again') continue newlist = [str.split(',') for str in placeList] THIS IS THE SCRIPT &amp; ERROR collect_places() Enter a country and city separated by a comma: uk,london Enter a country and city separated by a comma: eh Try again Enter a country and city separated by a comma: newlist Traceback (most recent call last): File “&lt;pyshell#343&gt;”, line 1, in newlist NameError: name ‘newlist’ is not defined THIS IS EXECUTED SUCCESSFULLY FROM THE REPL placeList [‘uk,london’] newlist = [str.split(’,’) for str in placeList] newlist ‘uk’, ‘london’
has comment: http://stackoverflow.com/comment/92237745
has comment: http://stackoverflow.com/comment/92243411
has comment: http://stackoverflow.com/comment/92237955
tagged with: list-comprehension
type: Question
has answer: http://stackoverflow.com/a/52656245

http://stackoverflow.com/q/52657192
type: Question
tagged with: indexing
score: 5
possible better answer: http://stackoverflow.com/a/52657224
has comment: http://stackoverflow.com/comment/92245158
has answer: http://stackoverflow.com/a/52657224
accepted answer: http://stackoverflow.com/a/52657207
has body: I know I can have for i in x[::-1]: to loop through a list in reverse order. But what if I want to skip the last element then traverse from high to low? for i in x[-1:0:-1] does not work x = [1,2,3,4,5] =&gt; 4,3,2,1 # desired for i in x[-1:-1]: print(i) # it does not work
favorite count: 0
tagged with: python-3.x
has title: How to loop a list in reverse order and skip last element
has answer: http://stackoverflow.com/a/52657369
tagged with: reverse
tagged with: python
upvote count: 6
answer count: 4
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52657207
has comment: http://stackoverflow.com/comment/92245573
has answer: http://stackoverflow.com/a/52657266
downvote count: 1

http://stackoverflow.com/comment/92326413
type: QuestionComment
has text: The PQuery library just translates the CSS selector to the `"descendant-or-self::*[@id = 'productDetails_detailBullets_sections1']` XPath expression, which is valid. So this is down to lxml now; `r.html.pq[0].xpath("descendant-or-self::table")` indeed only returns 4 elements.
comment on: http://stackoverflow.com/q/52699466
score: 0
type: Comment

http://stackoverflow.com/comment/92266355
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52668124
has text: The output makes sense to me. `hello":"list` doesn't have any spaces between "hello" and "list", so if you remove all the punctuation from it, of course it becomes `hellolist`. I don't think you can remove all punctuation and replace it with exactly one space using only maketrans. You _could_ replace all punctuation with the same number of spaces, so `hello":"list` becomes `hello[three spaces]list`, but that hardly seems ideal.
type: QuestionComment

http://stackoverflow.com/q/52655354
type: Question
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92243431
answer count: 0
upvote count: 3
type: UnansweredQuestion
has body: I made a bunch of attempts to normalize some JSON data that I'm working with, but I need help with it. Here is some sample data: 138 [{'id': 360014, 'default': False, 'name': 'Add/Remove User', 'raw_name': 'Add/Remove User', 'value': 'purpose_add/remove_user'}, {'id': 360014, 'default': False, 'name': 'Change Permissions', 'raw_name': 'Change Permissions', 'value': 'purpose_change_permissions'}, {'id': 360014, 'default': False, 'name': 'Failed Data Validation', 'raw_name': 'Failed Data Validation', 'value': 'purpose_failed_data_validation'}, {'id': 360014, 'default': False, 'name': 'Grant Access', 'raw_name': 'Grant Access', 'value': 'purpose_grant_access'}] 139 [{'id': 360014, 'default': False, 'name': '200 - OK', 'raw_name': '200 - OK', 'value': '200_-_ok'}, {'id': 360014, 'default': False, 'name': '201 - Created', 'raw_name': '201 - Created', 'value': '201_-_created'}, {'id': 360014, 'default': False, 'name': '400 - Bad Request', 'raw_name': '400 - Bad Request', 'value': '400_-_bad_request'}, {'id': 360014, 'default': False, 'name': '404 - Not Found', 'raw_name': '404 - Not Found', 'value': '404_-_not_found'}, {'id': 360014, 'default': False, 'name': '444 - No Response', 'raw_name': '444 - No Response', 'value': '444_-_no_response'}] 140 [{'id': 360014, 'default': False, 'name': 'Pi :: Flow', 'raw_name': 'Pi :: Flow', 'value': 'Pi____Flow'}, {'id': 360014, 'default': False, 'name': 'Pi :: CloudFlare', 'raw_name': 'Pi :: CloudFlare', 'value': 'Pi____cloudflare'}, {'id': 360014, 'default': False, 'name': 'Pi :: Other', 'raw_name': 'Pi :: Other', 'value': 'Pi____other'}, {'id': 360014, 'default': False, 'name': 'Platform :: Stackdriver', 'raw_name': 'Platform :: Stackdriver', 'value': 'platform____stackdriver'}, {'id': 360014, 'default': False, 'name': 'Platform :: AlertSite', 'raw_name': 'Platform :: AlertSite', 'value': 'platform____alertsite'}, {'id': 360014, 'default': False, 'name': 'Platform :: BigQuery', 'raw_name': 'Platform :: BigQuery', 'value': 'platform_…
has comment: http://stackoverflow.com/comment/92242132
score: 3
has title: Normalizing nested JSON data

http://stackoverflow.com/a/52623945
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52619313
has body: Here is a solution in R for the example you provided: # Alleles for each SNP alleles &lt;- data.frame( A1 = c("A", "C", "T"), A2 = c("T", "G", "A"), row.names = paste0("SNP", 1:3) ) # Get the three possible genotypes for each SNP (diallelic loci) genotypes &lt;- apply(alleles, 1, function(x) { paste0(x[c(1, 1, 2)], x[c(1, 2, 2)]) }) # Generate all possible combinations expand.grid(as.data.frame(genotypes)) output SNP1 SNP2 SNP3 1 AA CC TT 2 AT CC TT 3 TT CC TT 4 AA CG TT 5 AT CG TT 6 TT CG TT 7 AA GG TT 8 AT GG TT 9 TT GG TT 10 AA CC TA 11 AT CC TA 12 TT CC TA 13 AA CG TA 14 AT CG TA 15 TT CG TA 16 AA GG TA 17 AT GG TA 18 TT GG TA 19 AA CC AA 20 AT CC AA 21 TT CC AA 22 AA CG AA 23 AT CG AA 24 TT CG AA 25 AA GG AA 26 AT GG AA 27 TT GG AA
score: 3

http://stackoverflow.com/q/52722938
tagged with: grouping
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/4002598
has answer: http://stackoverflow.com/a/52723281
tagged with: python
upvote count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/231767
has comment: http://stackoverflow.com/comment/92371667
type: Question
has comment: http://stackoverflow.com/comment/92378150
has title: Python Equivalent to Ruby's chunk_while?
answer count: 1
has body: I have some interesting using cases in my Ruby code that I want to convert to Python. I think we can leverage in any lib, I mainly use pandas and numpy. For instance, imagine that you have an array of timed events, these events have a timestamp and another properties (an object or a tuple). I want a list/array of groups, where these groups are "contiguous" events, with a grace period of g units (in this case, time units). In my Ruby code I use something like this: grouped_events = events.chunk_while do |previous_event, next_event| next_event.timestamp &lt;= previous_event.timestamp + grace_period end Since I'm not using only in timed events, but with anything that I can sort (so they're comparable somehow), I ask: there's a generic way, or a known lib that does this?
has comment: http://stackoverflow.com/comment/92371917
score: 4
accepted answer: http://stackoverflow.com/a/52723281

http://stackoverflow.com/a/52706046
answers question: http://stackoverflow.com/q/52705870
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: I can't reproduce your problem. But since the second part of your question considers efficiency, I suggest you try a dictionary comprehension. The algorithm still has O(n) complexity but construction in a loop is implemented more efficiently: def num_changer(d, inc=10, k='b'): return {k: v if (k != 'b') or (v &gt;= 0) else v + 10 for k, v in d.items()} dict1 = num_changer(dict1) dict2 = num_changer(dict2) print(dict1, dict2, sep='\n') {'a': 1, 'b': 2, 'c': -1} {'a': -1, 'b': 7, 'c': 3}

http://stackoverflow.com/a/52631494
downvote count: 0
type: Answer
score: 1
has body: If you want better efficiency you can turn ListB into a set so that you can determine if an item is in ListB with an average time complexity of O(1): setB = set(ListB) print(next(i for i, a in enumerate(ListA) if a in setB)) This outputs: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52631029

http://stackoverflow.com/q/52727746
tagged with: django
has comment: http://stackoverflow.com/comment/92380708
tagged with: python
has body: The full error message: Traceback (most recent call last): File "manage.py", line 9, in &lt;module&gt; from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django.core'; 'django' is not a package The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have tried adding django directly to the PYTHONPATH, no dice I have created a virtual environment and installed django in it, still nothing According to pip freeze I got Django 2.1.2 installed I'm pretty sure I'm using python 3.7.0 Apparently I can import django just fine (by just typing "import django" in an empty test.py file), but when I try to import django.core it gives me the following error: Traceback (most recent call last): File "test.py", line 7, in import django.core ModuleNotFoundError: No module named 'django.core'; 'django' is not a package (stackoverflow won't let me format it as code for some reason)
tagged with: import
type: Question
tagged with: python-import
has comment: http://stackoverflow.com/comment/92382181
score: 0
has title: (windows server 2016) (python/Django) Couldn't import Django
has comment: http://stackoverflow.com/comment/92380661
has comment: http://stackoverflow.com/comment/92380735
has comment: http://stackoverflow.com/comment/92380688
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/92408326
score: 2
has text: Now i see, thank you very much for your detailed explanation.
type: AnswerComment
comment on: http://stackoverflow.com/a/52741670
type: Comment

http://stackoverflow.com/comment/92332831
has text: Where did u execute the pip install command? Inside mysql container?
comment on: http://stackoverflow.com/q/52703161
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52688035
accepted answer: http://stackoverflow.com/a/52688207
type: Question
score: 0
answer count: 1
has body: import requests from bs4 import BeautifulSoup urls = ['http://www.freejobalert.com/upsc-advt-no-18/33742/', 'http://www.freejobalert.com/upsc-recruitment/16960/#Engg-Services2019', 'http://www.freejobalert.com/ssc-recruitment/17522/#selection-posts'] for u in urls: page = requests.get(u) c = page.content soup = BeautifulSoup(c, "html5lib") row = soup.find_all("table", {"style":"width: 500px;"})[0].find_all('tr') dict = {} for i in row: for title in i.find_all('span', attrs={'style': 'color: #008000;'}): dict['Title'] = title.text for link in i.find_all('a', attrs={'title':'UPSC'}, href=True): dict['Link'] = link['href'] print(dict) Here I am scraping some specific data from multiple URLs at once.so it is very slow and it is taking more time means 3 times of one URL. Is there any way to make it fast using "workerpool" or "threading" or "multiprocessing" in python. Please help me to integrate on it
has answer: http://stackoverflow.com/a/52688207
tagged with: python
has title: Python implement multi threading or workerpool or multiprocessiong in beautifulsoup for multiple url scraping at once
type: AnsweredQuestion

http://stackoverflow.com/q/52672939
has comment: http://stackoverflow.com/comment/92335985
tagged with: loops
has comment: http://stackoverflow.com/comment/92276481
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92276447
has comment: http://stackoverflow.com/comment/92276677
has body: So I'm trying to send a datframe of VINs to the nhtsa open source api and get the information back. The below works with replacing df['vin'] with an actual vin. However when adding the loop to my function and trying to append, the result is that I get a blank dataframe back instead of the information for the 12 or so VINs. What am I doing wrong? Code below: import pandas as pd import requests #develop the data z = pd.DataFrame(columns = ["vin"], data = ['LHJLC79U58B001633','SZC84294845693987','LFGTCKPA665700387','L8YTCKPV49Y010001', 'LJ4TCBPV27Y010217','LFGTCKPM481006270','LFGTCKPM581004253','LTBPN8J00DC003107', '1A9LPEER3FC596536','1A9LREAR5FC596814','1A9LKEER2GC596611','1A9L0EAH9C596099', '22A000018']) z['manufacturer'] = ['A','A','A','A','B','B','B','B','B','C','C','D','D'] def nhtsa(df): ''' sends VIN to NHTSA for data call ''' for i in df: url = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/' post_fields = {'format': 'json', 'data': df['vin']}; r = requests.post(url, data=post_fields); x = r.json() f = pd.DataFrame(x['Results']) g = f'VIN','Make','Manufacturer','ManufacturerId','ManufacturerType', 'Model','ModelYear', 'ABS','VehicleType', 'BodyClass','DisplacementCC','ErrorCode', 'SuggestedVIN' csv = pd.DataFrame() csv = csv.append(g, ignore_index = True) return csv nhtsa(z)
has comment: http://stackoverflow.com/comment/92328072
answer count: 1
has comment: http://stackoverflow.com/comment/92276043
has comment: http://stackoverflow.com/comment/92276177
has title: Pandas Loop and Append Failure
has comment: http://stackoverflow.com/comment/92276714
has answer: http://stackoverflow.com/a/52700889
type: UnansweredQuestion
tagged with: python
tagged with: append

http://stackoverflow.com/q/52621659
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/52621748
type: Question
has title: Controlling windows command line with python 3
linked to: http://stackoverflow.com/q/48722212
has comment: http://stackoverflow.com/comment/92177757
score: 0
answer count: 1
has body: I would like to start a batch file and send commands to that commands line with python. I tried os module but I did only open windows command line. For example: import os os.system('cmd') // and now in pseudo-code: cd to directory run batch file send commands to that command line
type: UnansweredQuestion

http://stackoverflow.com/q/52629375
upvote count: 3
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/52630953
type: Question
has answer: http://stackoverflow.com/a/52630641
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52630641
answer count: 2
has body: I'm looking to create a function that calculates the Manhattan distance between a selected category and all the other categories in a dataset. The function should then return the CATEGORY with the lowest distance from the selected. df = pd.DataFrame(np.random.randint(0,100, size= (10,4)), columns=list('ABCD')) df['category']= ['apple','orange','grape','berry','strawberry','banana','kiwi','lemon','lime','pear'] The code below returns the smallest 4 distances which includes the selected category (distance = 0; which is redundant and not needed). I need the code to only return the lowest 3 distances as a list of categories, the first being the smallest. def distance(row): cols = list('ABCD') return (df[cols] - row[cols]).abs().sum(axis=1) df.set_index('category', inplace=True) dist = df.apply(distance, axis=1) dist['apple'].nsmallest(4) For instance, if "Apple" was selected, and the three lowest distances from Apple were Berry, Orange and Grape, return should look like this: ["Berry", "Orange","Grape"]
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/92971320
has title: Calculate Manhattan Distance return Category with lowest distance
favorite count: 0
has answer: http://stackoverflow.com/a/52630953
tagged with: python
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/52717580
has title: find missing column header in excel using python
score: 0
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/52717796
has comment: http://stackoverflow.com/comment/92364283
possible better answer: http://stackoverflow.com/a/52717802
type: Question
type: AnsweredQuestion
has body: I would like to find if all the required column names are present in the excel using python. for example: Header1 Header2 Header3 Val1 Val4 Val6 Val2 val5 Val7 I want to know if header4 is present or not I use the following: import pandas as pd path=C:\Req_file\excel_file xl = pd.Excelfile(path) for name in xl.sheet_names: df = pd.read_excel(xl, name) my_cols = [Header1, Header2,Header3,Header4] print(df[my_cols]) It generates a Keyerror: [header4] not in index I would like to know is it possible to do with "if" statement. I want to generate an error message on the frame, but I get only in the terminal. Thanks a lot in advance.
has comment: http://stackoverflow.com/comment/92365129
has comment: http://stackoverflow.com/comment/92360950
has answer: http://stackoverflow.com/a/52717796
has answer: http://stackoverflow.com/a/52717802
answer count: 2
has comment: http://stackoverflow.com/comment/92364837

http://stackoverflow.com/comment/92308998
type: QuestionComment
has text: I know that functions can be called twice, but im unsure at when the program knows when to call the 'minutes' parameters after the 'hours' parameters are passed through
comment on: http://stackoverflow.com/q/52690801
score: 0
type: Comment

http://stackoverflow.com/q/52691905
tagged with: key-value
type: Question
accepted answer: http://stackoverflow.com/a/52692300
has answer: http://stackoverflow.com/a/52693862
tagged with: python
tagged with: dictionary
has title: Match a value to key value and get key
has comment: http://stackoverflow.com/comment/92311147
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/52692383
has answer: http://stackoverflow.com/a/52692219
upvote count: 1
has comment: http://stackoverflow.com/comment/92310895
downvote count: 1
has comment: http://stackoverflow.com/comment/92310865
answer count: 5
has comment: http://stackoverflow.com/comment/92310848
possible better answer: http://stackoverflow.com/a/52692344
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52692344
has comment: http://stackoverflow.com/comment/92310834
has body: let's say I need do this: I need to match the values in list 'check_keys' against the key-values in dictionary 'parm' and store the matched keys in the same order into a new list 'insert' parm = {'f': 'w', 'l': 'b', 'b': 'y', 'u': 'o', 't': 'r', 'r': 'g'} check_keys = ['r','b','o','g','w','y'] insert = ['t','l','u','r','f','b']
has answer: http://stackoverflow.com/a/52692300
has comment: http://stackoverflow.com/comment/92310825
favorite count: 0

http://stackoverflow.com/comment/92162177
has text: This worked! I can't thank you enough, I've been reworking this for ages trying to find the problem and finally understand what's wrong. Thank you again for your help!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52613841
type: Comment

http://stackoverflow.com/comment/92154612
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52610160
has text: You should use `for line in files.readlines():`
score: 1

http://stackoverflow.com/q/52637766
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/92208587
upvote count: 0
has body: I have been trying to horizontally reverse the matrix in Python. input 1 0 1 0 output 0 1 0 1 Here is the code... class Reversedmat(object): def __list_oflist__(self,mat) rows = len(mat) columns = len(mat[0]) for i in range(0, len(mat)): reversed_mat = "" for j in range(0, len(mat[i])): reversed_mat += str(mat[i][j]) + "\t" ## this is where im print(reverse(reversed_mat)) if __name__ == "__main__": mat =[[1,0],[1,0]] print(Reversedmat().__list_oflist__(mat)) I have been trying to do this in Python, but I was not able to achieve. Any help is much appreciated! Thanks
answer count: 1
favorite count: 0
has title: Reverse of a list of list in Python
tagged with: python
has answer: http://stackoverflow.com/a/52637876
score: -4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52637876
has comment: http://stackoverflow.com/comment/92209874

lxml
tags question: http://stackoverflow.com/q/52659132
tags question: http://stackoverflow.com/q/52691503
tags question: http://stackoverflow.com/q/52645690
tags question: http://stackoverflow.com/q/52645431
type: Tag
tags question: http://stackoverflow.com/q/52681662
tags question: http://stackoverflow.com/q/52606692
tags question: http://stackoverflow.com/q/52608218
tags question: http://stackoverflow.com/q/52667632
tags question: http://stackoverflow.com/q/52746029
tag name: lxml
tags question: http://stackoverflow.com/q/52636648

http://stackoverflow.com/a/52626602
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/92186722
has comment: http://stackoverflow.com/comment/92219528
answers question: http://stackoverflow.com/q/52624875
has comment: http://stackoverflow.com/comment/92187451
downvote count: 0
score: 1
has body: The cronitem object is not a string and therefore does not have the attribute split. You can cast it to a str before you try to split. For example: from crontab import CronTab import datetime from croniter import croniter as ci cron = CronTab("pfmuser") for cronitem in cron: cronitemstr = str(cronitem) hour = cronitemstr.split()[1] minutes = cronitemstr.split()[0] minutesint = None hourint = None try: hourint = int(hour) minutesint = int(minutes) except ValueError as e: print e.message print hourint print minutesint if hourint &gt;= 16 and minutesint &lt;= 20: print('found a job running between 16 and 20') cronitemstr = cronitemstr[:cronitemstr.index(cronitemstr.split()[5])] iter = ci(cronitemstr) next_run = iter.get_next() last_run = iter.get_prev() next_run_datetime = datetime.datetime.fromtimestamp(next_run) last_run_datetime= datetime.datetime.fromtimestamp(last_run) print 'the next run is at {}'.format(next_run_datetime) print 'the last run was at {}'.format(last_run_datetime)

http://stackoverflow.com/a/52595586
upvote count: 5
answers question: http://stackoverflow.com/q/52595510
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can't rely on is working with string literals. Even when it works, it's an implementation detail of CPython, and in this case, even CPython's implementation doesn't support it, because CPython only automatically interns string literals that fit the rules for identifiers (that is, variable names). Your string contains .s, which means it's not automatically interned. You can see this easily at the interactive prompt: &gt;&gt;&gt; x = 'shapely.geometry.base' # Not a legal variable name &gt;&gt;&gt; y = 'shapely.geometry.base' &gt;&gt;&gt; x is y False &gt;&gt;&gt; x = 'abc123' # Legal variable name &gt;&gt;&gt; y = 'abc123' &gt;&gt;&gt; x is y True Basically, change your test to != 'shapely.geometry.base', and if you need more details, read up on the difference between is and ==. I'll note that your test is flawed in other ways. Right now, you require the immediate parent to be defined in shapely.geometry.base. But if you subclass a valid class, the child will be invalid (because the __base__ will refer to the subclass from the other module, not ultimate base class in shapely.geometry.base). A better solution is proper isinstance checking based on known good base classes, e.g.: # Top of file from shapely.geometry.base import BaseGeometry, GeometrySequence # Test code (passing a tuple of legal bases classes is allowed) if not isinstance(footprint, (BaseGeometry, GeometrySequence)): raise TypeError('footprint input geometry is not a shapely geometry based object') which, on top of being more explicit about what you want (explicitly enumerating legal base classes), and allowing indirect subclasses of the classes in question rather than only direct subclasses of a handful of base classes from that module, avoids allowing spurious types like CAP_STYLE and JOIN_STYLE (which, while defined in shapely.geometry.base, appear to exist largely as simple enum-like classes of constants, not actual geometry related things, and are likely not types you'd want to allow).
accepted answer of: http://stackoverflow.com/q/52595510

http://stackoverflow.com/comment/105120738
score: 0
type: AnswerComment
has text: Sure, but then it doesn't answer the (and my) question.
type: Comment
comment on: http://stackoverflow.com/a/52703116

http://stackoverflow.com/comment/92264904
type: Comment
type: QuestionComment
score: 2
has text: Your question says "each a[i], b[j], c[k] length larger than 10", but your code has a different test. Which is it supposed to be? Also, if there are multiple solutions, it looks like you only want the first solution found. Is that correct?
comment on: http://stackoverflow.com/q/52667345

http://stackoverflow.com/comment/122257356
type: Comment
comment on: http://stackoverflow.com/a/52644764
has text: @mak What's wrong with my solution? Without justification I will not spend time looking for another solution.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/92397690
comment on: http://stackoverflow.com/a/52735372
type: AnswerComment
score: 0
type: Comment
has text: so it means that there can be the small number of inputs and a large number of outputs. So What I didn't understand is in your image number of xt and number of ht are same. so when there's a large number of ht how is it produces . could you please give a visulaization to it. @Daniel

http://stackoverflow.com/comment/92367077
comment on: http://stackoverflow.com/a/52715368
score: 1
has text: "_It is faster_" primarily because it doesn't do the same thing as the OP's code. In fact, if you structure your code like this, `myop` is invoked exactly 5 times. For `count` `myopp` applications will be simply discarded from the execution plan. Change `count` to `c1.foreach(_ => ())` (or you want to squeeze as much as possible `c1.queryExecution.toRdd.foreach(_ => ())`) and measure the time to see what I mean.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92314139
type: QuestionComment
comment on: http://stackoverflow.com/q/52692120
has text: @AndrewMcDowell ...an error like this before. obvs it indicates that Amazon is actively refusing my connection on that page. not sure why only the additional `if` statement would invoke that
score: 0
type: Comment

http://stackoverflow.com/q/52733824
has title: How to properly manage Pipfile.lock
tagged with: devpi
type: Question
tagged with: pipenv
upvote count: 2
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
downvote count: 0
has body: This is my scenario: I am using pipenv I have private sources: source url = "http://devpi.mine/something/dev/+simple" verify_ssl = false name = "mysource" I have different environments: dev for development, with a private devpi where packages are upload, and int / preprod / prod with a shared devpi. Generating Pipfile.lock takes time (5min) My problem: the Pipfile.lock that I am generating in dev is not usable in int, because the hashes do not match (different devpi) Possible solutions: Generate Pipfile.lock.dev and Pipfile.lock.int, and manage that myself (symlinks or renaming the file): a bit cumbersome Generate Pipfile.lock as part of the release process: I don't like this because that means that Pipfile.lock is not used as reference, since each time it will be re-generated. Besides, this would slow down release. Do you have any other idea how to manage different environments in the context of pipenv?

http://stackoverflow.com/q/52711728
has comment: http://stackoverflow.com/comment/105261285
tagged with: postgresql
has title: How to update unittests when migrating from sqlite to postgres (django)
has body: I have a somewhat large Django project with many views/models. I recently migrated my project from sqlite3 to postgres locally, and plan to scale it out even further (put postgres on a separate machine, etc). I followed these instructions when I migrated from sqlite to postgres, and it appears to have worked perfectly. (ie, my running app looks identical to when the db was sqlite) My issue is this: When I run my previously-written unittests, the first unittest works and all proceeding unittests fail. Individually, the unittests work fine. I've seen some other posts on stackoverflow that addressed this issue, but the solutions were so unclear. How can I rework my setUp()/ teardown() methods for my unittests so that they will pass with my newly migrated postgres db? Do i need to completely rewrite all unittests? I've seen the pytest-postgresql library, although I'm not entirely sure how to modify my unittests based off of this. My testing suite is set up with different classes that test views. So for example, class View1Tests(TestCase): def setUp(self): c1 = Category.objects.create(id=55555, leaf_node_name="Test Category 1") c2 = Category.objects.create(id=12345, leaf_node_name="Test Category 2") s1 = Search.objects.create(category=c1, username="testuser") s2 = Search.objects.create(category=c2, username="testuser2") def test_view1_success(self): #blablabla def test_view1_fail(self): #blablabla def test_view1_something(self): #blablabla I'm getting errors like this: appname.models.DoesNotExist: Search matching query does not exist. Again, all of these unittests run perfectly fine when sqlite3 was the db. I think its an issue with the postgres testing settings? But I'm at a loss as to where to even begin. Any help would be appreciated!!
has answer: http://stackoverflow.com/a/59547818
tagged with: python
downvote count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/92377602
type: Question
score: 1
tagged with: python-unittest
tagged with: pytest-django
has comment: http://stackoverflow.com/comment/102041755
has comment: http://stackoverflow.com/comment/105264684
has comment: http://stackoverflow.com/comment/92376853
linked to: http://stackoverflow.com/q/48815872
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/92471201
type: Comment
comment on: http://stackoverflow.com/a/52740411
type: AnswerComment
score: 0
has text: Why is "qs = queryset[:query_max_limit+1]" and not "qs = queryset[:query_max_limit]"

http://stackoverflow.com/q/52700287
score: -1
has answer: http://stackoverflow.com/a/52700406
tagged with: replace
tagged with: pandas
upvote count: 0
answer count: 1
has title: Replace specific substring in match python
accepted answer: http://stackoverflow.com/a/52700406
favorite count: 0
has body: I was to use regex to replace a substring of a matched string in a df series. I have looked through the documentation (e.g. HERE ) and I have found a solution that is able to capture the specific type of string that I want to match. However, during the replace, it does not replace the substring. I have cases such as data initthe problem nationthe airline radicthe groups professionthe experience the cat in the hat In this particular case, I am interested in substituting "the" with "al" in those cases where "the" is not a standalone string (i.e. preceeded and followed by whitespaces). I have tried the following solution: patt = re.compile(r'(?:[a-z])(the)') df['data'].str.replace(patt, r'al') However, it also replaces the non-whitespace character preceding the "the". Any suggestions on how what I can do to just repalce those specific cases of a substring?
has comment: http://stackoverflow.com/comment/92327125
tagged with: python
tagged with: regex
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/25384333
linked to: http://stackoverflow.com/q/32698614
downvote count: 1
linked to: http://stackoverflow.com/q/38565849
type: Question
duplicate of: http://stackoverflow.com/q/32698614

http://stackoverflow.com/q/52693824
has title: Google Cloud Functions - how do I authenticate to AWS S3 bucket?
has body: I am trying to get a Google Cloud Function in Python 3.7 to take a file from Google Cloud Storage and upload it into AWS S3. In the command line, I would authenticate with awscli and then use the gsutil cp command to copy the file across. I have translated this process into python as: import subprocess def GCS_to_s3(arg1, arg2): subprocess.call(["aws configure set aws_access_key_id AKIA********"], shell=True) subprocess.call(["aws configure set aws_secret_access_key EgkjntEFFDVej"], shell=True) subprocess.call(["gsutil cp gs://test_bucket/gcs_test.csv s3://mybucket)"], shell=True)` The requirements.txt is: awscli google-cloud-storage This function deploys successfully and runs successfully but the output does not show up in the S3 bucket. What would be the best way of writing such a function?
tagged with: google-cloud-functions
tagged with: python
has answer: http://stackoverflow.com/a/52727262
type: AnsweredQuestion
tagged with: amazon-s3
accepted answer: http://stackoverflow.com/a/52727262
score: 4
type: Question
upvote count: 4
tagged with: google-cloud-platform
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/92169983
score: 0
type: AnswerComment
type: Comment
has text: Thank you, let me explain a little bit. we have a code with 10000 lines. Inside of this code we have more than 10 functions. Which one of these 10 function sshould be used in the whole code? we dont know, it will be decided by the user. If user turns 1, 4,6,7 on, so we have a code using these functions and other functions are out of use. If the user turns 8, 9 10, we have a code using function 8 9 10 and other functions are off.
comment on: http://stackoverflow.com/a/52617941

http://stackoverflow.com/comment/92201839
type: AnswerComment
comment on: http://stackoverflow.com/a/52634238
type: Comment
score: 1
has text: I don't get the impression that the OP needs to *keep* converting until they have five invalid inputs. The clear intent is to perform a *single* conversion, allowing up to five attempts to provide a valid value if an invalid input is provided, but ending immediately if a valid input is provided and converted.

http://stackoverflow.com/a/52666529
has comment: http://stackoverflow.com/comment/92263209
score: 0
type: Answer
has body: If this is represented as a string or you can easily get it to one, simply split it by the '\' character and access [1] and [2] indexes to get them. s = r"e\x00\x01\x01\xff\xff\xff".split(r"\x") # r prefixed the string to avoid having to escape the backslashes int1 = int(s[1], 16) # the second argument is the base, here, hexadecimal int2 = int(s[2], 16) print(int1) # 2 print(int2) # 1 If it's a byte object, you can already access it with indexes. Just print(s[1]) print(s[2]) to get the values you need
answers question: http://stackoverflow.com/q/52665942

http://stackoverflow.com/comment/92350312
type: QuestionComment
has text: Is there anything you could help me in this?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52621585

http://stackoverflow.com/a/52675720
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/52675607
has body: normal calls cont2_array* https://github.com/numpy/numpy/blob/master/numpy/random/mtrand/mtrand.pyx#L1651 and there is a lock Is this the reason? Can you try to use individual RandomState to generate random numbers? r = numpy.random.RandomState() ..... for ... : x += r.normal(0, noise_sigma, x.shape) / 255.0
has comment: http://stackoverflow.com/comment/92280853
accepted answer of: http://stackoverflow.com/q/52675607
upvote count: 3
has comment: http://stackoverflow.com/comment/92281228

http://stackoverflow.com/q/52686488
score: 1
type: Question
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/92316327
downvote count: 0
favorite count: 0
has title: Send emails with attachments from my address using Gmail API with API key
has comment: http://stackoverflow.com/comment/92314128
tagged with: python
tagged with: gmail-api
has comment: http://stackoverflow.com/comment/92318061
has body: I revised the demonstrated CreateMessageWithAttachment Python codes on Users.messages: send. The only difference is that I return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode("UTF-8")} instead of {'raw': base64.urlsafe_b64encode(message.as_string())} because the latter is actually causing errors. After that, I tried to send myself an email with an attachment: userID = my_email_address API_KEY = my_api_key # my_api_key was generated under my_email_address on GCP email_content = CreateMessageWithAttachment(userID, userID, "Test API", "This is a test.", file_dir, filename) r = requests.post( url="https://www.googleapis.com/gmail/v1/users/{}/messages/send?key={}".format(userID, API_KEY), data=json.dumps(email_content) ) if r.status_code == 200: print("Succeed!") else: print(r.status_code) I am getting 401 as status code now, which seems like an authorization issue. However, I have no idea where to start to solve this problem. I am sure the API key is correct and it is permitted to call Gmail API. One similar question on SO is How to access a gmail account I own using Gmail API?, but as a local cronjob, I don't know how to "Register my App at Google" like the answer suggested.
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37534548
upvote count: 1

http://stackoverflow.com/a/52702955
score: 0
has comment: http://stackoverflow.com/comment/92332391
type: Answer
accepted answer of: http://stackoverflow.com/q/52702411
answers question: http://stackoverflow.com/q/52702411
type: AcceptedAnswer
has body: Try this: Example data: perf = pd.DataFrame({'price':[100.1, 1.1, 3.5, 400, 3.1, 651, 39]}) Added code: test['peaks'] = False test['valleys'] = False test['peaks'].loc[peaks] = True test['valleys'].loc[valleys] = True Example output: index price peaks valleys 0 0 100.1 False False 1 1 1.1 False True 2 2 3.5 False False 3 3 400.0 True False 4 4 3.1 False True 5 5 651.0 True False 6 6 39.0 False False If you want to add a column with last peak and valley: test['last_peak'] = test.loc[peaks[0][-1]].price test['last_valley'] = test.loc[valleys[0][-1]].price Output: index price peaks valleys last_peak last_valley 0 0 100.1 False False 651.0 3.1 1 1 1.1 False True 651.0 3.1 2 2 3.5 False False 651.0 3.1 3 3 400.0 True False 651.0 3.1 4 4 3.1 False True 651.0 3.1 5 5 651.0 True False 651.0 3.1 6 6 39.0 False False 651.0 3.1 Is it what you want?

http://stackoverflow.com/comment/92317634
comment on: http://stackoverflow.com/a/52695603
type: Comment
has text: Amazing! Learned from it:)
score: 0
type: AnswerComment

passlib
tag name: passlib
tags question: http://stackoverflow.com/q/52704841
type: Tag

http://stackoverflow.com/q/52657173
tagged with: python
has comment: http://stackoverflow.com/comment/92245495
tagged with: c++
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51557135
upvote count: 2
type: Question
has title: Sharing an MPI communicator using pybind11
has answer: http://stackoverflow.com/a/52672832
accepted answer: http://stackoverflow.com/a/52672832
tagged with: pybind11
downvote count: 0
answer count: 1
favorite count: 0
has body: Suppose that I have created a wrapper around an MPI communicator: class Communicator { public: Communicator() : comm(MPI_COMM_WORLD) {} Communicator(int const color, int const key) { MPI_Comm_split(MPI_COMM_WORLD, color, key, &amp;comm); } Communicator(MPI_Comm comm) : comm(comm) {} MPI_Comm GetComm() const { return comm; } private: MPI_Comm comm; }; I would like to use pybind11 to create a python wrapper around this object that looks something like this: void CommunicatorWrapper(pybind11::module &amp;m) { py::class_&lt;Communicator, std::shared_ptr&lt;Communicator&gt; &gt; commWrap(m, "Communicator"); commWrap.def(py::init( []() { return new Communicator(); } )); commWrap.def(py::init( [](int const color, int const key) { return new Communicator(color, key); } )); commWrap.def(py::init( [](MPI_Comm comm) { return new Communicator(comm); } )); commWrap.def("GetComm", &amp;Communicator::GetComm); } However, I'd like the MPI_Comm type that python sees to be mpi4py.MPI.Comm. Is this possible? If so, how? The above (naive) implementation results in the following behavior: comm = Communicator(MPI.COMM_WORLD) Error: TypeError: __init__(): incompatible constructor arguments. The following argument types are supported: 1. Communicator() 2. Communicator(arg0: int, arg1: int) 3. Communicator(arg0: int) and comm = Communicator() print(comm.GetComm()) prints -2080374784. This behavior makes sense given what MPI_Comm is but is obviously not the functionality I need.
tagged with: mpi

http://stackoverflow.com/q/52604788
type: Question
accepted answer: http://stackoverflow.com/a/52623656
has title: Python Error converting value "AddmissionGuid" to System.GUID
tagged with: guid
has comment: http://stackoverflow.com/comment/92143968
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python
has body: I am receiving data from a request as follows [ { "Info": { "SoftwareVersion": "111", "IpAddress": "111.111.11", "DeviceName": "1111222", "Type": "Tablet" }, "DeviceIdentity": "Identity", "AdmissionGuid": "db128362-f942-47fb-b18e-c073aa03b95d", "UserId": "8c7be5ac-9f2e-42aa-8f17-4e935a85eff3", "ConnectionId": "f78f544e-0780-4b07-87ec-d4edbe4cb522", "PairingId": null } ] Then I am trying to parse it in python everything works i get the value as expected but i get the following error, I have tried to convert it to Object, String, Hex but nothing works Error converting value "AdmissionGuid" to System.GUID Python script from requests import Session from signalr import Connection import threading, time, json, logging import urllib.request import requests import uuid GetPatientID = requests.get('http://example-url.com/api/json') data = GetAdmissionID.json() print (type(data)) AdmissionGuid= uuid.UUID(data[0]["AdmissionGuid"]) print (type(AdmissionGuid)) UserID = "8c7be5ac-9f2e-42aa-8f17-4e935a85eff3" softwareVersion = "111" IpAddress = "111.111.11" machineName = "1111222" DeviceType = "Tablet" pairingId = "null" def __init__(self, cli): self.cli = cli logging.info("registered the cli (main thread)") with Session() as session: connection = Connection("http://example-url.com/signalr", session) print(connection) logging.info("got the connection") presenceservice = connection.register_hub('ClientRegistration') logging.info("got the hub") connection.start() def get_data(notificaition): print("Recived something?: ", notificaition) def print_error(error): print('error: ', error) connection.error += print_error presenceservice.server.invoke('IdentifyClient', 'devideIdentity', 'softwareVersion', 'ipAddress', 'machineName', 'deviceType', 'patientAdmissionGuid', 'patientId', 'pairingId') key = input("Press E\n") if key == 'e': connection.wait(1) presenceservice.client.on('Notification', get_data) print ('Nothing Happned') connection.wait(30) And the log &lt;class 'list'&gt; &lt;clas…
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/534839
tagged with: uuid
has comment: http://stackoverflow.com/comment/92144122
has comment: http://stackoverflow.com/comment/92144276
linked to: http://stackoverflow.com/q/15859156
has answer: http://stackoverflow.com/a/52623656
has comment: http://stackoverflow.com/comment/92144335
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
tagged with: signalr

http://stackoverflow.com/a/52694918
has comment: http://stackoverflow.com/comment/92316658
has body: Or this as full code: import re with open('filename.txt','r') as f: for i in f: print(' '.join(re.findall('\d{2}',i)[:-2])) Output: 62 59 64 60 66 61 33 30 Example
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/92316677
type: Answer
answers question: http://stackoverflow.com/q/52694875
score: 2
has comment: http://stackoverflow.com/comment/92317182

http://stackoverflow.com/comment/92235020
score: 0
type: Comment
type: AnswerComment
has text: thanks, and the only requirement here is I specify what the `USERNAME_FIELD = 'email'` is, or are there any other defaults I need to add?
comment on: http://stackoverflow.com/a/52651562

http://stackoverflow.com/comment/92380546
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52726670
has text: Sorry, that may not have been precise enough. You will of course get differently colored scatter points, but their color will have nothing to do with the colormap you define. Because of that it is still unclear what exactly you want to achieve.

http://stackoverflow.com/comment/92356314
comment on: http://stackoverflow.com/a/52715020
type: AnswerComment
type: Comment
has text: What I mean is you have white space, you can isolate it, then in one operation, you shrink it, in the second you enlarge it. Then you subtract bigger to smaller and on that mask on an image you make a blur.
score: 0

http://stackoverflow.com/comment/92249346
comment on: http://stackoverflow.com/q/52659390
type: Comment
type: QuestionComment
has text: that table is inside a comment in your particular case, that's why you're not able to find it
score: 0

http://stackoverflow.com/q/52725229
has comment: http://stackoverflow.com/comment/92375972
has comment: http://stackoverflow.com/comment/92422421
tagged with: logistic-regression
has body: My issue is perfect separation with a logistic model testing two binary factors and their interaction on the dependent variable. When I do not include the interaction term, the model works, when I include the interaction term I get "PerfectSeparationError: Perfect separation detected, results not available" There is already a question answered on perfect separation for logistic regression, but this question specifically pertains to perfect separation error with an interaction term in the model. Here is my data Dataframe My code: endog_cols = df.columns[1:3] exog_cols = df.columns[4:8] logit2 = sm.GLM(df[endog_cols], df[exog_cols], family = sm.families.Binomial()).fit()
type: UnansweredQuestion
has title: Python Logistic Regression Perfect Separation Error
answer count: 0
has comment: http://stackoverflow.com/comment/92377000
has comment: http://stackoverflow.com/comment/92421224
has comment: http://stackoverflow.com/comment/92382271
has comment: http://stackoverflow.com/comment/92376012
type: Question
linked to: http://stackoverflow.com/q/34668868
tagged with: python
score: 0

http://stackoverflow.com/a/52685017
has comment: http://stackoverflow.com/comment/92301087
score: 1
has comment: http://stackoverflow.com/comment/92300898
upvote count: 1
has body: Your spider logic is very confusing: def parse(self, response): for quote in response.xpath('//div[@class="quote"]'): yield Request("http://quotes.toscrape.com/", callback=self.parse2, meta={'item':item}) For every quote you find on quotes.toscrape.com you schedule another request with to the same webpage? What happens is that these new scheduled requests get filtered out by scrapys duplicate request filter. Maybe you should just yield the item right there: def parse(self, response): for quote in response.xpath('//div[@class="quote"]'): item = MyItems() item['tinfo'] = quote.xpath('./span[@class="text"]/text()').extract_first() yield item To illustrate why your current crawler does nothing see this drawing:
answers question: http://stackoverflow.com/q/52684338
has comment: http://stackoverflow.com/comment/92301183
downvote count: 0
has comment: http://stackoverflow.com/comment/92304956
has comment: http://stackoverflow.com/comment/92301645
type: Answer
has comment: http://stackoverflow.com/comment/92302084
has comment: http://stackoverflow.com/comment/92304434

http://stackoverflow.com/comment/92398007
type: AnswerComment
comment on: http://stackoverflow.com/a/52736596
type: Comment
score: 2
has text: in a shorter form: `awk '!/>/' ORS="" text.txt`

http://stackoverflow.com/q/52681048
possible better answer: http://stackoverflow.com/a/52681216
has comment: http://stackoverflow.com/comment/92290959
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92292845
has comment: http://stackoverflow.com/comment/92290593
tagged with: python
has comment: http://stackoverflow.com/comment/92290663
has answer: http://stackoverflow.com/a/52681216
has answer: http://stackoverflow.com/a/52693851
accepted answer: http://stackoverflow.com/a/52693851
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/92297455
has body: I am working on a dataset with pandas in which a maintenance work is done at a location. The maintenance is done at random intervals, sometimes a year, and sometimes never. I want to find the years since the last maintenance action at each site if an action has been made on that site. There can be more than one action for a site and the occurrences of actions are random. For the years prior to the first action, it is not possible to know the years since action because that information is not in the dataset. I give only two sites in the following example but in the original dataset, I have thousands of them. My data only covers the years 2014 through 2017. Action = 0 means no action has been performed that year, Action = 1 means some action has been done. Measurement is a performance reading related to the effect of the action. The action can happen in any year. Site Year Action Measurement A 2014 1 100 A 2015 0 150 A 2016 0 300 A 2017 0 80 B 2014 0 200 B 2015 1 250 B 2016 1 60 B 2017 0 110 Given this dataset; I want to have a dataset like this: Item Year Action Measurement Years_Since_Last_Action A 2014 1 100 1 A 2015 0 150 2 A 2016 0 300 3 A 2017 0 80 4 B 2015 1 250 1 B 2016 1 60 1 B 2017 0 110 2 Please observe the Year 2015 is filtered out for Site B because that year is prior to the first action for that site. Many thanks in advance!
has title: Getting the years since an event
has comment: http://stackoverflow.com/comment/92290935
answer count: 2
has comment: http://stackoverflow.com/comment/92293999

http://stackoverflow.com/comment/92399076
comment on: http://stackoverflow.com/a/52737100
score: 0
type: Comment
type: AnswerComment
has text: @Paradowski sorry about that....happened because of muscle memory....have been dealing with a lot of useless contents in iterables.

google-colaboratory
tags question: http://stackoverflow.com/q/52659755
tags question: http://stackoverflow.com/q/52611672
tags question: http://stackoverflow.com/q/52734397
type: Tag
tags question: http://stackoverflow.com/q/52606202
tags question: http://stackoverflow.com/q/52710348
tags question: http://stackoverflow.com/q/52618058
tags question: http://stackoverflow.com/q/52620788
tags question: http://stackoverflow.com/q/52733786
tag name: google-colaboratory
tags question: http://stackoverflow.com/q/52656692

http://stackoverflow.com/comment/92483810
has text: I am overwriting them - Good idea - I'll test this today!
type: Comment
comment on: http://stackoverflow.com/q/52740474
score: 0
type: QuestionComment

http://stackoverflow.com/q/52630340
favorite count: 0
tagged with: jupyter-notebook
has title: Animate a 3D matrix with Matplotlib in Jupyter Notebook
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/52630620
type: Question
answer count: 1
downvote count: 0
tagged with: python
has body: I have a 3D matrix of shape (100,50,50), e.g. import numpy as np data = np.random.random(100,50,50) And I want to create an animation that shows each of the 2D slices of size (50,50) as a heatmap or imshow e.g.: import matplotlib.pyplot as plt plt.imshow(data[0,:,:]) plt.show() would display the 1st 'frame' of this animation. I'd like to also have this display in a Jupyter Notebook. I am currently following this tutorial for inline notebook animations being displayed as a html video, but I can't figure out how to replace the 1D line data with a slice of my 2D array. I know I need to create a plot element, an initialisation function and an animate function. Following that example, I've tried: fig, ax = plt.subplots() ax.set_xlim((0, 50)) ax.set_ylim((0, 50)) im, = ax.imshow([]) def init(): im.set_data([]) return (im,) # animation function. This is called sequentially def animate(i): data_slice = data[i,:,:] im.set_data(i) return (im,) # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True) HTML(anim.to_html5_video()) But I'm getting various errors whatever I try, mostly associated with the line im, = ax.imshow([]) Any help appreciated!
has answer: http://stackoverflow.com/a/52630620

http://stackoverflow.com/q/52728790
has body: It appears that the quote() and unquote() methods inside django.contrib.admin.utils do not effectively handle underscores in primary keys. Specifically, I have some string-type primary keys that look like cus_C2xVQnht and when I use the django admin interface to edit them via the small pencil icon, the popup window will display an error like Customer with ID "cusÂxVQnht" doesn't exist. Perhaps it was deleted? (it is converting the C2 to the codepoint 00C2, aka Â. This is true for other valid codepoints as well (00C7, 00C6, 001B, etc) If I manually go to the customers model and find the ID, I can pull it up and edit it just fine, but it seems the URL encoding doesn't work right when the primary key has an underscore in it. After quite a lot of digging I managed to find these two functions buried deep inside django.contrib.admin.utils: def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' and similarly problematic characters. Similar to urllib.parse.quote(), except that the quoting is slightly different so that it doesn't get automatically unquoted by the Web browser. """ if not isinstance(s, str): return s res = list(s) for i in range(len(res)): c = res[i] if c in """:/_#?;@&amp;=+$,"[]&lt;&gt;%\n\\""": res[i] = '_%02X' % ord(c) return ''.join(res) def unquote(s): """Undo the effects of quote(). Based heavily on urllib.parse.unquote().""" mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except ValueError: myappend('_' + item) else: myappend('_' + item) return "".join(res) They appear to be called somewhere in the admin template rendering process, but I couldn't figure out where/how often/all the locations, so I decided to do a quick monkey patch to decide if it was worth pursuing as a solution: I changed all the underscores in quote() and unquote() except for the one in the list o…
tagged with: django-admin
downvote count: 0
answer count: 1
has title: How can I safely override the django.contrib.admin.utils quote() method?
favorite count: 0
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/55988689
accepted answer: http://stackoverflow.com/a/55988689
type: Question

http://stackoverflow.com/a/52709547
answers question: http://stackoverflow.com/q/52709059
score: 0
type: Answer
has body: You could use apply(), but I would guess that the most computationally intensive part of your code are your HTTP requests (as mentioned by @Peter Leimbigler in his comment). Here is an example with your function: def func_ret_value(x): r = requests.get(url_pre + x['Symbol'] + url_suf) soup = BeautifulSoup(r.text, 'html.parser') tables = soup.findAll('table') for td in tables[40].findAll("td"): if td.text == "Short Percent of Float": return list(td.next_siblings)[1].text.strip("%") df['dload'] = df.apply(func_ret_value, axis=1) Note that axis=1 specifies that you will apply this function row-wise. You may also consider implementing some error-handling here in the case that your if statement inside your func_ret_value() function is never triggered for a given row.

http://stackoverflow.com/a/52653433
has body: First you need to write a transformation function which always returns tuples, using singleton tuples when necessary: def transform(name): if name.startswith("p"): return (name + "_prd", name) if name.startswith("h"): return (name + "_uat", name) return (name,) # Singleton tuple. Then you can do this: import itertools mod_hostnames = list(itertools.chain.from_iterable( transform(name) for name in hostnames)) print(mod_hostnames) itertools.chain.from_iterable is essentially a flatten operation which concatenates all the intermediate tuples, and the outer list turns the output from that generator into an actual list. However, in such cases, a more pedestrian approach with a traditional for loop makes more sense.
score: 1
answers question: http://stackoverflow.com/q/52653278
has comment: http://stackoverflow.com/comment/92240837
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/52701964
type: Question
upvote count: 1
favorite count: 0
tagged with: hidden-markov-models
has comment: http://stackoverflow.com/comment/92330467
has comment: http://stackoverflow.com/comment/92337078
has title: switching between list (transition matrix)
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92330513
tagged with: python
score: 1
tagged with: transition
has body: I have a problem to calculate the transition probabilities of people changing jobs. In the example below (which is a pivot table). Individiual 7 has different jobs in different years with different employers. I need to calculate the probability of this person changing job. pivot table is generated from raw data (bottom of this question) as follow: newdf.pivot_table(columns=['employers'], index=['indviduals','year'], fill_value=0, aggfunc=len) employers 1 7 12 13 15 22 23 27 28 45 99 indviduals year 7 2000 1 0 0 0 0 0 0 0 0 0 0 2001 0 0 0 0 1 0 0 0 0 0 0 2002 0 0 0 0 0 0 1 0 0 0 0 2004 0 0 0 0 0 1 0 0 0 0 0 2005 0 0 0 0 0 0 0 0 0 1 0 2006 0 0 0 0 0 0 0 0 1 0 0 2009 0 0 0 0 0 0 0 0 0 1 0 12 1999 0 0 2 0 0 0 0 0 0 0 0 2001 0 0 1 1 0 0 0 0 0 0 0 2006 0 0 0 0 0 0 0 0 0 0 1 2012 0 0 1 0 0 0 0 0 0 0 0 Here is what I have tried in python: transitions=newdf['employers'] n=1+max(transitions) M = [[0]*n for _ in range(n)] for (i, j) in zip(transitions, newdf['indviduals'][1:]): M[i][j] +=1 #this generates list out of index error. This is an obvious error because I am trying to match the list of unequal length. second attempt is counts=newdf.groupby('individual')['employer'].value_counts() (counts/counts.sum()) this is not going to give me the state of change from employer to employer. RAW DATA import pandas as pd newd = {'year': [2001, 2002, 2005, 2002, 2004, 1999, 2000, 1999, 2012, 2000, 2010, 2005, 2006, 2009, 2009, 2009, 2009, 2010, 2001, 2001, 2004, 2001, 2002, 2006, 2009,2001,2002,2003,2004,2005], 'indviduals': [12, 23, 24, 28,30, 12,7, 12, 12, 23, 24, 7, 12, 35, 39,37, 36, 333, 13, 15, 7, 7, 7, 7, 7, 12, 13, 15, 28,30], 'employers': [12, 23, 28, 22, 12, 12,1, 12, 12, 23, 27, 45, 99, 7, 7, 7, 7, 1, 15, 13, 22, 15, 23, 28, 45, 13, 13, 13, 13, 13] } newdf=pd.DataFrame(newd)

http://stackoverflow.com/comment/92220698
has text: what was the exception? there's really not enough information in your question to give any meaningful answer. Please provide [mcve]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52636719
score: 0

http://stackoverflow.com/q/52735322
answer count: 4
type: AnsweredQuestion
has title: Django issue with json : 'tuple' object has not attribute '_meta'
has comment: http://stackoverflow.com/comment/92398908
score: 1
possible better answer: http://stackoverflow.com/a/52735406
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/92398105
upvote count: 1
has answer: http://stackoverflow.com/a/52735409
type: Question
has answer: http://stackoverflow.com/a/52737483
has comment: http://stackoverflow.com/comment/92395725
has comment: http://stackoverflow.com/comment/92399069
has answer: http://stackoverflow.com/a/52735757
has comment: http://stackoverflow.com/comment/92399339
accepted answer: http://stackoverflow.com/a/52737483
has comment: http://stackoverflow.com/comment/92398158
has comment: http://stackoverflow.com/comment/92398739
downvote count: 0
has comment: http://stackoverflow.com/comment/92399410
favorite count: 0
has comment: http://stackoverflow.com/comment/92395422
has comment: http://stackoverflow.com/comment/92398846
has body: I'm trying to export data from queryset to different file formats and I'm getting an issue with json format. This is my little piece of code : from django.core import serializers def export_categories_json(request): with open("categories.json", "w") as out: data = serializers.serialize("json", Category.objects.all().values_list('id', 'name')) out.write(data) Then, I set in my template a button which call this function and should download the json file. But I have this issue : Traceback: File "/home/val/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/val/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/val/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/val/Bureau/Projets/Publication/publication/src/web/views/exports.py" in export_categories_json 276. data = serializers.serialize("json", Category.objects.all().values_list('id', 'name')) File "/home/val/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/core/serializers/__init__.py" in serialize 129. s.serialize(queryset, **options) File "/home/val/.pyenv/versions/Publication3.6.2/lib/python3.6/site-packages/django/core/serializers/base.py" in serialize 84. concrete_model = obj._meta.concrete_model Exception Type: AttributeError at /Category/json Exception Value: 'tuple' object has no attribute '_meta' Something is wrong in my code ? I can't send a queryset to json file ? EDIT : I wrote this and it works, but json is shown in my template. How I can export this one to a json file ? def export_categories_json(request): from django.http import JsonResponse data = list(Category.objects.values()) return JsonResponse(data, …
tagged with: django
has comment: http://stackoverflow.com/comment/92395699
tagged with: python
has answer: http://stackoverflow.com/a/52735406

http://stackoverflow.com/comment/92341614
comment on: http://stackoverflow.com/a/52706091
score: 0
type: AnswerComment
has text: The fact that the paths change for each similar state is the principle of a Markov Chain. The randomness is mandatory each time you generate a new path.
type: Comment

http://stackoverflow.com/comment/92398735
has text: Added the failed case
score: 0
comment on: http://stackoverflow.com/q/52732145
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52621123
has comment: http://stackoverflow.com/comment/92176357
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92176561
has comment: http://stackoverflow.com/comment/92176026
has comment: http://stackoverflow.com/comment/92175944
linked to: http://stackoverflow.com/q/13148429
has comment: http://stackoverflow.com/comment/92175969
type: Question
has comment: http://stackoverflow.com/comment/92175975
has body: For example, I have a pandas dataframe like this : T2 T4 T3 T1 Time 1 0.1 0.7 0.6 0.2 18:00 2 0.3 0.4 0.1 0.4 16:00 3 0.2 0.3 0.2 0.9 20:00 4 0.1 0.7 0.5 0.4 19:00 5 0.1 0.4 0.8 0.9 17:00 If I have a list : column_order = ["T1","T2","T3","T4","Time"] How do I reorder the pandas dataframe to this by given column_order: T1 T2 T3 T4 Time 1 0.2 0.1 0.6 0.7 18:00 2 0.4 0.3 0.1 0.4 16:00 3 0.9 0.2 0.2 0.3 20:00 4 0.4 0.1 0.5 0.7 19:00 5 0.9 0.1 0.8 0.4 17:00 I have done some research this and this but none of them mention how to reorder pandas dataframe column by given column name order. Thanks in advance.
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/92176055
has title: How to order pandas datafame column by given a list of column
linked to: http://stackoverflow.com/q/11067027
duplicate of: http://stackoverflow.com/q/13148429

http://stackoverflow.com/a/54119819
score: 10
answers question: http://stackoverflow.com/q/52728609
downvote count: 0
type: Answer
has body: Had the same issue but then realized that I was inadvertently trying to execute the file in the build folder instead of the dist folder. Looks like you might be making the same mistake from your traceback so see if using the executable in dist doesn't fix it for you
upvote count: 10

http://stackoverflow.com/comment/92528588
score: 0
type: QuestionComment
has text: I guess the last error is because if you flatten your data, the length of the time data and the total data does not match - one has number of values as the length of time dimension and other as the product of time, lon and lat dimensions. Anyhow, I am not sure what is your aim with the data. For me it does not make sense to convert (time,lat,lon) data to one Pandas table and I would rather work with the NumPy array with (time,lat,lon) dimensions. If you are to use just one timeserie, then it makes sense to use Pandas table for it.
comment on: http://stackoverflow.com/q/52680199
type: Comment

http://stackoverflow.com/q/52646692
has body: I have a postgres table where I have a column date of type timestamp with time zone Now when I insert a record into the table, it always fails for this column and gives an error like column "date" is of type timestamp with time zone but expression is of type numeric I am using python to do a sql query and for the column date, I pass the value datetime.now(tz) which I basically obtain by import pytz from datetime import datetime tz = pytz.timezone("Asia/Kolkata") date = datetime.now(tz) In the table there are already existing values for the column date which has values like 2018-07-23 10:30:00+05:30 and my generated value is 2018-10-04 17:53:18.431857+05:30 which I believe is in the same format.Then why am I receiving this error?
tagged with: postgresql
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/92225749
has comment: http://stackoverflow.com/comment/92230878
tagged with: pytz
answer count: 0
has comment: http://stackoverflow.com/comment/92225717
has title: Postgres throws error while inserting datetime with timezone
type: Question
score: 0

http://stackoverflow.com/q/52691386
tagged with: python
tagged with: ping
tagged with: subprocess
type: Question
has title: Knowing if my server is up or down using ping. .
answer count: 1
tagged with: python-3.6
score: 0
has body: Thanks to all for your time. I'm trying to know if several server are up or down using ping, and it works . . . but when I try convert the result into a up or down, something is wrong and always is down. Dunno what other thing I should try, don't need anything else, just up or down and the IP. import os import datetime import platform import subprocess import string date = datetime.datetime.now() day = date.day hour = date.hour def writedoc (): os.chdir ('Path') wresult = open ("pingresults_{}_{}.txt".format(day,hour), 'a') wresult.write ('{}-{}\n'.format(ips, rping)) wresult.close () os.chdir ('Path') openips = open ("ips.txt","r") ipfile = openips.readlines() for ips in ipfile: ips = ips.strip() print (ips) args = ["ping", "-n", "4", "-l", "1", "-w", "1000", ips] pping = subprocess.Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE) rping = pping.stdout for line in rping: print (line) if (rping.find("(100% perdidos)" != -1)): result = "down" print (result) else: result = "up" print (result) writedoc()
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52691481

http://stackoverflow.com/comment/92355242
has text: This was exactly what I was looking for, and the explanation is really helpful, thanks!
comment on: http://stackoverflow.com/a/52672324
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52633247
tagged with: list-comprehension
type: Question
has title: Python: modifying list with nested loops in list comprehension
tagged with: nested-loops
has answer: http://stackoverflow.com/a/52633550
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: I have part of a code that does something analogous to the following: import numpy as np N = 10 test = [1] * N np.random.seed(123) norm = np.random.rand(N) my_dic = {(k, kk):np.random.rand(1) for k,_ in enumerate(test) for kk in range(5)} for i, _ in enumerate(test): test[i] *= norm[i] for j in range(5): test[i] *= my_dic[(i, j)] Since both loop are modifying a list, is there a way for me to translate that to list comprehension? I have been trying variations of the following, with no success: import numpy as np N = 10 test = [1] * N np.random.seed(123) norm = np.random.rand(N) my_dic = {(k, kk):np.random.rand(1) for k,_ in enumerate(test) for kk in range(5)} test = [val for val in norm] test = [test[i] * my_dic[(i, j)] for i, _ in enumerate(test) for j in range(5)]
has comment: http://stackoverflow.com/comment/92199964
score: 0

http://stackoverflow.com/q/52598012
upvote count: 2
has comment: http://stackoverflow.com/comment/92130841
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92130748
possible better answer: http://stackoverflow.com/a/52598194
score: 1
has answer: http://stackoverflow.com/a/52598194
accepted answer: http://stackoverflow.com/a/52598577
type: Question
tagged with: numpy
answer count: 2
tagged with: arrays
has comment: http://stackoverflow.com/comment/92130875
has title: Slicing, indexing and iterating over 2D numpy arrays
has body: I am enrolled in a beginners class Python at my university. We've got a programming assignment which I'm stuck on. We got an assignment to find a route between two point in a map, the map is an 2D numpy array. One of the first tasks is to convert the array consisting of free road(1) and buildings(0) to an array where all the locations surrounding a building (left, right, below, above) are converted to parking spots (-1) I started with writing a function to generate a 2D numpy array in the right size: def get_map(): map = np.random.randint(2, size=(12, 10)) return map Now I want to write another function that takes the map as an argument, and returns the map where the parking spots are converted from 1's to -1's. def adjusted_map(map): map_adjusted = return map_adjusted I am mostly stuck on the elements above and below the 0's. Left and right I can do because that's no different from 1D arrays or normal lists, strings etc. Im sorry if this is a stupid question but I looked into the numpy documentation about indexing, slicing and iterating over numpy arrays, but I could not find a solution for my problem.
favorite count: 0
has answer: http://stackoverflow.com/a/52598577

http://stackoverflow.com/q/52636864
tagged with: sqlite
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92209188
type: Question
has comment: http://stackoverflow.com/comment/92234440
has title: Data comparison tool broken by date input request:
score: 0
has body: I am working on a Python program using sqlite3 that compares the hours billed to the hours on site for different employees, the code follows: from dbConnect import db_connect con = db_connect() cur = con.cursor() def hours_discrepancy(): emp_ids_dict = [4759, 4477, 4475, 1230, 4479] continue_marker = "yes" chosen_date = input("Date: ") for i in emp_ids_dict: choose_emp = i # chosen_date = input("Date: ") emp_check = cur.execute(f"SELECT LastName, FirstName " f"FROM BrandHours " f"WHERE EmpID LIKE {choose_emp} AND Date LIKE {chosen_date}") emp_fetch = emp_check.fetchone() employee_name = str(emp_fetch[0] + ", " + emp_fetch[1]) print(employee_name) reported = cur.execute(f"SELECT Reported, Punched " f"FROM BrandHours " f"WHERE EmpID LIKE {choose_emp} AND Date LIKE {chosen_date}") hours_fetch = reported.fetchone() reported_hours = hours_fetch[0] punched_hours = hours_fetch[1] print(reported_hours) print(punched_hours) discrepancy = reported_hours - punched_hours print(f"Discrepancy: {discrepancy}") print("=============================================================================") hours_discrepancy() I was having an issue in which only one employee would come up until, as you can see, I commented out the chosen_date input variable and moved in outside of the for loop. Definitely it is better to have it outside of the loop, I see that now. Still, the behavior with the date input inside of the loop was not what I expected. My question is, why did the program merely return one employee, rather than asking for input "Date: " at each iteration? EDIT: dbConnect is another script I have that this one calls to: import os import sqlite3 default_path = os.path.join(os.path.dirname(__file__), 'db.sqlite3') def db_connect(db_path=default_path): con = sqlite3.connect(db_path) return con
tagged with: sql

http://stackoverflow.com/q/52727837
upvote count: 3
has comment: http://stackoverflow.com/comment/92380909
has comment: http://stackoverflow.com/comment/92380955
type: Question
has comment: http://stackoverflow.com/comment/92380929
has answer: http://stackoverflow.com/a/52728064
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/62257704
favorite count: 0
has title: Default value format on Django DateField
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm trying to specify a default date in a Django model, for example: from datetime import date class A(models.Model): date = models.DateField(default=date.today()) This works and I can see the default date in a ModelForm, but when I change the form input_format to %d-%m-%Y, the default date never appears in the field. I've also tried: from datetime import date class A(models.Model): date = models.DateField(default=date.today().strftime('%d-%m-%Y')) This doesn't work either. Can anyone help me?
has comment: http://stackoverflow.com/comment/92380988
score: 3
has answer: http://stackoverflow.com/a/52728035

http://stackoverflow.com/a/52738630
accepted answer of: http://stackoverflow.com/q/52736897
answers question: http://stackoverflow.com/q/52736897
upvote count: 7
downvote count: 1
has body: I used Github's code search to find user-agent in the YTDL codebase, ended up finding this piece of code that sets the user agent based on the command line. So, all in all, just import youtube_dl.utils youtube_dl.utils.std_headers['User-Agent'] = 'my-user-agent' to override it.
type: AcceptedAnswer
score: 6
type: Answer

http://stackoverflow.com/comment/92167740
score: 0
type: AnswerComment
has text: Thank you- this worked. I will be reading more about using the "numpy" way of doing things, which sounds like it will end up creating faster code for me.
type: Comment
comment on: http://stackoverflow.com/a/52616012

http://stackoverflow.com/comment/92384707
has text: Thank you! That's both brilliant and obvious. I should have thought harder about that.
comment on: http://stackoverflow.com/a/52729710
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/92197361
comment on: http://stackoverflow.com/a/52631716
type: AnswerComment
score: 0
type: Comment
has text: I don't believe there is, because `process.extract()` is designed to handle a single query string and apply the passed scoring algorithm to that query and the supplied match options. I will add some details to my answer in another edit.

http://stackoverflow.com/q/52662063
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52662181
tagged with: numbers
has comment: http://stackoverflow.com/comment/92254465
has answer: http://stackoverflow.com/a/52662181
has title: Python number with comma as 1000 separator
type: Question
tagged with: format
has answer: http://stackoverflow.com/a/52662115
upvote count: 5
has body: Easy task: number = 100123.44 number_formated = "100,123" Don't tell me there is no better way than: number_formated = "{:,}".format(int(format("{:.0f}".format(number)))) ?
linked to: http://stackoverflow.com/q/1823058
answer count: 3
downvote count: 0
duplicate of: http://stackoverflow.com/q/1823058
has answer: http://stackoverflow.com/a/52662217
favorite count: 0
score: 5
accepted answer: http://stackoverflow.com/a/52662217

http://stackoverflow.com/comment/92335287
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52702954
has text: You can try scraping the page using [Selenium instead](https://medium.freecodecamp.org/better-web-scraping-in-python-with-selenium-beautiful-soup-and-pandas-d6390592e251).

http://stackoverflow.com/q/52703252
has body: I would like to download the emails and their attachments from my Outlook account via Python. Therefore, I have used the official python script with some changes since I didn't want to employ Django. Here below you can see my two unsuccessful attempts, the two corresponding errors and some comments. If I am not mistaken the issue arises when I try to obtain the Authorization code for getting the access token. During this step I can't make my app sign in successfully and automatically. Although I only present in this post the issue with the Authorization code, I would like to make you aware that a second issue comes from the incorrect access token I obtain using my client_id, client_secret and my manually obtained Authorization code. Note that I am using the so called "Azure AD v2 authentication endpoint" (as suggested in both https://learn.microsoft.com/en-us/previous-versions/office/office-365-api/api/version-2.0/use-outlook-rest-api and https://learn.microsoft.com/en-us/outlook/rest/python-tutorial) in order to register and authenticate my app. It is worth stressing that I have also tried to employ the Azure AD and OAuth (i.e. the second approach to handle app registration and user authorization 'https://manage.windowsazure.com/') without any success. What is the correct approach in my case? Where is my mistake? Given my problems I believe I am registering my app wrongly. Thanking you in advance, I wish you all a nice day. Modified script: # Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE.txt in the project root for license information. #from urllib.parse import quote, urlencode from urlparse import urlparse from urllib2 import urlopen from urllib import urlencode import requests import base64 import json import time import httplib # Client ID and secret client_id = 'xxxxxxxxxx' client_secret = 'xxxxxxxxxx' # Constant strings for OAuth2 flow # The OAuth authority authority = 'https://login.microsoftonline.com' # The author…
tagged with: oauth-2.0
type: Question
tagged with: office365api
tagged with: outlook-restapi
score: 0
tagged with: azure
answer count: 1
has answer: http://stackoverflow.com/a/52713397
has title: OAuth2 Authorization Code - Outlook rest API
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52737885
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92488146
type: Question
has body: I would like to create an xarray dataset from several input files. each file is for 1 timestamp, 1 level and 1 source. An example with 2 timestamps, 2 levels and 3 sources: d1 = np.arange(0,9).reshape((3,3)) # 01:00, 3m, SG1 -&gt; 00001-101.con d2 = np.arange(10,19).reshape((3,3)) # 01:00, 3m, SG2 -&gt; 00001-102.con d3 = np.arange(20,29).reshape((3,3)) # 01:00, 3m, SG3 -&gt; 00001-103.con d4 = np.arange(60,69).reshape((3,3)) # 01:00, 10m, SG1 -&gt; 00001-201.con d5 = np.arange(70,79).reshape((3,3)) # 01:00, 10m, SG2 -&gt; 00001-202.con d6 = np.arange(80,89).reshape((3,3)) # 01:00, 10m, SG3 -&gt; 00001-203.con e1 = np.arange(100,109).reshape((3,3)) # 02:00, 3m, SG1 -&gt; 00002-101.con e2 = np.arange(110,119).reshape((3,3)) # 02:00, 3m, SG2 -&gt; 00002-102.con e3 = np.arange(120,129).reshape((3,3)) # 02:00, 3m, SG3 -&gt; 00002-103.con e4 = np.arange(160,169).reshape((3,3)) # 02:00 10m, SG1 -&gt; 00002-201.con e5 = np.arange(170,179).reshape((3,3)) # 02:00 10m, SG2 -&gt; 00002-202.con e6 = np.arange(180,189).reshape((3,3)) # 02:00 10m, SG3 -&gt; 00002-203.con dstk = np.stack((d1,d2,d3,d4,d5,d6)) # 01:00, both levels all sgs -&gt; 00001-101.con - 00001-203.con estk = np.stack((e1,e2,e3,e4,e5,e6)) # 02:00, both levels all sgs -&gt; 00002-101.con - 00002-203.con i managed to manually create the dataset in the way i need it like this: xx = [100,200,300] yy = [600,700,800] dds1 = xr.Dataset(data_vars={"SG1":(("x","y"),dstk[0]),"SG2":(("x","y"),dstk[1]),"SG3":(("x","y"),dstk[2])},coords={"x":xx,"y":yy,"lvl":"3m","t":pd.Timestamp("2010-01-01 01:00:00")}) dds2 = xr.Dataset(data_vars={"SG1":(("x","y"),dstk[3]),"SG2":(("x","y"),dstk[4]),"SG3":(("x","y"),dstk[5])},coords={"x":xx,"y":yy,"lvl":"10m","t":pd.Timestamp("2010-01-01 01:00:00")}) eds1 = xr.Dataset(data_vars={"SG1":(("x","y"),estk[3]),"SG2":(("x","y"),estk[4]),"SG3":(("x","y"),estk[5])},coords={"x":xx,"y":yy,"lvl":"3m","t":pd.Timestamp("2010-01-01 02:00:00")}) eds2 = xr.Dataset(data_vars={"SG1":(("x","y"),estk[3]),"SG2":…
downvote count: 0
favorite count: 0
tagged with: python-xarray
has title: Create xarray dataset dynamically from multiple files
tagged with: python
score: 2
answer count: 0
upvote count: 2

http://stackoverflow.com/q/52611806
tagged with: python
linked to: http://stackoverflow.com/q/14507794
has comment: http://stackoverflow.com/comment/92157957
has body: I have a dataframe with two headers like this: I want to transform it to have one header. Desired output: I have followed some solutions on stack-overflow about multi-indexing and multi-headers, but I am not able to achieve the result I want. Can anybody help me solve this? Thanks in advance.
type: Question
has comment: http://stackoverflow.com/comment/92158204
has title: Transforming columns with multiple indexes/headers
duplicate of: http://stackoverflow.com/q/14507794
score: 0
tagged with: pandas
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52689226
has comment: http://stackoverflow.com/comment/92306175
tagged with: tokenize
has answer: http://stackoverflow.com/a/52690870
score: 1
accepted answer: http://stackoverflow.com/a/52690870
has comment: http://stackoverflow.com/comment/92306330
upvote count: 1
has body: There is any way to tokenize strings with ngram range? Like when u get the features from a CountVectorizer. For example, (w ngram range = (1,2)): strings = ['this is the first sentence','this is the second sentence'] to [['this','this is','is','is the','the','the first',''first','first sentence','sentence'],['this','this is','is','is the','the','the second',''second','second sentence','sentence']] Update: iterating over n i get: sentence = 'this is the first sentence' nrange_array = [] for n in range(1,3): nrange = ngrams(sentence.split(),n) nrange_array.append(nrange) for nrange in nrange_array: for grams in nrange: print(grams) output: ('this',) ('is',) ('the',) ('first',) ('sentence',) ('this', 'is') ('is', 'the') ('the', 'first') ('first', 'sentence') and i want: ('this','this is','is','is the','the','the first','first','first sentence','sentence')
type: Question
tagged with: split
tagged with: nltk
has comment: http://stackoverflow.com/comment/92306281
has comment: http://stackoverflow.com/comment/92307226
has comment: http://stackoverflow.com/comment/92308207
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/92305857
linked to: http://stackoverflow.com/q/17531684
tagged with: python
has title: Tokenize with ngram range
type: AnsweredQuestion

http://stackoverflow.com/a/52605746
has comment: http://stackoverflow.com/comment/92149466
has body: Try os.path.expanduser("~/Desktop")
downvote count: 0
has comment: http://stackoverflow.com/comment/92147018
has comment: http://stackoverflow.com/comment/92147112
type: Answer
answers question: http://stackoverflow.com/q/52605706
has comment: http://stackoverflow.com/comment/92161848
score: 1
has comment: http://stackoverflow.com/comment/92218898
upvote count: 1
has comment: http://stackoverflow.com/comment/92147354
has comment: http://stackoverflow.com/comment/92216284

http://stackoverflow.com/comment/92406247
type: AnswerComment
has text: But the same error also happens when I connect from a linux desktop computer, it happens in both. Does that mean I need to enable that x11 fowarding in both?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52739728

http://stackoverflow.com/a/52733262
accepted answer of: http://stackoverflow.com/q/52733173
score: -1
upvote count: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52733173
has body: Try changing the line Player1 = p1dice+p1dice2 to Player1 += p1dice+p1dice2 The old version replaces the value of Player1 each time. The new version adds to it. By the way, the += is a shorthand for Player1 = Player1+p1dice+p1dice2 Many of Python's other operators have a similar "augmented assignment" notation.
downvote count: 1

http://stackoverflow.com/comment/92323110
type: QuestionComment
score: 0
has text: Firstly, thank you for answering and I'm sorry, this is my first time using stackoverflow. Possible duplicate does not answer my question because there wasn't solved adding text on points in plot, and points are fixed, possible duplicate solution just adds new points. But here, I'm trying to move points, and add text for every point.
comment on: http://stackoverflow.com/q/52687197
type: Comment

http://stackoverflow.com/a/52614549
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52614470
has body: Python strings have built in checks for letters and digits: s = "test1" for char in s: is_digit = char.isdigit() is_letter = char.isalpha() or is_digit print char, is_letter, is_digit If you are attempting to determine if a character is a letter or digit you should use this.

http://stackoverflow.com/a/78304959
has body: The initial proposition is the best one for me, so the simplest and most elegant way of improving it is: import logging if not condition_met: missing = set_one - set_two error = ValueError('Missing keys: {}'.format(missing)) logging.error(error) raise error
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52672268
score: 1

http://stackoverflow.com/comment/92366624
type: Comment
type: QuestionComment
has text: My guess is that the SetImage function from tesserocr expects a PIL image as an input, but you give it a numpy array. Have a look at the docs to check the input and output of functions you use, and refactor your code accordingly.
comment on: http://stackoverflow.com/q/52717068
score: 0

http://stackoverflow.com/a/52636226
has comment: http://stackoverflow.com/comment/92205852
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/92205868
downvote count: 0
has body: IIUC, you can use apply() with a custom function: import pandas as pd df = pd.DataFrame([['Sweet Mango', 1],['Green Apple', 2],['Few blue Banana', 0],['Black Banana', 5]], columns=['Fruit','Price']) fruits = {'BN':'Banana', 'LM': 'Lemon', 'AP':'Apple', 'MG': 'Mango'} def find_category(x): return [k for k in fruits.values() if k in x][0] df['Fruit'] = df['Fruit'].apply(find_category) Yields: Fruit Price 0 Mango 1 1 Apple 2 2 Banana 0 3 Banana 5
has comment: http://stackoverflow.com/comment/92205882
has comment: http://stackoverflow.com/comment/92206387
answers question: http://stackoverflow.com/q/52636092
has comment: http://stackoverflow.com/comment/92205999
has comment: http://stackoverflow.com/comment/92205842

http://stackoverflow.com/a/52743794
answers question: http://stackoverflow.com/q/52743065
score: 1
upvote count: 1
has body: If you set the x-axis limits separately, they won't be overwritten until you change them, regardless of what is plotted. to make it mesh with your code, try: plt.xlim(xlim) when you get xlim, it gets the current limits, but once you 'set' them, they're locked until you change them again. This works for the y-axis as well, if you want those to be fixed too (just swap 'x' for 'y' and add the code).
downvote count: 0
type: Answer

http://stackoverflow.com/comment/92708342
comment on: http://stackoverflow.com/a/52897940
has text: I left out the specific reason for the error: The print statement changed from Python 2 (print 'hello') to Python 3 (print('hello')). For Python 3 it should read print(get_version())
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92398906
comment on: http://stackoverflow.com/q/52736989
has text: https://docs.python.org/3/tutorial/introduction.html#strings
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92254221
comment on: http://stackoverflow.com/q/52641266
type: QuestionComment
type: Comment
has text: I see you finally figured out your actual problem. Perhaps this question should now be marked as a duplicate of https://stackoverflow.com/questions/52661863/how-to-delete-non-ascii-characters-in-a-text-file/52661986#52661986 or simply deleted.
score: 0

http://stackoverflow.com/comment/92958084
comment on: http://stackoverflow.com/q/52671308
has text: Did either of the posted solutions work for you? Consider accepting the one that worked best for you?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92362557
has text: It's still not accurate, `range(n)` returns an iterator (a list in Python 2 and a `range` object in Python 3) with the numbers `0` to `n - 1`.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/52718370
type: Comment

http://stackoverflow.com/q/52645125
has answer: http://stackoverflow.com/a/52646053
has comment: http://stackoverflow.com/comment/92223782
has body: I have the following Pipfile: source url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] mypy = "==0.521" [requires] python_version = "3.6" And the Dockerfile: FROM heroku/heroku:18 #Install system dependencies RUN apt-get update &amp;&amp; apt-get install -y software-properties-common build-essential curl nano #Install python 3.6 RUN apt-get update RUN apt-get install -y python3.6 libpython3.6 python3.6-dev python-dev python-pip \ python3-pip libssl-dev libffi-dev libxml2-dev libxslt1-dev zlib1g-dev #Install backend packages RUN pip3 install pipenv python-magic libmagic django ENV LC_ALL=C.UTF-8 ENV LANG=C.UTF-8 Image build and start container docker build -t test -f Dockerfile . docker run -it test /bin/bash Copy Pipfile to container docker cp Pipfile &lt;container&gt;:/test/Pipfile Generate lock file pipenv lock Trying to install packages pipenv install --dev --system --python=`which python3` Error An error occurred while installing mypy==0.521! Will try again. An error occurred while installing typed-ast==1.0.4! Will try again. ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 2/2 — 00:00:01 Installing initially failed dependencies... Collecting mypy==0.521 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/2 — 00:00:00 Using cached https://files.pythonhosted.org/packages/18/11/733e33decfdbd76cce7158c92618b9317d4132b41affd04db00216d17f76/mypy-0.521.tar.gz Complete output from command python setup.py egg_info: ERROR: You need Python 3.2 or later to use mypy. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-cebwoI/mypy/ ☤ ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/2 —
upvote count: 4
downvote count: 0
answer count: 1
score: 4
favorite count: 0
tagged with: docker
accepted answer: http://stackoverflow.com/a/52646053
has title: Pipenv in docker fails to install packages
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92224564
type: Question
tagged with: pipenv

http://stackoverflow.com/comment/92167395
score: 0
has text: How do I handle this if the columns names are different? This means not A to O
type: AnswerComment
comment on: http://stackoverflow.com/a/52615770
type: Comment

http://stackoverflow.com/q/52632997
has comment: http://stackoverflow.com/comment/92200277
has answer: http://stackoverflow.com/a/52633564
favorite count: 0
has body: I'm making a small little test software using Tkinter. I'm trying to color a button red, and when you click on it, it turns green. There seem to be similar questions asked, but none of them made any difference. root = tkinter.Tk() root.title('Test Software') root.resizable(width = False, height = False) root.geometry("300x300") HandleBarButton = ttk.Button(text = "Handle Bars", bg = "red", command = handleBarCommand) HandleBarButton.grid(row = 0, column = 0) parkingStallButton = ttk.Button(text = "Parking Stalls", bg = "red", command = parkingStallsCommand) parkingStallButton.grid(row = 0, column = 1) toiletButton = ttk.Button(text = "Toilets", bg = "red", command = toiletsCommand) toiletButton.grid(row = 0, column = 2) doorsButton = ttk.Button(text = "Doors", bg = "red", command = doorsCommand) doorsButton.grid(row = 0, column = 3) I have commands defined above, but It's not essential to my question. When I run this, it gives the error : _tkinter.TclError: unknown option "-bg" Any help on this? Thanks.
tagged with: tkinter
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Colors of Buttons in Tkinter
score: 1
accepted answer: http://stackoverflow.com/a/52633564
type: Question
answer count: 1
downvote count: 0

modal-dialog
tag name: modal-dialog
type: Tag
tags question: http://stackoverflow.com/q/52654882

http://stackoverflow.com/a/52836304
has body: Provided that each name is labeled by exactly one label (e.g. all A are 1) you can use the following: Group the names by label and check which label has an excess (in terms of unique names). Randomly remove names from the over-represented label class in order to account for the excess. Select the part of the data frame which does not contain the removed names. Here is the code: labels = df.groupby('label').name.unique() # Sort the over-represented class to the head. labels = labels[labels.apply(len).sort_values(ascending=False).index] excess = len(labels.iloc[0]) - len(labels.iloc[1]) remove = np.random.choice(labels.iloc[0], excess, replace=False) df2 = df[~df.name.isin(remove)]
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52735334
type: Answer
answers question: http://stackoverflow.com/q/52735334

http://stackoverflow.com/comment/92193158
type: QuestionComment
has text: Doing multiprocessing from a multithreaded application is tricky. It's best not to mix the two, or at least not to fork a multithreaded process.
comment on: http://stackoverflow.com/q/52629457
score: 0
type: Comment

http://stackoverflow.com/comment/92177752
has text: ahh i see. yield is used to return a single object or request. but in your case you are yielding a list.. try using `yield from [ ]` or `yield FormRequest()` instead.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52609340

http://stackoverflow.com/a/52728394
upvote count: 9
answers question: http://stackoverflow.com/q/52727681
type: AcceptedAnswer
has body: To add a non-null column to an existing table, Django needs to use an ALTER TABLE ADD COLUMN ... DEFAULT &lt;default_value&gt;. This only allows Django to call the default function once, that's why you see every row having the same value. Your workaround is pretty much spot on, except that you can populate the existing rows with unique values using a data migration, so that it doesn't require any manual steps. The entire procedure for this use-case is described in the docs: https://docs.djangoproject.com/en/2.1/howto/writing-migrations/#migrations-that-add-unique-fields
accepted answer of: http://stackoverflow.com/q/52727681
has comment: http://stackoverflow.com/comment/92382650
downvote count: 0
has comment: http://stackoverflow.com/comment/92382116
type: Answer
score: 9

http://stackoverflow.com/a/52689290
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/52689010
has body: You will have to chain a groupby here. Consider this example: import pandas as pd import numpy as np np.random.seed(111) names = [ 'Robert Baratheon', 'Jon Snow', 'Daenerys Targaryen', 'Theon Greyjoy', 'Tyrion Lannister' ] df = pd.DataFrame({ 'season': np.random.randint(1, 7, size=100), 'actor': np.random.choice(names, size=100), 'appearance': 1 }) s = df.groupby(['season','actor'])['appearance'].count() print(s.sort_values(ascending=False).groupby('season').head(1)) # &lt;-- head(3) for 3 values Returns: season actor 4 Daenerys Targaryen 7 6 Robert Baratheon 6 3 Robert Baratheon 6 5 Jon Snow 5 2 Theon Greyjoy 5 1 Jon Snow 4 Where s is (clipped at 4) season actor 1 Daenerys Targaryen 2 Jon Snow 4 Robert Baratheon 2 Theon Greyjoy 3 Tyrion Lannister 4 2 Daenerys Targaryen 4 Jon Snow 3 Robert Baratheon 1 Theon Greyjoy 5 Tyrion Lannister 3 3 Daenerys Targaryen 2 Jon Snow 1 Robert Baratheon 6 Theon Greyjoy 3 Tyrion Lannister 3 4 ...
has comment: http://stackoverflow.com/comment/92305580
type: Answer
has comment: http://stackoverflow.com/comment/92308530
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52689010
type: AcceptedAnswer

http://stackoverflow.com/comment/92384119
comment on: http://stackoverflow.com/q/52729163
has text: yes in the place i installed nccl it is there but the error is asking for NCCL-SLA.txt not LISCENSE .txt right?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52592549
has title: Label encoding using sklearn python start from 1
linked to: http://stackoverflow.com/q/58270129
has comment: http://stackoverflow.com/comment/92123538
duplicate of: http://stackoverflow.com/q/58270129
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/92122459
has comment: http://stackoverflow.com/comment/92123673
upvote count: 2
has comment: http://stackoverflow.com/comment/92122503
tagged with: encode
type: UnansweredQuestion
has body: I wanna ask about how to convert categorical features to numerical using sklearn python beginning from 1 not 0. Thank you
has comment: http://stackoverflow.com/comment/92123696
tagged with: python
has comment: http://stackoverflow.com/comment/92123651
answer count: 0
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/92123503
has comment: http://stackoverflow.com/comment/92119784

http://stackoverflow.com/q/52663054
accepted answer: http://stackoverflow.com/a/52663272
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92256193
tagged with: python-3.x
type: Question
has body: I want to monitor a page to get changes. So I use proxies. Not all this proxies work (some maybe are banned some are to slow etc.) so I want to refresh page, and I want to change the proxy every refresh and if the page do not load until 2 seconds make a refresh. options = webdriver.ChromeOptions() options.add_argument('--proxy-server=http://%s' % PROXY['http']) while True: try: browser = webdriver.Chrome(executable_path=path, options=options) browser.implicitly_wait(1) browser.get(links) break except: browser.close() PROXY = proxy_reader.proxies_call(3) #this function return a new proxy each time source = browser.page_source I don't know how to make every session during 2 seconds... I hope someone can help me.
tagged with: python
answer count: 1
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
has title: Selenium Python refreshing a page with proxies until is fully loaded
score: 0
has answer: http://stackoverflow.com/a/52663272
tagged with: selenium

http://stackoverflow.com/comment/92338878
comment on: http://stackoverflow.com/q/52706139
score: 0
type: QuestionComment
type: Comment
has text: yea I don't know how to use that.

http://stackoverflow.com/comment/92269113
type: AnswerComment
score: 0
has text: Let me check and come back it
type: Comment
comment on: http://stackoverflow.com/a/52669578

http://stackoverflow.com/a/52659033
has comment: http://stackoverflow.com/comment/92249287
has body: You just need to make the final period optional. Also lookbehind for a space or the start of the string before the first letter to ensure it's not part of another word, and lookahead after the end for a space or the end of the string: pattern = r'(?i)(?:^|(?&lt;= ))(?:[a-z]\.)+[a-z]\.?(?= |$)'
upvote count: 3
has comment: http://stackoverflow.com/comment/92278485
has comment: http://stackoverflow.com/comment/92248881
answers question: http://stackoverflow.com/q/52659009
has comment: http://stackoverflow.com/comment/92248933
score: 3
has comment: http://stackoverflow.com/comment/92248780
has comment: http://stackoverflow.com/comment/92248749
has comment: http://stackoverflow.com/comment/92249477
has comment: http://stackoverflow.com/comment/92248809
downvote count: 0
has comment: http://stackoverflow.com/comment/92249484
has comment: http://stackoverflow.com/comment/92249204
type: Answer
has comment: http://stackoverflow.com/comment/92264122

http://stackoverflow.com/comment/92161413
score: 0
has text: "['Elijah', 'Noah', 'Liam']" is not equal to "['Noah', 'Liam']"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52613320

http://stackoverflow.com/comment/92360299
comment on: http://stackoverflow.com/q/52716762
has text: I want to separate the text into paragraphs so that each paragraph begins with a number followed by a dot. However trying to match a number and a dot gives problems since there is other mathces to that inside of the actual text that are not paragraphs.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/61047641
score: 5
type: Answer
downvote count: 2
upvote count: 7
has body: If the path is correct and the name of the image is OK, but you are still getting the error use: from skimage import io img = io.imread(file_path) instead of: cv2.imread(file_path) The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).
answers question: http://stackoverflow.com/q/52676020

uwsgi
tags question: http://stackoverflow.com/q/52619958
tags question: http://stackoverflow.com/q/52613238
tag name: uwsgi
type: Tag
tags question: http://stackoverflow.com/q/52735085
tags question: http://stackoverflow.com/q/52705715

http://stackoverflow.com/q/52654634
has title: SQLAlchemy dynamic filter queries
linked to: http://stackoverflow.com/q/41305129
linked to: http://stackoverflow.com/q/39137911
linked to: http://stackoverflow.com/q/29885879
has body: I'm stuck on this database search problem: I have a PyQt5 widget with different checkBoxes. Each of them represents a column from my database. For example, 'worker_name' and 'department'. checkBoxes are placed near lineEdits, so user inserts some text into this lineEdit, than click on checkBox and 'Find' button. Let's say, user insert 'John' in lineEdit, than press 'worker_name' checkBox and gets all docs of this worker via session.query(Doc).filter_by('worker_name'=text_from_lineEdit) If user insert text in both lineEdits and pressed both checkBoxes ('worker_name' and 'department') query will look like this: session.query(Doc).filter_by('worker_name'=text_from_lineEdit, 'department'=text_from_lineEdit_2) But what if I have many checkBoxes (as many as columns in DB table) and i don't know which of them will be pressed and which are not. How should I form the query in that case ? I mean I will have 'wrk_name','department' and 'date' and user could search only by 'worker_name' or by 'worker_name' + 'date' or with all of the checkBoxes. Is there any way to form database query dynamically relying on which arguments are given and which are not to include them in 'filter_by'/'filter or just ignore. Please, share your ideas about possible implementation of such functionality. Thx for your time.
answer count: 1
linked to: http://stackoverflow.com/q/37336520
favorite count: 0
has comment: http://stackoverflow.com/comment/92253884
linked to: http://stackoverflow.com/q/19506105
duplicate of: http://stackoverflow.com/q/37336520
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52660279
linked to: http://stackoverflow.com/q/2921847
score: 1
has comment: http://stackoverflow.com/comment/92241156
tagged with: pyqt5
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/92263969
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52665767
has text: Sounds good, I'll have a look at it. Does introduce another dependency though. ;-)

http://stackoverflow.com/q/52673497
tagged with: sequencematcher
tagged with: difflib
answer count: 1
accepted answer: http://stackoverflow.com/a/52674640
has body: In an attempt to find common substrings between two strings, SequenceMatcher does not return all expected common substrings. s1 = '++%2F%2F+Prints+%22Hello%2C+World%22+to+the+terminal+window.%0A++++++++System.out.pr%29%3B%0A++++%7D%0A%7D%0ASample+program%0Apublic+static+voclass+id+main%28String%5B%5D+args%29+' s2 = 'gs%29+%7B%0A++++++++%2F' # The common substring are '+%', '%0A++++++++', '%s' and 'gs%29+' # but 'gs%29+' is not matched. import difflib as d seqmatch = d.SequenceMatcher(None,s1,s2) matches = seqmatch.get_matching_blocks() for match in matches: apos, bpos, matchlen = match print(s1[apos:apos+matchlen]) Output: +% %0A++++++++ %2 "gs%29+" is a common substring between s1 and s2, but it is not found by SequenceMatcher. Am I missing something? Thanks
has comment: http://stackoverflow.com/comment/92278624
tagged with: python
has answer: http://stackoverflow.com/a/52674640
type: AnsweredQuestion
has title: difflib sequence matcher missing common substrings
type: Question
has comment: http://stackoverflow.com/comment/92277976
has comment: http://stackoverflow.com/comment/92278041
score: 0

http://stackoverflow.com/comment/92289979
comment on: http://stackoverflow.com/q/52680611
has text: @pygo Thank you for your effort.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/92329139
comment on: http://stackoverflow.com/q/52701303
score: 0
type: Comment
type: QuestionComment
has text: But does "but it's not working fine as i want it" mean? Do you get an exception etc? Do you have sample data to make this reproducible?

http://stackoverflow.com/comment/92170502
type: QuestionComment
has text: The first mistake is using `sum` and `dict` as variable names. Don't shadow built-ins.
score: 1
comment on: http://stackoverflow.com/q/52618197
type: Comment

http://stackoverflow.com/comment/92279064
type: Comment
score: 0
has text: @Learner, I suggest you try all 3 ways and see which works best for you.
comment on: http://stackoverflow.com/a/52674741
type: AnswerComment

http://stackoverflow.com/a/52735372
has comment: http://stackoverflow.com/comment/92397690
has body: Short Answer: If you are more familiar with Convolutional Networks, you can thick of the size of the LSTM layer (128) is the equivalent to the size of a Convolutional layer. The 10 only means that the size of your input (lenght of your sequence is 10) Longer Answer: You can check this article for more detail article about RNNs. In the left image, a LSTM layer is represented with (xt) as the input with output (ht). The feedback arrow shows that there is some kind of memory inside the cell. In practice in Keras (right image), this model is "unrolled" to give the whole input xt in parallel to our layer. So when your summary is: lstm_1 (LSTM) (None, 10, 128) 91648 It means that your input sequence is 10 (x0,x1,x2,...,x9), and that the size of your LSTM is 128 (128 will be the dimension of your output ht)
score: 5
upvote count: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/103741213
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52734659
answers question: http://stackoverflow.com/q/52734659
has comment: http://stackoverflow.com/comment/92398731
type: Answer

http://stackoverflow.com/q/52654349
answer count: 3
upvote count: 0
has answer: http://stackoverflow.com/a/52654441
favorite count: 0
linked to: http://stackoverflow.com/q/944700
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52654421
has title: Getting nan using row function. However while comparing row with nan, condition is getting False
has answer: http://stackoverflow.com/a/52654466
has comment: http://stackoverflow.com/comment/92240332
downvote count: 1
type: Question
score: -1
has body: This is the output of half expression mentioned in the last: row['dep'] Out[302]: nan However I am not getting BU in the cell 17,5. if row['dep'] == 'nan': local.Cells(17,5).Value = "BU" Can anyone please help
tagged with: python-2.7

http://stackoverflow.com/a/52690370
has body: You probably wanted to write: read_yaml("config.yaml") Remember that a string is delimited by two quotes.
score: 0
has comment: http://stackoverflow.com/comment/92308335
answers question: http://stackoverflow.com/q/52690131
type: Answer
accepted answer of: http://stackoverflow.com/q/52690131
type: AcceptedAnswer

http://stackoverflow.com/comment/92388426
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52726463
has text: Yes I imported numpy for python3.6, but the problem was because I named a .py after a module, changing the .py name solved it but thanks for checking out my situation.

http://stackoverflow.com/comment/92241006
type: Comment
has text: This "https://adviseme.mit.edu/" is the secured one, if you want to access it, you need their certificate. Try accessing that site from a web browser like chrome or firefox.
comment on: http://stackoverflow.com/q/52654685
score: 1
type: QuestionComment

http://stackoverflow.com/comment/92279073
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52674741
has text: IOPub data rate exceeded. The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable `--NotebookApp.iopub_data_rate_limit`. I get the following error if I try with the last method (set difference) Current values: NotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec) NotebookApp.rate_limit_window=3.0 (secs)
type: AnswerComment

http://stackoverflow.com/a/52657505
answers question: http://stackoverflow.com/q/52657429
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52657429
has comment: http://stackoverflow.com/comment/92245645
has comment: http://stackoverflow.com/comment/92245628
has comment: http://stackoverflow.com/comment/92261953
type: AcceptedAnswer
upvote count: 3
has body: It doesn't look like df.Rolling will support this. Instead, can you resample to 1 sec intervals and then just concat every value with the row after it? You can then merge the result back using merge_asof: v = df.resample('1s').agg(''.join) pd.merge_asof(df, v.add(v.shift(-1)).rename({'mychart': 'res'}, axis=1), left_index=True, right_index=True) myvalue mychart res mytime 2018-01-01 14:34:12.340 1.0 a ab 2018-01-01 14:34:13.000 2.0 b b 2018-01-01 14:34:15.342 NaN c cd 2018-01-01 14:34:16.420 3.0 d d 2018-01-01 14:34:28.742 1.0 e NaN
has comment: http://stackoverflow.com/comment/92245619
type: Answer

tabs
type: Tag
tag name: tabs
tags question: http://stackoverflow.com/q/52609980

http://stackoverflow.com/comment/92368606
has text: For that specific case : `np.moveaxis(np.moveaxis(A,0,-1)[np.ix_(b,c,d)],-1,0)`. For the generic case, you might want to work with `slice`.
type: Comment
comment on: http://stackoverflow.com/q/52721198
score: 1
type: QuestionComment

http://stackoverflow.com/comment/92371917
type: Comment
type: QuestionComment
has text: There are quite a few options here: https://stackoverflow.com/questions/4002598/python-list-how-to-read-the-previous-element-when-using-for-loop
comment on: http://stackoverflow.com/q/52722938
score: 0

http://stackoverflow.com/q/52618450
has title: Getting dynamic set global variables from one module to another
has comment: http://stackoverflow.com/comment/92205574
has comment: http://stackoverflow.com/comment/92208403
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92208323
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/92172435
tagged with: import
type: Question
has body: I have two modules that do separate things. download.py downloads files to a specific directory create.py creates a job (text file) using the downloaded file paths from download.py The files downloaded could be any amount of files. I am able to download the files to a specific location fine, however, when create.py creates a job, it depends on the files paths from download.py. I can set a global variable like this in download.py: file_paths = None and when I import it in create.py and print it I can see it print out None. from download import file_paths print(file_paths) # None But this variable file_paths never gets updated. I am overriding and setting the variable once download is complete with the file paths, but when I call create.py again, it still prints out None. How can I get the updated value?
downvote count: 0

raspberry-pi
tags question: http://stackoverflow.com/q/52665317
tags question: http://stackoverflow.com/q/52747090
type: Tag
tags question: http://stackoverflow.com/q/52653576
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/52711780
tags question: http://stackoverflow.com/q/52690152
tags question: http://stackoverflow.com/q/52598031
tags question: http://stackoverflow.com/q/52722444
tags question: http://stackoverflow.com/q/52689685
tags question: http://stackoverflow.com/q/52735862
tags question: http://stackoverflow.com/q/52699157
tags question: http://stackoverflow.com/q/52665888
tags question: http://stackoverflow.com/q/52650799
tags question: http://stackoverflow.com/q/52616907
tags question: http://stackoverflow.com/q/52684900
tags question: http://stackoverflow.com/q/52707130
tags question: http://stackoverflow.com/q/52615425
tags question: http://stackoverflow.com/q/52666308
tags question: http://stackoverflow.com/q/52629543

http://stackoverflow.com/a/52708709
downvote count: 0
has comment: http://stackoverflow.com/comment/108564388
type: Answer
answers question: http://stackoverflow.com/q/52708341
upvote count: 7
has comment: http://stackoverflow.com/comment/108568446
accepted answer of: http://stackoverflow.com/q/52708341
score: 7
has body: The standard hacky way of deep-copying python objects should work. That is, using pickle. import pickle sr2 = pickle.loads(pickle.dumps(sr))
type: AcceptedAnswer

http://stackoverflow.com/a/52629910
answers question: http://stackoverflow.com/q/52629455
type: AcceptedAnswer
has body: you can join the rows and apply the FreqDist after tokenizing the sentence df.groupby('category')['sentence'].apply(lambda x: nltk.FreqDist(nltk.tokenize.word_tokenize(' '.join(x)))) Out: category a big 2.0 cat 2.0 dog 2.0 over 2.0 runs 2.0 c include 1.0 random 1.0 sentences 1.0 words 1.0 d including 1.0 one 1.0 this 1.0 Name: sentence, dtype: float64
type: Answer
score: 4
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52629455
upvote count: 5

http://stackoverflow.com/comment/92395875
score: 0
comment on: http://stackoverflow.com/q/52735515
has text: but numpy real doesn't seem to work there
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92340287
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52706982
has text: You can produce multiple strings, each formatted, but here you could just print the numbers directly with `print(*range(width))`.

http://stackoverflow.com/comment/92413154
has text: My theory since you don't provide data: your function label_sub_cat() is defined over your dataframe, so when you do data.apply(label_sub_cat(), ...) you're effectively doing data.apply('Other' ...) hence the error
comment on: http://stackoverflow.com/q/52744139
score: 0
type: Comment
type: QuestionComment

arima
tag name: arima
tags question: http://stackoverflow.com/q/52709452
type: Tag
tags question: http://stackoverflow.com/q/52716590
tags question: http://stackoverflow.com/q/52629820

http://stackoverflow.com/comment/92326449
has text: Why don't you just do `friend.stealth = 10`?
type: QuestionComment
comment on: http://stackoverflow.com/q/52699918
type: Comment
score: 1

http://stackoverflow.com/q/52677922
score: -1
type: Question
has title: How to save the following python output result to .csv format
has body: How can I save the result from this code to .csv format? import re import CSV text = open('example.txt').read() pattern = r'([0-9]+)[:]([0-9]+)[:](.*)' regex = re.compile(pattern) for match in regex.finditer(text): result = ("{},{}".format(match.group(2),match.group(3)))
downvote count: 2
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52677983
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52677983

http://stackoverflow.com/comment/92288535
comment on: http://stackoverflow.com/a/52668465
score: 0
type: AnswerComment
has text: `from test import moduletoimport` works, but `from moduletoimport import func` doesn't. That's very weird of PyCharm.
type: Comment

http://stackoverflow.com/comment/92327026
has text: Thanks Willem! Amazing!... :)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52699982
type: AnswerComment

http://stackoverflow.com/comment/92201353
comment on: http://stackoverflow.com/q/52633626
score: 0
type: Comment
type: QuestionComment
has text: I clarified what I need to do. T.Y. @ImportanceOfBeingErnest I would like to do it in a single command. T.Y.

http://stackoverflow.com/q/52736221
has answer: http://stackoverflow.com/a/53128184
answer count: 2
tagged with: pandas
downvote count: 0
has title: Pandas NaN value causing trouble when change values depending on other columns
favorite count: 0
has answer: http://stackoverflow.com/a/52736241
has comment: http://stackoverflow.com/comment/93150819
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/52736241
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/53128184
has body: why do pandas NaN values sometime typed as numpy.float64, and sometimes float? This is so confusing when I want to use function and change values in a dataframe depending on other columns example: A B C 0 1 NaN d 1 2 a s 2 2 b s 3 3 c NaN I have a def to change value of column C def change_val(df): if df.A==1 and df.B==np.nan: return df.C else: return df.B Then I apply this function onto column C df['C']=df.apply(lambda x: change_val(x),axis=1) Things go wrong on df.B==np.nan, how do I correctly express this please? Desired result: A B C 0 1 NaN d 1 2 a a 2 2 b b 3 3 c c

http://stackoverflow.com/q/52713462
tagged with: matplotlib
has body: I have a dataframe and a plot if data1.empty: pass else: ax = data1['30'].value_counts(sort=True).plot(kind='bar',width=0.1, figsize=(10,8), color="red", fontsize=13,position=1) At times data1 becomes empty. Now I am using a pass. But I would like to change pass with some code that will assign the count as zero and will plot as 0 in graph.
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/92353663
tagged with: pandas
has comment: http://stackoverflow.com/comment/92353746
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52714167
has comment: http://stackoverflow.com/comment/92353638
tagged with: python
has title: How to set pandas value count to 0, if data frame is empty
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92353162
has comment: http://stackoverflow.com/comment/92353201
downvote count: 2
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52714167

http://stackoverflow.com/comment/92184862
type: QuestionComment
has text: [`inspect`](https://docs.python.org/3/library/inspect.html) is part of the Python STD library, you don't need to install it externally. Maybe `pyenv` failed in building up the right environment. Did you use `pyenv` to install Python 3.6?
comment on: http://stackoverflow.com/q/52623168
score: 0
type: Comment

http://stackoverflow.com/q/52732675
tagged with: numpy
answer count: 1
favorite count: 0
tagged with: python-3.x
downvote count: 5
type: UnansweredQuestion
tagged with: python
upvote count: 0
score: -5
has comment: http://stackoverflow.com/comment/92391653
has answer: http://stackoverflow.com/a/52735128
type: Question
has body: I want to create an 2D array for an input asking no of nodes and for each node accepting 2 value x coordinate and y coordinate from user and generating its 2D array where consist 3 column node, x coordinate, y coordinate. Input: enter the number of nodes:3 10 12 12 13 5 6 output [A 10 12 B 12 13 C 5 6 ]
has title: i want to create a 2D array which consist of nodes name and its x y coordinate using numpy python

http://stackoverflow.com/a/52712341
has body: 1st solution is treat none as character not NaN , the we using eq with sum (if need drop row using sum(axis=1)) df.loc[:,df.eq('none').sum().lt(2)] Out[559]: # of customers Category 0 30 none 1 none women 2 50 kids 2nd solution is assuming your none as np.nan and using dropna with thresh #df=df.replace('none',np.nan) df.dropna(axis=0,thresh=2)#here thresh is Require that many non-NA values. Out[563]: # of customers Category Sales 2 50 kids 40
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/92350664
answers question: http://stackoverflow.com/q/52712288
accepted answer of: http://stackoverflow.com/q/52712288

http://stackoverflow.com/comment/92123262
comment on: http://stackoverflow.com/q/52594018
score: 0
has text: @eyllanesc You are right, the description was wrong, I corrected it. Maybe choice of using QHBoxLayout is not right, what do you suggest
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52668721
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52668124
answers question: http://stackoverflow.com/q/52668124
has comment: http://stackoverflow.com/comment/110078396
has comment: http://stackoverflow.com/comment/92283381
has body: well... this works txt = text.translate(str.maketrans(string.punctuation, ' ' * len(string.punctuation))).replace(' '*4, ' ').replace(' '*3, ' ').replace(' '*2, ' ').strip()
has comment: http://stackoverflow.com/comment/107928473

http://stackoverflow.com/a/53270183
type: Answer
answers question: http://stackoverflow.com/q/52730864
has body: In writing my other answer, I slowly came around to the idea that the OP's algorithm might be easier to implement with an approach that focuses on the jobs (which can be different), instead of the people (which are all the same). Here's a solution that uses the job-centric approach: from collections import Counter import numpy as np import pandas as pd def assignJob(job, assignedix, areasPerPerson): for i in range(len(assignedix)): if (areasPerPerson - len(assignedix[i])) &gt;= len(job): assignedix[i].extend(job) return True else: return False def allocatePeople(df, areasPerPerson=3): areas = df['Area'].values times = pd.to_datetime(df['Time']).values peopleUniq = df['Person'].unique() npeople = int(np.ceil(areas.size / float(areasPerPerson))) # search for repeated areas. Mark them if the next repeat occurs within an hour ixrep = np.argmax(np.triu(areas.reshape(-1, 1)==areas, k=1), axis=1) holds = np.zeros(areas.size, dtype=bool) holds[ixrep.nonzero()] = (times[ixrep[ixrep.nonzero()]] - times[ixrep.nonzero()]) &lt; np.timedelta64(1, 'h') jobs =[] _jobdict = {} for i,(area,hold) in enumerate(zip(areas, holds)): if hold: _jobdict[area] = job = _jobdict.get(area, []) + [i] if len(job)==areasPerPerson: jobs.append(_jobdict.pop(area)) elif area in _jobdict: jobs.append(_jobdict.pop(area) + [i]) else: jobs.append([i]) jobs.sort() assignedix = [[] for i in range(npeople)] for job in jobs: if not assignJob(job, assignedix, areasPerPerson): # break the job up and try again for subjob in ([sj] for sj in job): assignJob(subjob, assignedix, areasPerPerson) df = df.copy() for i,aix in enumerate(assignedix): df.loc[aix, 'Person'] = peopleUniq[i] return df This version of allocatePeople has also been extensively tested and passes all of the same checks described in my other answer. It does have more looping than my other solution, so it is likely to be slightly less efficient (though it'll only matter if your dataframe is very large, say 1e6 rows and up). On the other hand, it is …
score: 0

http://stackoverflow.com/a/52674610
has body: Here is an example dataset import pandas as pd df = pd.DataFrame([[1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3], ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B']]).T df.columns = ['trip_id', 'user_id'] print(df) Gives: trip_id user_id 0 1 A 1 1 B 2 1 C 3 2 A 4 2 B 5 2 C 6 3 A 7 3 B 8 3 C 9 3 A 10 3 B I think what you're asking for is: df.groupby(['trip_id', 'user_id']).size() trip_id user_id 1 A 1 B 1 C 1 2 A 1 B 1 C 1 3 A 2 B 2 C 1 dtype: int64 Am I correct?
score: 0
has comment: http://stackoverflow.com/comment/92296221
type: Answer
answers question: http://stackoverflow.com/q/52674510

http://stackoverflow.com/comment/92122156
comment on: http://stackoverflow.com/q/52593508
has text: Possible duplicate of [Applying my custom function to a data frame python](https://stackoverflow.com/questions/51505187/applying-my-custom-function-to-a-data-frame-python)
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/comment/92226958
has text: Please post the error and the code that caused it as text instead of a screenshot, this is more likely to attract people to answer your question.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52646836

http://stackoverflow.com/a/52712120
score: 1
answers question: http://stackoverflow.com/q/52712062
upvote count: 1
type: Answer
downvote count: 0
has body: &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; veg_type = ['Urban','Urban','Forest','OpenForest','Arboretum'] &gt;&gt;&gt; veg_density = [0.5,0.6,0.1,0,0.9] &gt;&gt;&gt; sums = defaultdict(int) &gt;&gt;&gt; for name,value in zip(veg_type,veg_density): ... sums[name] += value ... &gt;&gt;&gt; sums defaultdict(&lt;class 'int'&gt;, {'Urban': 1.1, 'Forest': 0.1, 'OpenForest': 0, 'Arboretum': 0.9})

http://stackoverflow.com/a/52716540
accepted answer of: http://stackoverflow.com/q/52716413
score: 0
has body: Well You need to simply change the return in check function to yield thereby converting it to a generator and we can use the next function to iterate through the output def fac(n) : f = [] for i in range(2,int(n/2)) : if n % i == 0 : f.append(i) return f def check(n) : for j in fac(n) : g=[] g.append(n) g.append(j) g.append(int(n/j)) x = int("".join(map(str, g))) yield x print("using for loop") #print (check(28)) for i in check(28): print(i) print("Using next function") n=check(28) print(next(n)) print(next(n)) print(next(n)) OUTPUT using for loop 28214 2847 2874 Using next function 28214 2847 2874
answers question: http://stackoverflow.com/q/52716413
type: Answer
has comment: http://stackoverflow.com/comment/92359313
has comment: http://stackoverflow.com/comment/92358978
has comment: http://stackoverflow.com/comment/92359003
type: AcceptedAnswer

http://stackoverflow.com/q/52600959
type: UnansweredQuestion
tagged with: fork
has answer: http://stackoverflow.com/a/52734728
has body: I frequently find myself writing programs in Python that construct a large (megabytes) read-only data structure and then use that data structure to analyze a very large (hundreds of megabytes in total) list of small records. Each of the records can be analyzed in parallel, so a natural pattern is to set up the read-only data structure and assign it to a global variable, then create a multiprocessing.Pool (which implicitly copies the data structure into each worker process, via fork) and then use imap_unordered to crunch the records in parallel. The skeleton of this pattern tends to look like this: classifier = None def classify_row(row): return classifier.classify(row) def classify(classifier_spec, data_file): global classifier try: classifier = Classifier(classifier_spec) with open(data_file, "rt") as fp, \ multiprocessing.Pool() as pool: rd = csv.DictReader(fp) yield from pool.imap_unordered(classify_row, rd) finally: classifier = None I'm not happy with this because of the global variable and the implicit coupling between classify and classify_row. Ideally, I would like to write def classify(classifier_spec, data_file): classifier = Classifier(classifier_spec) with open(data_file, "rt") as fp, \ multiprocessing.Pool() as pool: rd = csv.DictReader(fp) yield from pool.imap_unordered(classifier.classify, rd) but this does not work, because the Classifier object usually contains objects which cannot be pickled (because they are defined by extension modules whose authors didn't care about that); I have also read that it would be really slow if it did work, because the Classifier object would get copied into the worker processes on every invocation of the bound method. Is there a better alternative? I only care about 3.x.
type: Question
tagged with: python-multiprocessing
tagged with: multiprocessing
score: 12
has title: Avoid global variables for unpicklable shared state among multiprocessing.Pool workers
has answer: http://stackoverflow.com/a/52685345
upvote count: 12
downvote count: 0
answer count: 3
linked to: http://stackoverflow.com/q/52495824
has answer: http://stackoverflow.com/a/52689622
tagged with: python
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/52685989
upvote count: 2
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/92300718
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92300972
type: Answer
has comment: http://stackoverflow.com/comment/92300874
has comment: http://stackoverflow.com/comment/92299704
answers question: http://stackoverflow.com/q/52685928
has comment: http://stackoverflow.com/comment/92299971
accepted answer of: http://stackoverflow.com/q/52685928
has body: Well, in your code: a=1 b=2 c=a c=b Before you assign c to b's value and after you assign c to a's value, c will be a. And after, at the end of the code, c will be b, because you're reassigning the variable. The second assignment, basically creates new variable, without knowing that the variable is there already, so it will just do it but no way of accessing previous holding-value of the varaible
has comment: http://stackoverflow.com/comment/92300289

http://stackoverflow.com/comment/92147297
type: Comment
has text: It is possible - your log file is just a white space separated file and you could turn that into a csv file easily enough if that helps (or not). What code have you tried already? What makes you think it's not possible, or what problems have you already encountered?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52606526

http://stackoverflow.com/q/52738537
type: AnsweredQuestion
has body: Sorry for my english. I want to create a decorator method that can check each step methods and write it db. This is my method: class Test: @StepStatusManager.logger_steps("GET_LIST") # TypeError: logger_steps() missing 1 required positional argument: 'type' def get_mails(self): print("GET_MAIL") This is my decorator class: class StepStatusManager: def __init__(self): self.db = DB() def logger_steps(self, type): def logger_steps(func): @functools.wraps(func) def wrapper(*args): try: func(*args) self.db.setStatus(type) except BaseException as e: print(e) return wrapper return logger_steps
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/12179271
type: Question
accepted answer: http://stackoverflow.com/a/52738702
linked to: http://stackoverflow.com/q/136097
answer count: 1
downvote count: 0
tagged with: decorator
favorite count: 0
has title: decorator inside class Python
has comment: http://stackoverflow.com/comment/92402695
has answer: http://stackoverflow.com/a/52738702
tagged with: python

http://stackoverflow.com/a/52659988
has body: ITT can be disabled by in the above cmake: -D WITH_ITT=OFF \
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52658083
accepted answer of: http://stackoverflow.com/q/52658083
downvote count: 0

http://stackoverflow.com/a/52601752
has body: The files list in the tuples returned by os.walk contains only the file names without the path names, so you should join it with the path name before you call os.path.abspath: print os.path.abspath(os.path.join(root, file))
accepted answer of: http://stackoverflow.com/q/52601725
answers question: http://stackoverflow.com/q/52601725
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92137875
score: 1

http://stackoverflow.com/comment/116956104
comment on: http://stackoverflow.com/q/52651665
score: 0
has text: @ArielB we have created our own job, but now we would maybe have chosen DMS
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92423264
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52733838
has text: If you add e.g. `print("{}".format(t.hour))` what does it show?

http://stackoverflow.com/q/52594544
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/52594691
has answer: http://stackoverflow.com/a/52595127
has answer: http://stackoverflow.com/a/52594648
has title: Pandas: Replacing '-' when used as a zero but not when used as a negative
tagged with: dataframe
has answer: http://stackoverflow.com/a/52594795
has comment: http://stackoverflow.com/comment/92124342
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/52594795
accepted answer: http://stackoverflow.com/a/52594691
favorite count: 0
has answer: http://stackoverflow.com/a/52594706
answer count: 5
has body: I am reading a csv file into a pandas dataframe. df= pd.read_csv("table.csv", encoding = 'ISO-8859-1') I have a column named 'value' which contains '-' when the value is nil. My aim is to filter out all rows where the value in this column is nil. However the sign is also contained when the value is a negative. When I try: df['value'] = df['value'].str.replace(',', '') df['value'] = df['value'].str.replace('-', '0') df['value'] = df['value'].astype(str).astype(float) df= df[df['value'] !=0] All negative numbers become positive as I am stripping out the negative sign. However, if I don't convert '-' to '0' then I get the error: ValueError: could not convert string to float: '-' Thanks for any help.
upvote count: 1
tagged with: python

http://stackoverflow.com/q/52590059
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52600964
type: UnansweredQuestion
tagged with: python
tagged with: amazon-dynamodb
upvote count: 1
downvote count: 1
type: Question
has title: Format Query results while querying
tagged with: boto3
tagged with: amazon-web-services
score: 0
answer count: 1
has body: My data is structured as follows, and for simple queries it does return it in this way: { 'props':{ 'prop1':'value1', 'prop2':'value2', 'prop3':'value3', }, 'some_id':'123', 'timestamp':'1970-01-02 23:25:37' } Code used for querying: response = table.query( KeyConditionExpression=Key('some_id').eq(some_id), ProjectionExpression="#p.#p1, #s", ExpressionAttributeNames={'#p': 'props', '#p1': 'prop1', '#s': 'some_id'} ) Result with current code: { 'some_id': '123', 'props': { { 'prop1':'value1' } } } But my desired result is flattened: { 'some_id': '123', 'prop1': 'value1' } So the question is - how do I get the desired result with the query, not with python after getting the resuts.

http://stackoverflow.com/q/52653931
has title: Authenticate with Kubernetes cluster with token
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: kubernetes
tagged with: python
upvote count: 3
has body: The way my environment is setup (AWS EKS) is that in my ~/.kube/config the user has an exec configuration to make a call to aws-iam-authenticator. This is so that when kubectl is run, it'll request the token to auth to the Kubernetes cluster. I'm currently writing a client application that will interact with the Kubernetes API. This is written in Python, using the official Python client. When doing any of the examples, I get the error that system:anonymous isn't allowed to perform a certain operation (e.g. list pods). I think the root of the problem is that I need to pass a token from aws-iam-authenticator to my client requests. Unfortunately I can't seem to figure out how to pass this token in with the Python client for Kubernetes. I see this snippet but I get an error that api_key attribute isn't part of the configuration module (and sure enough, it isn't). How am I supposed to inject the token into my requests from the Python client for Kubernetes? Thanks in advance!
has answer: http://stackoverflow.com/a/52654167
type: Question
score: 3

http://stackoverflow.com/q/52689640
type: Question
has comment: http://stackoverflow.com/comment/95679146
tagged with: python-2.7
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/52689667
downvote count: 3
has comment: http://stackoverflow.com/comment/92306212
tagged with: python
linked to: http://stackoverflow.com/q/3776275
tagged with: dictionary
upvote count: 0
duplicate of: http://stackoverflow.com/q/3776275
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1024847
has body: students = {} name = input("Give me the student name(key): ") grade = input("What is their Grade(value): ") '(put in to dictionary key=name and value = grade print all students and their grades from dictionary"
has answer: http://stackoverflow.com/a/52690045
score: -3
has title: In Python,how can I add to a dictionare from raw_input,for both key and value? M
has comment: http://stackoverflow.com/comment/92306193

http://stackoverflow.com/q/52647703
score: 0
tagged with: cron
tagged with: google-app-engine
tagged with: python
has comment: http://stackoverflow.com/comment/92238040
has answer: http://stackoverflow.com/a/52653404
has body: I have been trying to run a cron job with GAE (code developed in Python), but when I trigger the job, it fails without any error message -- I can't find anything at all in the logs. This is happening for a service for which I'm using the flexible environment. This is the structure of my files: my_service.yaml looks like this: service: my_service runtime: custom env: flex env_variables: a: b: the my_service.app looks like this: from __future__ import absolute_import from flask import Flask from flask import request import logging import datetime import os import tweepy from google.cloud import datastore import time logging.basicConfig(level=logging.INFO) app = Flask(__name__) @app.route('/Main') def hello(): """A no-op.""" return 'nothing to see.' @app.route('/my_service') def get_service(): is_cron = request.headers.get('X-Appengine-Cron', False) logging.info("is_cron is %s", is_cron) # Comment out the following test to allow non cron-initiated requests. if not is_cron: return 'Blocked.' ## data scraping and saving in Datastore return 'Done.' @app.errorhandler(500) def server_error(e): logging.exception('An error occurred during a request.') return """ An internal error occurred: &lt;pre&gt;{}&lt;/pre&gt; See logs for full stacktrace. """.format(e), 500 if __name__ == '__main__': app.run(host='127.0.0.1', port=8080, debug=True) Then I have a dispatch.yaml with this structure: dispatch: - url: "*/my_service*" service: my_service And a cron.yaml: cron: - description: run my service url: /my_service schedule: 1 of month 10:00 target: my_service Not sure what I'm doing wrong here. EDIT A bit of context. This is something I'm editing starting from this repo. The service called backend that is defined in there works perfectly (it has also the same schedule in the cron job as my_service but when I trigger it in a day different from the one in which it's scheduled, it works just fine). What I did was to create an additional service with its own yaml file, which looks exactl…
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52653404
has answer: http://stackoverflow.com/a/52649965
has comment: http://stackoverflow.com/comment/92251690
accepted answer: http://stackoverflow.com/a/52649965
has comment: http://stackoverflow.com/comment/92234387
has comment: http://stackoverflow.com/comment/92238103
answer count: 2
has title: GAE - cron job failing, with no error message in logs
has comment: http://stackoverflow.com/comment/92237993

http://stackoverflow.com/a/52705647
has body: You can't access the data attribute of the request, because the authentication object is applied to a requests.PreparedRequest() instance, which has no .data attribute. The normal flow for a Session.request() call (used by all the request.&lt;method&gt; and session.&lt;method&gt; calls), is as follows: A Request() instance is created with all the same arguments as the original call The request is passed to Session.prepare_request(), which merges in session-stored base values with the arguments of the original call first, then A PreparedRequest() instance is created The PreparedRequest.prepare() method is called on that prepared request instance, passing in the merged data from the Request instance and the session. The prepare() method calls the various self.prepare_* methods, including PreparedRequest.prepare_auth(). PreparedRequest.prepare_auth() calls auth(self) to give the authentication object a chance to attach information to the request. Unfortunately for you, at no point during this flow will the original data mapping be available to anyone else but PreparedRequest.prepare() and PreparedRequest.prepare_body(), and in those methods the mapping is a local variable. You can't access it from the authentication object. Your options are then: To decode the body again, and call prepare_body() with the updated mapping. To not use an authentication object, but use the other path from my answer; to explicitly create a prepared request and manipulate data first. To play merry hell with the Python stack and extract locals from the prepare() method that is two frames up. I really can't recommend this path. To keep the authentication method encapsulated nicely, I'd go with decoding / re-encoding; the latter is simple enough by reusing PreparedRequest.prepare_body(): import base64 import hashlib import hmac import time try: # Python 3 from urllib.parse import parse_qs except ImportError: # Python 2 from urlparse import parse_qs from requests import AuthBase URL_ENCODED = 'a…
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/52705158
accepted answer of: http://stackoverflow.com/q/52705158
type: AcceptedAnswer
type: Answer
upvote count: 4

http://stackoverflow.com/a/52619484
has body: Here are 2 solutions that you can use. The first solution will collect every row positions with your word and the word position into them. wolf = [['fat', 'small'],[1, 3]] def get_positions(lists, word): i = 0 for list in lists: if word in list: index = list.index(word) print "List Position: " + str(i) + "\nWord Postion: " + str(index) + "\n" i += 1 get_positions(wolf, "small") Ouput: List Position: 0 Word Postion: 1 Here is an example with multiple rows with that word. example2 = [['fat', 'small'],[1, 'fat']] get_positions(example2, "fat") Output List Position: 0 Word Postion: 0 List Position: 1 Word Postion: 1 The second solution, you have to provide the array, nested array position and the word, and it will return you the index position of this nested array: wolf = [['fat', 'small'],[1, 3]] def get_positions(lists, list_index, word): result = False if word in lists[list_index]: result = lists[list_index].index(word) return result print get_positions(wolf, 0, "small") Output: 1
answers question: http://stackoverflow.com/q/52619153
has comment: http://stackoverflow.com/comment/92874463
accepted answer of: http://stackoverflow.com/q/52619153
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/92593752
has comment: http://stackoverflow.com/comment/92181671
has comment: http://stackoverflow.com/comment/92173120
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52741293
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I'm trying to understand OOP in Python and I have this "non-pythonic way of thinking" issue. I want a method for my class that verifies the type of the argument and raises an exception if it isn't of the proper type (e.g. ValueError). The closest to my desires that I got is this: class Tee(object): def __init__(self): self.x = 0 def copy(self, Q : '__main__.Tee'): self.x = Q.x def __str__(self): return str(self.x) a = Tee() b = Tee() print(type(a)) # &lt;class '__main__.Tee'&gt; print(isinstance(a, Tee)) # True b.x = 255 a.copy(b) print(a) # 255 a.copy('abc') # Traceback (most recent call last): [...] # AttributeError: 'str' object has no attribute 'x' So, even that I tried to ensure the type of the argument Q in my copy method to be of the same class, the interpreter just passes through it and raises an AttributeError when it tries to get a x member out of a string. I understand that I could do something like this: [...] def copy(self, Q): if isinstance(Q, Tee): self.x = Q.x else: raise ValueError("Trying to copy from a non-Tee object") [...] a = Tee() a.copy('abc') # Traceback (most recent call last): [...] # ValueError: Trying to copy from a non-Tee object But it sounds like a lot of work to implement everywhere around classes, even if I make a dedicated function, method or decorator. So, my question is: is there a more "pythonic" approach to this? I'm using Python 3.6.5, by the way.
has answer: http://stackoverflow.com/a/52741438
type: Question
tagged with: oop
has answer: http://stackoverflow.com/a/52742015
answer count: 2
accepted answer: http://stackoverflow.com/a/52741438
possible better answer: http://stackoverflow.com/a/52742015
tagged with: types
downvote count: 0
has comment: http://stackoverflow.com/comment/92407918
has title: Python OOP, type verification for arguments within methods / classes
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/92139982
type: Comment
type: QuestionComment
has text: I'm afraid that Stack Overflow is not suited to broad questions like this. We can only really help with specific programming issues. That said, I'm not sure where best to ask this kind of question sorry.
comment on: http://stackoverflow.com/q/52602917
score: 0

http://stackoverflow.com/comment/92287412
has text: It would be easier to answer this question if you could concentrate on one approach. For example, since you're posting under `python-asyncio`, the second one using asyncio websockets.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52652755

http://stackoverflow.com/comment/92176785
score: 0
has text: Thanks Dithon for your effort. However, I wanted to use "try/except" to practice that as well - I was able to do "if/else" way. Best, M
comment on: http://stackoverflow.com/a/52621414
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52593023
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17071871
score: 1
type: Question
has answer: http://stackoverflow.com/a/52593059
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52593135
downvote count: 0
has title: Dropping rows of panadas dataframe based on conditional
favorite count: 0
possible better answer: http://stackoverflow.com/a/52593135
accepted answer: http://stackoverflow.com/a/52593059
has body: Im sure this has been asked before but i cannot phrase it in a way such that I find a similar question. What I would like to do is drop rows of my dataframe where rows with the same item name that all have value of 0 are dropped. For example. One of my columns is the 'itemname' and the other is the 'value'. the 'itemname' may be repeated many times. I want to check for each 'itemname', if all other items with the same name have value 0, then drop these rows I know this should be simple, however I cannot get my head around it. Just to make it clearer, here itemname value 0 a 0 1 b 100 2 c 0 3 a 0 4 b 75 5 c 90 As all a items have a value of 0, They should be dropped. itemname value 1 b 100 2 c 0 3 b 75 4 c 90 Hope that makes sense. I check if someone else has asked something similar and couldnt find something in this case.
upvote count: 1
tagged with: python

http://stackoverflow.com/q/52609356
score: 1
has comment: http://stackoverflow.com/comment/92156329
type: Question
tagged with: ibm-cloud-infrastructure
tagged with: ibm-cloud
has comment: http://stackoverflow.com/comment/92153117
upvote count: 1
has comment: http://stackoverflow.com/comment/92155024
has comment: http://stackoverflow.com/comment/92162504
answer count: 1
favorite count: 0
tagged with: python
has body: I'm trying to retrieve license information (license name, license version, expiry date, etc...) that are associated with each hardware components (instances) under a specific account ID. Can someone help how to list down all the hardware components associated under a specific account ID and all the software licenses attached to each hardware component?
has title: How to retrieve all the licenses associated with an account using Python API
has answer: http://stackoverflow.com/a/52617098
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52617098
downvote count: 0

http://stackoverflow.com/q/52673468
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92277218
answer count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/92277154
type: Question
has comment: http://stackoverflow.com/comment/92277264
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/92276937
has body: User defined button that will hold an image and is moveable causes screen smearing when moved to the left and causes a screen smear to the right of the widget. Any ideas? Image of smearing to the right of the playing card - vertical grey lines. As i stated this only happens when moving the button to the left. #!/usr/bin/python3 # -*- coding: utf-8 -*- from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from functools import partial import datetime,psutil,sys class playingCard(QPushButton): def __init__(self, Text = '', parent = None): super(playingCard, self).__init__() self.ftop = 10 self.fleft = 10 self.fwidth = 87 self.fheight = 124 self.initUI() def initUI(self): self.setGeometry(self.fleft, self.ftop, self.fwidth+2, self.fheight+2) self.setText('') pixmap = QPixmap('clubs1.png') pixmap = pixmap.scaled(self.fwidth,self.fheight, Qt.KeepAspectRatio, Qt.FastTransformation) buttonicon = QIcon(pixmap) self.setIcon(buttonicon) self.setIconSize( QSize(self.fwidth,self.fheight)) self.setFixedSize( QSize(self.fwidth+2,self.fheight+2)) def mousePressEvent(self, event): self.__mousePressPos = None self.__mouseMovePos = None if event.button() == Qt.LeftButton: self.__mousePressPos = event.globalPos() self.__mouseMovePos = event.globalPos() super(playingCard, self).mousePressEvent(event) def mouseMoveEvent(self, event): if event.buttons() == Qt.LeftButton: # adjust offset from clicked point to origin of widget currPos = self.mapToGlobal(self.pos()) globalPos = event.globalPos() diff = globalPos - self.__mouseMovePos newPos = self.mapFromGlobal(currPos + diff) self.move(newPos) self.__mouseMovePos = globalPos super(playingCard, self).mouseMoveEvent(event) def mouseReleaseEvent(self, event): if self.__mousePressPos is not None: moved = event.globalPos() - self.__mousePressPos if moved.manhattanLength() &gt; 3: event.ignore() return super(playingCard, self).mouseReleaseEvent(event) class Example(QMainWindow): def __init__(self): super().__init__()…
has title: PyQt5 Moveable button causes screen smear

http://stackoverflow.com/q/52641927
downvote count: 4
type: AnsweredQuestion
has body: EX:- Input Word = "නමුත්" Expected output = ['න','මු','ත්']
has comment: http://stackoverflow.com/comment/92216696
favorite count: 0
accepted answer: http://stackoverflow.com/a/52642119
type: Question
has answer: http://stackoverflow.com/a/52642119
has title: How to separate Sinhala letters from Sinhala words using python?
upvote count: 1
has comment: http://stackoverflow.com/comment/92216193
answer count: 1
has comment: http://stackoverflow.com/comment/92216154
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92217636
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/92216848

http://stackoverflow.com/comment/92292927
type: QuestionComment
comment on: http://stackoverflow.com/q/52682226
score: 0
has text: are grades represented as number of A, B, C's, etc.?
type: Comment

http://stackoverflow.com/a/52723213
answers question: http://stackoverflow.com/q/52722934
upvote count: 1
has body: You aren't providing enough bins. Though your max year is 2018 because you have dates that should be grouped with 2019, you need to increase the maximum year by 1. Similarly, you should subtract 1 from the minimum year. y_max = data.year.max() + 1 y_min = data.year.min() - 1 Now you will have the correct bins and labels that span your entire dataset: pd.date_range(str(y_min), str(y_max+1), freq='BAS-JUL') #DatetimeIndex(['2007-07-02', '2008-07-01', '2009-07-01', '2010-07-01', '2011-07-01', # '2012-07-02', '2013-07-01', '2014-07-01', '2015-07-01', # '2016-07-01', '2017-07-03', '2018-07-02', '2019-07-01'], # dtype='datetime64[ns]', freq='BAS-JUL') labels = [str(x) + ' - ' + str(x+1) for x in np.arange(y_min, y_max, 1)] #['2007 - 2008', # '2008 - 2009', # '2009 - 2010', #... # '2017 - 2018', # '2018 - 2019']
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52722934
type: Answer

http://stackoverflow.com/a/52672358
has comment: http://stackoverflow.com/comment/92308073
has comment: http://stackoverflow.com/comment/92362910
has comment: http://stackoverflow.com/comment/92306426
has comment: http://stackoverflow.com/comment/92308174
has comment: http://stackoverflow.com/comment/92306356
score: 0
has comment: http://stackoverflow.com/comment/92306487
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52671308
has comment: http://stackoverflow.com/comment/92335052
answers question: http://stackoverflow.com/q/52671308
type: Answer
has comment: http://stackoverflow.com/comment/92307321
has comment: http://stackoverflow.com/comment/92305794
has comment: http://stackoverflow.com/comment/92364823
has comment: http://stackoverflow.com/comment/92306308
has body: Here's one with maxisland_start_len_mask - # https://stackoverflow.com/a/52718782/ @Divakar def maxisland_start_len_mask(a, fillna_index = -1, fillna_len = 0): # a is a boolean array pad = np.zeros(a.shape[1],dtype=bool) mask = np.vstack((pad, a, pad)) mask_step = mask[1:] != mask[:-1] idx = np.flatnonzero(mask_step.T) island_starts = idx[::2] island_lens = idx[1::2] - idx[::2] n_islands_percol = mask_step.sum(0)//2 bins = np.repeat(np.arange(a.shape[1]),n_islands_percol) scale = island_lens.max()+1 scaled_idx = np.argsort(scale*bins + island_lens) grp_shift_idx = np.r_[0,n_islands_percol.cumsum()] max_island_starts = island_starts[scaled_idx[grp_shift_idx[1:]-1]] max_island_percol_start = max_island_starts%(a.shape[0]+1) valid = n_islands_percol!=0 cut_idx = grp_shift_idx[:-1][valid] max_island_percol_len = np.maximum.reduceat(island_lens, cut_idx) out_len = np.full(a.shape[1], fillna_len, dtype=int) out_len[valid] = max_island_percol_len out_index = np.where(valid,max_island_percol_start,fillna_index) return out_index, out_len def maxisland_start_len(a, trigger_val, comp_func=np.greater): # a is 2D array as the data mask = comp_func(a,trigger_val) return maxisland_start_len_mask(mask, fillna_index = -1, fillna_len = 0) Sample run - In [169]: a Out[169]: array([[ 1, 0, 3], [ 2, 7, 3], [ 6, 8, 4], [ 8, 6, 8], [ 7, 1, 6], [ 3, 7, 8], [ 2, 5, 8], [ 3, 3, 0], [ 6, 5, 0], [10, 3, 8], [ 2, 3, 3], [ 1, 7, 0], [ 0, 0, 4], [ 2, 3, 2]]) # Per column results In [170]: row_index, length = maxisland_start_len(a, 5) In [172]: row_index Out[172]: array([2, 1, 3]) In [173]: length Out[173]: array([3, 3, 4])
has comment: http://stackoverflow.com/comment/92307283
has comment: http://stackoverflow.com/comment/92305913

http://stackoverflow.com/a/52646451
upvote count: 2
answers question: http://stackoverflow.com/q/52646004
accepted answer of: http://stackoverflow.com/q/52646004
type: AcceptedAnswer
downvote count: 0
has body: The reason of such behaviour is that all references in list points to the same dict. Line j['c'] = test_dict doesn't create copy of dictionary, but just make j['c'] refer to test_dict. To get expected result you need change this line to: j['c'] = test_dict.copy(). It will make deep copy of test_dict and assign it to j['c'].
type: Answer
score: 2

http://stackoverflow.com/comment/92397099
type: QuestionComment
comment on: http://stackoverflow.com/q/52732145
score: 0
type: Comment
has text: I want to create a custom model subclassing model. According to tf.keras guide, I specify the layers in init method and hook up them with input into a whole network in call method. The loss function is required when compiling the model. The catch is model compiling happens after init but before call. Which means by then the last Dense layer haven't got its dimensions and therefore the weight matrix is not available. Thus I can't pass SampledSoftmax the right parameters to obtain the loss function before compiling model. It forms a cycle I can't break.